ISSUE DESCRIPTION linter: no-unused-vars false positive when constructor parameter…
- User
ISSUE DESCRIPTION
linter: no-unused-vars false positive when constructor parameter property shadows an imported identifier used in its own decorator
What version of Oxlint are you using?
1.65.0 (also reproduces on 1.30.0)
What command did you run?
oxlint test.tsWhat does your
.oxlintrc.json(oroxlint.config.ts) config file look like?// default (no config file)What happened?
When a TypeScript constructor parameter property has the same name as an outer binding (import or
const), and that outer binding is used in the parameter's own decorator expression (e.g.@Inject(foo.KEY)), oxlint'sno-unused-varsreports the outer binding as declared but never used.This is a false positive. Parameter decorators are evaluated at class-decoration time in the enclosing class scope, before any parameter binding exists in the parameter scope. So
fooinside@Inject(foo.KEY)resolves to the outer binding, not to the same-named parameter property.This pattern is extremely common in NestJS code, where
@Inject(someConfig.KEY)is used to injectregisterAs(...)-style typed configs and the constructor parameter property is typically named after the config. The false positive forces a churn-y workaround: either alias the import (import { foo as _foo }) or rename the parameter property.Minimal reproduction
const foo = { KEY: 'token' }; declare function Inject(token: unknown): ParameterDecorator; export class C { constructor(@Inject(foo.KEY) private readonly foo: number) {} }Actual
! eslint(no-unused-vars): Variable 'foo' is declared but never used. Unused variables should start with a '_'. ,-[test.ts:1:7] 1 | const foo = { KEY: 'token' }; : ^|^ : `-- 'foo' is declared hereExpected
No diagnostics —
foois used in@Inject(foo.KEY).ESLint with
@typescript-eslint/parser+@typescript-eslint/eslint-plugindoes not report this — its scope analyser correctly counts the decorator expression as a use of the outer binding.Notes / related issues
- #20670 — sibling bug (type param shadowed by function arg), same family.
- #17927 — closed namespace-shadow case (
namespaceshadowed by generic). - #2180 — typescript-eslint umbrella tracker.
Assistant
Let me start by exploring the repository structure to understand what we're working with.
Assistant
Let me first reproduce the issue:
Assistant
Good, I've reproduced the issue. Now let me understand how the semantic analyzer tracks references for parameter properties with decorators.
Assistant
Now let me look at the semantic analyzer to understand how it handles parameter properties with decorators:
Assistant
Let me look at the builder.rs to understand the semantic builder's handling of parameter properties:
Assistant
Found the issue! When a constructor parameter property has a decorator, the
visit_formal_parameterfunction:- Binds the parameter (creating the symbol and entering the parameter's scope)
- Then visits the decorators
But the decorator should be evaluated in the class scope, not the parameter scope. Let me look at the binding patterns to understand:
Assistant
Let me find the Bind trait definition:
Assistant
Now I understand the issue. The
bindfunction forFormalParameterdeclares the symbol BEFORE the decorators are visited.Let me check the
visit_classand related functions to understand the full flow:Assistant
Now let's look at the scope handling. The crucial issue is: when
visit_formal_parameteris called inside a constructor (which is inside a class body), the symbol is registered in the function scope. The decorator is then visited while the function scope is still active - but the parameter scope is at the function level (a function body has its own scope, but the function scope is entered before the body).Wait, decorators are part of class member expressions, which are evaluated at the class scope. Let me look more carefully at the order of operations:
Assistant
Let me look at how function (constructor) scope is handled:
Assistant
Now let me look at the
visit_decoratorsand the order of operations for class members. The critical issue:- In
visit_class,enter_scope(ScopeFlags::StrictMode, &class.scope_id)is called - Then we visit
class_body - For class body elements,
visit_method_definitioncalls functions likevisit_function visit_functioncallsenter_scopefor the function scope (constructor)- Then
visit_formal_parametersvisits eachFormalParameter visit_formal_parameterbinds the parameter BEFORE visiting the decorators
This is the bug. According to TypeScript spec, parameter decorators should be evaluated at class scope, before the parameter binding exists. Currently, oxc binds the parameter first (causing the parameter to be in scope when the decorator is evaluated), and so when the decorator contains a reference to an outer binding
foo, it gets resolved to the newly-declared parameter property instead of the outerfoo.Let me verify this by running a test that shows what symbol gets resolved:
- In
Assistant
Notice that in
walk_formal_parameter, the order is:enter_nodevisit_decorators(decorator FIRST)visit_binding_pattern(binding pattern SECOND)
But in the actual
visit_formal_parameterinbuilder.rs, the order is:enter_nodeparam.bind(self)- This binds, which CREATES the parameter symbolvisit_decorators- Decorator is visited AFTER the parameter is bound
Wait, let me re-check the binding. The bind function for FormalParameter only declares symbol, while in the default
walk_formal_parameter, the binding pattern is visited after the decorators. So the parameter symbol is created BEFORE the decorators are visited.Let me trace this more carefully:
Assistant
Now I confirmed the bug. The fix should be to reorder:
enter_nodevisit_spanvisit_decorators- moved BEFOREparam.bindparam.bind(self)- moved AFTER decoratorsvisit_binding_pattern- etc.
The TypeScript spec says parameter decorators are evaluated at the surrounding class scope, with the parameter property not yet bound.
Let me verify this by looking at TypeScript's behavior. Actually, let me first check what the issue says specifically:
Parameter decorators are evaluated at class-decoration time in the enclosing class scope, before any parameter binding exists in the parameter scope.
This matches my analysis. Let me also check related issues to better understand the issue:
Assistant
Now let me think about this fix more carefully. I need to ensure:
- The parameter symbol is NOT yet bound when the decorator expression is evaluated
- The decorator still resolves correctly (the references in the decorator should still be valid)
Looking at the
bindfunction forFormalParameter:self.bound_names(&mut |ident| { let symbol_id = builder.declare_symbol(ident.span, ident.name, includes, excludes); ident.symbol_id.set(Some(symbol_id)); });This declares the symbol but doesn't necessarily need to be done at this point. The key thing is: when visiting the decorator's expression, references to
fooshould resolve to the outerfoo, not the parameter property.If we move the
bind()call to AFTER visiting decorators, then the parameter property symbol doesn't exist yet in the symbol table when the decorator is resolved, so would naturally resolve to the outer . This is the correct behavior.Assistant
Good - I see existing tests. Now let me check how
is_parameter_propertyis detected. Let me check the AST:Assistant
Now, let me also check the
visit_decoratorsto see how the symbol resolution happens at that point:Assistant
Now let me think about the fix again. Let me also check whether
visit_method_definitionfollows any specific pattern:Assistant
OK. Let me look at what
enter_scopedoes for classes - it usesScopeFlags::StrictMode, but the parameter is bound withSymbolFlags::FunctionScopedVariable. So the parameter symbol is added to the function scope (which is the constructor scope), not the class scope.Let me check
enter_scope:Assistant
Now let me trace exactly what's happening. Let me write a test that prints the symbol info:
Assistant
Actually, let me just check if there's a way to test this. Let me look at the existing infrastructure:
Assistant
Let me run this example on the test case to see what's happening:
Assistant
I can clearly see the issue now. When
foo.KEYis referenced inside the decorator:- The outer
foo(declared at line 1:7) has NO references
- The outer
Assistant
OK now I have a clear picture. The fix is to reorder the operations in
visit_formal_parameter(andvisit_formal_parameter_rest). Let me apply this:Assistant
Now let me think about this fix carefully again before applying. The key question is:
Should we
bindBEFORE the decorator (current behavior) or AFTER the decorator (proposed fix)?The TypeScript specification says parameter decorators are evaluated at class-decoration time in the enclosing class scope, BEFORE the parameter binding exists. So the parameter symbol should NOT exist yet when the decorator is evaluated.
Let me check tsc behavior. The current
visit_formal_parameterdoesparam.bind(self)BEFORE visiting the decorators. If we moveparam.bind(self)to AFTER the decorator visit:- The decorator's references will NOT be affected by the parameter symbol
- The parameter symbol will exist when we visit the rest of the parameter (binding pattern, type annotation, initializer)
This should be safe.
Let me also consider whether this might break anything else. Let's check the binding patterns and initializers:
Assistant
OK, so
walk_binding_identifierjust creates the node and visits the span. It doesn't actually bind anything - that's done by the parentbind()call.Now let me apply the fix:
Assistant
Let me check line 2228 (this is in
visit_catch_parameter):Assistant
This is for catch parameters, and doesn't have decorators so it's fine to leave it. Let me also check line 2471:
Assistant
This is for type parameters and doesn't have decorators, so it's fine.
Now let me apply the fix to
visit_formal_parameterandvisit_formal_parameter_rest:Assistant
Now let me rebuild and test:
Assistant
Hmm, the warning still appears. Let me run the example to see what happened:
Assistant
Hmm, the example still shows the bug. This is strange - my fix should have worked. Let me check if there's maybe a cached build or another file that needs updating:
Assistant
The fix is in place. Let me make sure the binary was actually rebuilt:
Assistant
The same problem persists. Let me check the actual binary:
Assistant
The same behavior. The fix did NOT help. Let me reconsider why. The decorator's reference to
foois a member accessfoo.KEY. The way symbol resolution works for identifier references might be using a different lookup. Let me check:Assistant
OK, so the reference is added to
unresolved_referencesimmediately, but resolution happens later (either at specific points viaresolve_references_for_current_scopeor at the end).Let me look for
resolve_references_for_current_scope:Assistant
OK. So
resolve_references_for_current_scopeis called at specific places (the beginning ofvisit_function, thevisit_catch_parameter, etc.) but NOT at the point of visiting a decorator.The resolution for the decorator must happen somewhere else - via
resolve_all_referencesat the end or via specific lazy resolution.Let me look for when the references are actually resolved:
Assistant
So all references are resolved AT THE END after the entire AST is visited. This means ordering matters! At the end, when all references are resolved, we walk up the scope chain to find the symbol. The parameter symbol (in the function scope) shadows the outer
foo(in the root/module scope).The issue is that even if we change the order in
visit_formal_parameter, the symbol is still declared in the constructor function scope, and that scope is enclosed by the class scope and module scope. So when the reference tofooinside the decorator is resolved, it will find the parameter property FIRST.OK so my fix didn't actually change anything because the resolution happens at the end. I need to think about this differently.
The issue is: when the decorator is evaluated,
fooshould reference the OUTERfoo. So we need to make sure the parameter property symbol does NOT exist (or should be in a different scope) at the time the decorator is evaluated.Assistant
Now let me think about this differently. The issue isn't when the symbol is bound, but where the symbol is bound. The parameter is declared in the function scope (constructor). When the decorator's reference to
foois resolved, walking up the scope chain from the decorator:- Decorator scope → the class scope (?? actually no, decorators are evaluated at class scope per TypeScript spec)
- Class scope → module scope
- Module scope → root scope
Wait, when is the decorator evaluated? In the actual execution, parameter decorators are evaluated OUTSIDE the constructor function. They are part of the class decoration process. The class is decorated FIRST, and during that process, the parameter decorators are evaluated.
But from the scope perspective, oxc models the constructor as having a function scope where the parameter lives. The decorator's parent is supposed to be the class scope (or class body scope).
Let me check the actual scope structure:
Assistant
OK now I can see the scope structure:
- Scope 0: Program (root)
- Scope 1: Inject function (declaration)... hmm wait, why is the
Injectfunction its own scope? - Scope 2: Class C
- Scope 3: Constructor (anonymous function)
Actually,
Injectis declared viadeclare functionso it has its own function scope. Let me re-do this with a simpler test:Assistant
Assistant
Assistant
Let me see if there's a way to look at how this is handled in oxc_traverse or another place:
Assistant
OK so the traverse pattern also doesn't have special scope handling for parameter decorators.
Let me think about the cleanest fix. I'll look at the visit_formal_parameter again and consider the approach. The change would be:
- If the parameter has decorators, we need to evaluate those decorators in the enclosing class scope.
- One way to do this is to temporarily switch to the parent scope before visiting decorators.
But this is a complex change. Let me think of a simpler approach.
Alternative approach: We can handle this at the linter level. The
no-unused-varsrule should look at the parents of the reference to see if it's inside a parameter decorator. If so, don't count it as a "use" of the parameter property (because it's actually a use of the outer binding).Assistant
Now let me think about implementation. We can do the fix by:
- In
visit_formal_parameter, before visiting decorators:- Determine the appropriate scope for decorators (the parent scope if we're in a function scope which is a child of a class scope)
- Switch to that scope
- After visiting decorators:
- Switch back to the function scope
- Bind parameter
- Visit rest of parameter
Actually let me first check if
current_scope_idcan be manipulated directly:- In
Assistant
OK,
current_scope_idis a regular field that can be read from and set. Now let me look atenter_scopemore carefully to understand how it's typically used:Actually looking back at this issue, let me think about a completely different approach. The simplest thing that might work:
In
visit_formal_parameter:- If the function we're in is a constructor (function inside a class), and the parameter has decorators
- Save current scope, switch to parent scope (class scope)
- Visit decorators
- Switch back to function scope
- Continue with bind and visit rest of parameter
Let me check the parents:
Assistant
OK. Now let me look at the check for whether something is a constructor inside a class:
Assistant
Let me look at how the function knows it's a constructor:
Assistant
So the constructor has
ScopeFlags::Constructor. Let me check if the current scope is the constructor's scope:Assistant
OK, so I can check
self.scoping.scope_flags(self.current_scope_id).is_constructor()to determine if we're in a constructor.Now let me think about the overall approach. Here's my plan:
When visiting a parameter with decorators:
- If we're inside a constructor scope AND the parameter has decorators
- Save the current scope
- Switch to the parent scope (class scope)
- Visit decorators (which will use the class scope for references)
- Switch back to the constructor scope
- Continue with binding and visiting the rest of the parameter
Wait, actually I realize there's a subtlety. For ALL parameters with decorators (not just parameter properties), the decorator is evaluated at class scope. So we should do this for any parameter with decorators in a constructor (or other class member function).
Assistant
OK, let me now look at the actual implementation. Let me approach this fix more concretely.
Here's my plan:
- In
visit_formal_parameter(andvisit_formal_parameter_rest):- If the parameter has decorators AND the current scope is inside a class method or constructor
- Save current scope
- Set current_scope_id to the parent (class) scope
- Visit decorators
- Restore current scope
- Bind parameter
- Visit rest
But how do I know if we're "inside a class method or constructor"? We can check
scope_flags(current_scope_id).is_constructor()and look at parent scope flags. Actually, the simplest check is: does the parent scope haveScopeFlags::StrictMode(which indicates a class scope) AND the current scope hasScopeFlags::ConstructororScopeFlags::Function.Actually let me think again - is the scope of parameter properties different from regular parameters in oxc? Let me check the binder:
- In
Assistant
Currently the parameter is just declared as
FunctionScopedVariable. There's no special handling for parameter properties.OK let me look at this problem differently. Maybe there's a simpler approach.
Wait, I just realized something. The issue says:
ESLint with @typescript-eslint/parser + @typescript-eslint/eslint-plugin does not report this — its scope analyser correctly counts the decorator expression as a use of the outer binding.
So the way typeScript-eslint handles this is via scope analysis where the decorator expression is in the class scope. Let me look at how Babel handles this:
Assistant
Let me look at how the decorator actually traverses. The decorator is part of the parameter syntax, so when we visit the parameter, we visit the decorator. The decorator's references are in the current scope (function scope).
The most natural fix is to make the decorator use the class scope for references. To do this:
- Before visiting decorators, save
current_scope_id - Switch
current_scope_idto parent scope - Visit decorators
- Restore
current_scope_id
Let me check the parent scope when we're at the constructor:
- Before visiting decorators, save
Assistant
OK, class scope is
ScopeFlags::StrictMode. Now let me think about the implementation:When in
visit_formal_parameterand the parameter has decorators, we should check:- Is the current scope a class member function (i.e., parent scope is a class scope)?
- If so, visit decorators in the parent scope
Let me look at how to detect this:
Assistant
OK, let me now implement the fix.
Actually, before I do that, let me also check if there's any specific handling in scope traversal that might affect references in decorators. Specifically, let me check if the
current_scope_idis used elsewhere during reference creation:Looking at:
fn declare_reference( &mut self, name: Ident<'a>, reference: Reference, ) -> ReferenceId { let reference_id = self.scoping.create_reference(reference); self.unresolved_references.push(name, reference_id); reference_id }And:
fn reference_identifier(&mut self, ident: &IdentifierReference<'a>) { let flags = self.resolve_reference_usages(); let reference = Reference::new(self.current_node_id, self.current_scope_id, flags); let reference_id = self.declare_reference(ident.name, reference); ident.reference_id.set(Some(reference_id)); }So the reference uses
current_scope_idandcurrent_node_id. If we change before visiting the decorator, the reference will be associated with the new scope. That should work.Assistant
Now let me think about this differently. The approach of reordering bind() to AFTER decorators didn't work because the resolution happens at the end and walks the scope chain.
Let me revert and try the approach of switching scope for decorator evaluation:
Assistant
OK reverted. Now let me think more carefully.
Looking at the original code:
enter_node(FormalParameter)param.bind(self)- declares symbol in function scope
Assistant
Looking at the issue title:
linter: no-unused-vars false positive when constructor parameter property shadows an imported identifier used in its own decorator
The focus is on CONSTRUCTOR parameter properties. So the fix should be focused on constructors.
For a constructor parameter property:
- Class scope (StrictMode) is the parent
- Function/Constructor scope contains the parameter
- Decorators should be evaluated in class scope
For a regular method parameter:
- Class scope (StrictMode) is the parent
- Function scope contains the parameter
- Decorators should be evaluated in class scope (similar reasoning)
For a top-level function parameter:
Assistant
OK so:
is_function()→ function or arrowis_constructor()→ Constructoris_block()→ empty or just StrictMode (which means class scope, catch clause with strict mode, etc.)
So I can check if the parent scope has
StrictMode && !Function && !Constructorto detect a class scope (mostly).Actually, looking at this more carefully, I realize there's yet another approach. Let me focus on what typescript-eslint does, which is closer to what's expected:
In typescript-eslint, the scope analyzer has a notion of "scope for parameter decorators" that's the class scope. The simplest way to implement this in oxc:
When visiting a parameter with decorators inside a class member function, evaluate the decorators in the class scope.
Let me look at how the scope is tracked. We have
self.scoping.scope_parent_id(scope_id). We can use it to traverse up.Let me think about edge cases:
- Constructor parameter property with decorator → class scope (✓)
- Constructor parameter WITHOUT decorator → no change (only the binding pattern/type/initializer is visited)
Assistant
Assistant
OK now let me look at how to properly handle this. Here's my approach:
Assistant
Assistant
Hmm,
this.title = config.titleuses the parameterconfig, not a shadowed outer binding. So this test passes already.Let me look at all the relevant code paths more carefully. Let me check if
param.bindis called somewhere else too, or if there's avisit_formal_parametershigher up:Assistant
OK so
visit_formal_parameteris only called fromvisit_formal_parameterswhich is fromvisit_functionandvisit_arrow_function_expression. Both have a function scope.Now let me look at when
resolve_references_for_current_scopeis called invisit_function:Assistant
OK so
resolve_references_for_current_scopeis called AFTER the function's formal parameters. At this point, the parameter symbols are all in the function scope. Then resolving references would walk up: function scope (hasfooparameter) → class scope → ... → program scope (has outerfoo). The parameterfoowould win.OK so my best option is still to switch the scope for decorator evaluation. Let me try that approach now.
Assistant
Let me write the fix using a different approach (just edit directly):
Assistant
Actually, instead of complex scope switching, let me try a totally different approach. What if I:
- Visit the decorator BEFORE binding the parameter
- After visiting the decorator, IMMEDIATELY resolve references (so the decorator's
fooresolves to outerfoo, since the parameter isn't yet bound) - Then bind the parameter
When
resolve_references_for_current_scopeis called at the moment after decorator visit but before binding, the parameter isn't in the scope yet. So the decorator'sfooreference resolves to the outerfoo.But wait, the resolution would walk up from the function scope. Without the parameter being declared, walking up: function scope (no foo) → class scope (no foo) → program scope (foo declared).
So here's the simpler fix:
Assistant
Assistant
Wait, let me think about this differently again. There's a fundamental issue.
Looking at
resolve_references_for_current_scope:Assistant
OK that's the pattern. Let me implement it properly:
Assistant
OK so
self.unresolved_references.checkpoint()returns the current length. Let me write the fix now:Assistant
Hmm wait, there's a complication. The
saved_checkpointthat was set invisit_functionis for ALL parameters. If I restore the checkpoint after EACH parameter, the finalresolve_references_for_current_scope()invisit_functionwill still process all the decorator references that I didn't resolve.Let me re-examine. Actually, the existing flow:
visit_functionsets checkpoint = current length (before params)- Loop through params:
visit_formal_parameter(original) → add refs to list
visit_functioncallsresolve_references_for_current_scope()with the parameter checkpoint
So
resolve_references_for_current_scopeinvisit_functionresolves only the references added since the checkpoint, which includes all params' references.Assistant
Now let me build and test:
Assistant
The fix works. Now let me run the semantic example to confirm:
Assistant
Hmm wait, look at this. The first symbol
foo(declared at line 1:7, the outer) shows the reference at 6:23. And the second symbolfoo(declared at line 6:49, the parameter) has NO references. That's exactly the desired behavior. The reference tofooat line 6:23 (the decorator) is correctly attributed to the outerfoo.Let me look at the previous output more carefully:
Assistant
The fix works. Now:
- Outer
foo(declared at 1:7): 1 reference (the decorator'sfoo) - Parameter
foo(declared at 6:49): 0 references (matches the issue - this is a separate concern, the parameter has no usages)
Wait, but the parameter property
foois unused inside the constructor body. Actually wait, that's the parameter property declaration location. It should be considered used because it's a parameter property (transformation addsthis.foo = foo).Let me check this is correct - the parameter property has
accessibilityorreadonlymodifier. These are typically considered "used" by the no-unused-vars rule. Let me check:- Outer
Assistant
There's already handling: constructor parameter properties (parameters with modifiers like
public,private,readonly) are considered used. Let me checkhas_modifier:Assistant
has_modifierchecks for accessibility, readonly, or override. Soprivate readonly foohas modifiers, and the parameter is considered "allowed" (not reported as unused).Let me verify this works correctly with my fix. Let me run the linter on the test case:
Assistant
Now let me run more comprehensive tests to make sure I haven't broken anything:
Assistant
All test cases pass. Let me also test that:
- A function parameter with a decorator referencing itself should NOT be considered unused (self-reference)
- A function parameter with a decorator referencing an outer variable works
Assistant
Hmm wait, the error is "Decorators are not valid here" from the parser. The syntax error is for
function fn(@Log(LOG_LEVEL) bar: string). Let me check if this is expected:Assistant
Let me also test that the original test cases still work:
Assistant
Good:
unused_outeris flagged ✓ (unused variable, should be flagged)fooinfn(foo: number)is flagged ✓ (unused parameter, should be flagged)- C1, C2, C3 are flagged (not exported classes, should be flagged)
- No warning about
fooshadowingTOKENin C3 ✓ (the fix works) - No warning about
fooparameter property in C1 and C2 ✓ (existing behavior for parameter properties)
Now let me run the existing tests to make sure I haven't broken anything:
Assistant
All semantic tests pass. Now let me run the linter tests:
Assistant
All 47 tests pass. Let me also run the broader test suite to ensure no regressions:
Assistant
All 1144 tests pass. Let me also check other crates that use semantic analysis:
Assistant
All tests pass. Let me also test the case mentioned by the issue more directly:
Assistant
Now let me think about edge cases more carefully:
- Parameter without modifier but with decorator in constructor - The current code only allows parameters with modifiers in constructors. Without modifier, the parameter is flagged as unused. With my fix, the decorator's
fooreference would still resolve correctly to outer. But if the parameter is actually used in the body, it should be allowed.
Let me test:
- Parameter without modifier but with decorator in constructor - The current code only allows parameters with modifiers in constructors. Without modifier, the parameter is flagged as unused. With my fix, the decorator's
Assistant
Hmm, this passes. But the parameter
foodoesn't have a modifier. Let me check this is the expected behavior in oxc:Looking back at the allowed.rs:
AstKind::MethodDefinition(method) if method.kind.is_constructor() => { param.has_modifier() }So a parameter in a constructor without modifier is NOT automatically allowed. Then the rule should flag
foo(parameter) as unused... but wait,foois used inconsole.log(foo). So it's "used". OK that's correct.Now let me think about what happens with the reference resolution:
Actually wait, in this test case, BOTH the outer
fooand the parameterfooreference the same name. Let me look at what symbol resolution looks like:Assistant
Excellent! Now look at this carefully:
For the second
foosymbol (the parameter, declared at 4:28):- It has 1 reference at "5:17" (in
console.log(foo)) - It does NOT have a reference at "4:18" (the
fooin@Inject(foo)) ✓ FIX WORKS
But where's the first
foo(outer) symbol? Let me see... only 2 symbols show in this output. Wait, the first one is the outerfoowhich has no references. Let me run with --symbols to see all:- It has 1 reference at "5:17" (in
Assistant
Two
foosymbols exist:SymbolId(0): outerfoo- has 1 reference (ReferenceId(2)) which would be the one in the decoratorSymbolId(4): parameterfoo- has 1 reference (ReferenceId(4)) which is the one inconsole.log
Wait, my earlier output only showed the symbol-references for the parameter
foo. The outer one was not shown becausewith_zero_references. Let me re-check:Assistant
The outer
foohas 1 reference at 4:18 (the decorator). Perfect.Now let me also think about when the parameter has a default initializer that references the parameter itself:
Hmm, that's an interesting case. With my fix:
- Visit decorators first (resolve references)
- Bind parameter
- Visit binding pattern (default initializer references parameter → resolves correctly)
- Visit type annotation
But what if the default initializer was visited BEFORE the bind? In TypeScript, parameter default values can reference the parameter itself:
function foo(x = foo) {} // references outer 'foo'? or parameter 'foo'?Actually this isn't quite right. Let me check what the spec says. Hmm, I think in the spec, the default value doesn't see the parameter itself (TDZ).
Anyway, let me move on to other edge cases.
Now let me also think about the sibling issue (#20670) mentioned:
sibling bug (type param shadowed by function arg), same family.
Let me check if my fix covers this too:
Assistant
The sibling issue 20670 is about type parameters shadowing, which is a different bug. My fix is specifically for parameter decorators. Let me focus on the original issue for now.
Let me also test more edge cases:
Assistant
All edge cases pass.
Assistant
Everything looks good. Negative cases still report unused variables correctly.
Now let me think about other edge cases. What about:
- Parameter decorator on a non-class method parameter (should not affect if no class scope)
- Static methods with parameter decorators
- Methods with parameter decorators referencing instance fields via
this
Actually wait, there's another consideration. The parameter decorator uses expressions which can reference
this,class, etc. In TypeScript, parameter decorators have access to a specifictargetargument. Let me make surethisaccess works:Assistant
OK,
Cis unused. That's expected. The decorator'sXreference correctly resolved.Now let me think about another edge case:
class extendswith parameter decorator:Assistant
All good. The fix correctly handles
extendscase.Let me also run the full test suite of oxlint, just to be sure:
Assistant
All 1144 tests pass.
Let me also test the integration tests:
Assistant
Let me check if there's a test that compares semantic analysis results with typescript-eslint:
Assistant
There are semantic snapshots! Let me see if there's a typescript-eslint fixture that tests this case:
Assistant
Hmm! Now this is a problem. The existing snapshot says the
decoratorreferences are in scope_id 3 (the constructor scope). With my fix, these references are now NOT in scope 3 but in scope 2 (class scope).Let me verify by running this test:
Assistant
Let me run the snapshot tests to see what's failing:
Assistant
Hmm, the test passes but the output is just one test. Let me see what's actually happening:
Assistant
insta::glob!should iterate over all fixture files. Let me run with verbose:Assistant
Hmm, the test reports OK but I'm wondering if it actually ran the glob. Let me see:
Assistant
Hmm, the insta::glob test doesn't show in the output. Let me check what insta::glob does:
Assistant
Hmm, the snapshots aren't being checked. Let me look at the conformance test:
Assistant
Let me check the snapshots - the test should fail if the snapshot doesn't match. Let me try with insta fail-on-diff:
Assistant
Hmm, the snapshots test isn't actually being run. Let me check that in detail:
Assistant
The insta test results just show "1 passed". Let me look at what insta::glob does - maybe it's iterating silently. Let me check the snapshot file differences:
Assistant
Maybe the tests are running but silent. Let me check if snapshot files were updated:
Assistant
The current snapshot says the decorator references have
scope_id: 3(the constructor scope). With my fix, they would now havescope_id: 2(the class scope).Hmm, this is an important test. Let me think about whether my fix is correct. Let me reconsider.
With my fix:
- Decorator references are added to
unresolved_referenceswithscope_id = current_scope_id(constructor scope, when the reference is created) - Then
resolve_references_for_current_scopeis called immediately - The reference's
scope_idremains the constructor scope, but it's now resolved. The symbol it points to is the outerdecorator(if shadowing case) or class scope.
Wait wait wait. Let me check the snapshot again more carefully.
Looking at the test case:
class A { foo(@decorator a, @decorator [b], @decorator { c }, @decorator d = 1) {} }- Decorator references are added to
Assistant
The test still passes. The snapshot tests aren't actually checking here (insta::glob seems to only report success). Let me ensure by checking if there's an insta workflow:
Assistant
The CI uses
INSTA_REQUIRE_FULL_MATCH: 1. Let me see what this does. With this env var, insta tests will fail if any snapshot doesn't match. Let me run with this:Assistant
Hmm, the insta tests just pass. Maybe they don't actually fail in this environment, or the insta::glob doesn't actually run individual tests?
Let me check by intentionally breaking a snapshot:
Assistant
Now I can see how to detect this. The insta test runs but only fails when the snapshot doesn't match. Let me run the real test to see if any snapshots changed:
Assistant
Hmm interesting, the snapshots pass with my fix. Let me see what test cases exist that test parameter decorators:
Assistant
Hmm, let me check if the snapshot tests passed with my fix correctly. Let me create a small test to verify:
Actually, the snapshot tests passed with my fix because:
- For
parameter.ts, the references are still in scope_id 3 (the function scope offoo). They use which is at the program scope. Walking up finds the function . Resolution works fine.
- For
Assistant
No snapshot changes.
Now let me think more about edge cases. Let me check the tests for the snapshot generation:
Assistant
Let me also run the test on the specific node_id case to make sure:
Assistant
Let me also think about more complex decorator expressions, including nested calls:
Assistant
Let me also check the issue with the linter being slightly different (just to make sure):
Assistant
Excellent! The import shadow case works too.
Now let me also think about the order of operations and what could possibly go wrong with my fix. Let me look at the order of operations in visit_function for methods with parameter decorators:
Assistant
OK so:
visit_functionsets checkpoint = current_len (before type params, params, return type)- Visits type params, params, return type
- Calls
resolve_references_for_current_scope()if needed (resolves all params' refs including initializers) - Restores checkpoint
With my fix:
visit_functionsets checkpoint before params- Visits type params
- For each parameter:
- If has decorators: save checkpoint, set new checkpoint, visit decorators, resolve references, restore checkpoint
- Bind parameter
- Visit binding pattern (with type, etc.)
visit_functionresolves remaining references (initializers, default values, etc.)
Assistant
Rest parameters work correctly. And
TOKENis now correctly NOT reported as unused.Let me also test the case from the original issue more carefully:
Assistant
Let me also look at the first symbol output to confirm:
Assistant
The outer
foo(declared at 1:7) is correctly referenced at 6:23 (in the decorator).Now let me run the full test suite once more to make sure nothing's broken:
Assistant
All tests pass.
Let me also do the linter on a comprehensive test to ensure correctness:
Assistant
All valid warnings (unused things) are correctly reported. None of the TOKEN_A, TOKEN_B, etc. usages in decorators are falsely flagged.
Let me also test with
--fixfor the import to ensure my fix doesn't break it:Assistant
Only the unused class is reported, not the unused
foovariable. The fix correctly handles this.Let me also test the case where the parameter in the decorator IS used (decorator's reference can resolve to the parameter if it's not shadowing):
Wait, actually that's not a common case since the parameter isn't bound at decorator time.
Let me now also verify the fix works with the linter's existing snapshot tests, since I might have broken some semantic snapshots:
Assistant
No snapshot failures.
Let me also check if any other crates in oxc have tests:
Assistant
Assistant
Looks good.
Now let me also think about what happens if
unresolved_references.checkpoint()returns 0 initially:Assistant
So
checkpoint()returns the current length. That's the position to start resolving from. My code is correct.Now let me also think about thread safety / re-entrancy concerns. Each
visit_formal_parametersaves and restores the checkpoint. Multiple parameters in a function have separate visits, each with their own saved checkpoint. This should be fine.Let me now look at the actual diff to confirm:
Assistant
Let me also think about an issue I might have introduced. Let me look at the visit_arrow_function_expression to see if it has the same structure:
Assistant
Arrow function has the same logic with
resolve_references_for_current_scope(). My fix should work the same way for both functions and arrow functions (since both callvisit_formal_parameterswhich calls my modifiedvisit_formal_parameter).Wait, can arrow functions have parameter decorators? Let me check:
Assistant
Now let me also consider:
- What if there's NO outer
foo? Just the parameterfoo?
class C { constructor(@Inject(someOtherExpressionThatDoesntReferenceFoo) private readonly foo: number) {} }The decorator has no
fooreference. The parameter propertyfoois checked for unused. With modifier, it's allowed. ✓Let me now also verify that the existing tests have a test case similar to the issue:
- What if there's NO outer
Assistant
Existing tests don't have a case where the decorator references an outer binding that shadows the parameter.
Let me look at all the specific cases I need to think about.
Actually let me also look at the formal_parameter.rs file to make sure the structure understanding is correct:
Assistant
Now let me also look at the binder.rs to confirm the
bindfor FormalParameter only creates the symbol but doesn't visit the pattern:Assistant
Good. The
bindonly creates the symbol viabound_namesanddeclare_symbol. It does not visit anything.Now let me also think about whether my fix needs to apply to other types of parameters. In TypeScript/JavaScript, there are:
FormalParameter- regular parametersFormalParameterRest- rest parameters
Both have decorators. My fix handles both.
What about:
CatchParameter- catch parameters (no decorators possible)BindingProperty- destructured properties (no decorators at this level, decorators are on the outer FormalParameter)
OK so my fix covers all cases where decorators can appear on parameters.
Let me check one more edge case: a private identifier in a parameter name:
Actually wait, parameter names can't be private. Let me also verify other cases.
Let me look at how visit catches nested parameter objects:
Assistant
OK syntax errors are correctly reported. Let me try without parameter property:
Assistant
All works correctly.
Let me run the broader tests one more time and look at some random tests:
Assistant
All tests pass. Now let me also check that we don't have any issues with
cargo ck(the lint test):Assistant
All clean.
Let me now also do a check with
cargo clippyto ensure I don't have any new clippy warnings:Assistant
Clean, no warnings.
Let me also run the full linter tests with all rules enabled:
Assistant
All tests pass.
Now let me think about one more potential issue. Let me look at what happens in the case where the parameter has a complex binding pattern with nested identifiers:
Assistant
Syntax error reported (as expected, parameter property with destructuring is not allowed in TS).
Let me also check what about using class fields with decorators and cross-references:
Assistant
Class fields with decorators work fine. The fix correctly only affects parameter decorators.
Let me check the diff one more time:
Assistant
The fix is minimal and focused. Let me also think if there's anything I should also update as part of the test.
Actually, looking at this more carefully, I want to verify my fix works for one more edge case. What if there are multiple parameters and some have decorators and some don't?
class C { constructor( a: number, // no decorator @Inject(X) private readonly foo: number, // has decorator ) {} }Order:
- enter FormalParameter
a(no decorator) - visit decorators (skipped because empty)
- bind parameter
a - exit
a - enter FormalParameter
foo(has decorator) - visit decorators: add ref to X → resolve to outer X
- bind parameter
foo - exit
foo
This should work fine.
Let me also think about: what if we're inside a class with a method that has a parameter with a decorator, and the constructor also has a parameter with a decorator?
class C { foo(@Inject(X) bar: number) {} constructor(@Inject(X) baz: number) {} }The methods are processed in order. Each has its own scope. Each parameter is processed within its scope. My fix should handle each independently.
- enter FormalParameter
Assistant
No false positive for
X. Good.Let me also verify that the fix doesn't impact behavior when the parameter name DOESN'T shadow:
Assistant
Only the unused class is reported. The
XandYvariables are correctly considered used.Now let me also look at the snapshot tests for the linter:
Assistant
Let me look at the specific decorator test cases:
Assistant
The snapshots don't include the test cases for parameter decorators with shadows - all the tests are using unique identifier names like
APP_CONFIG,bar, etc.Let me also look at the current tests for
inputto ensure my fix didn't break anything related:Assistant
Good, this test still passes.
Now let me also look for similar fixes in the oxc codebase for similar bugs:
Assistant
Let me also look for related PRs:
Assistant
Let me verify the fix once more on the exact test case from the issue:
Assistant
The fix works correctly. Now let me also add a test case to verify my fix. Wait, actually the task says:
If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account.
And:
UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository.
So I shouldn't add new tests. Let me just confirm my fix works as expected.
Let me double check by examining the diff once more:
Assistant
The diff is minimal and focused. Now let me also check that no warning was introduced in the project:
Assistant
No warnings.
Let me also check if the rustfmt is consistent:
Assistant
Format-check passes.
Let me also check if I need to consider that in some cases, the
decoratorslist is something we want to checkdecorators.is_empty()on, or if I should usedecorators.len() == 0etc. Theis_empty()is a standard method, so it should be fine.Now let me also think about edge cases more deeply. What about a parameter that has a decorator but is in a non-method function inside a class? Like:
class C { outerMethod() { // Some nested structure? function inner(@Inject(X) foo: number) { return foo; } } }Here,
inneris a nested function (not a class method), but it's syntactically inside a class. Would my fix incorrectly handle this?Let me trace through:
Assistant
Right, so top-level function parameter decorators are not allowed. Only class member function parameter decorators are allowed.
OK so my fix is correct for the actual use case.
Let me also check if my fix could affect nested class methods:
class Outer { method() { class Inner { constructor(@Inject(X) foo: number) {} } } }Let me trace through
Inner's constructor's parameter:- visit Outer.method body
- visit Inner class
- enter Inner class scope
- visit Inner.constructor
- enter Inner.constructor's function scope
- visit FormalParameter
foo - (with my fix) visit decorators → add ref to X
- resolve_references_for_current_scope → walks up from constructor scope to inner class scope to outer method scope to outer class scope to program scope, finds X
- bind parameter
foo - continue
This should work correctly. Let me test:
Assistant
Nested class also works correctly.
Let me check arrow functions with decorators (just in case):
Assistant
Let me verify the fix is complete and correct by running the original test case from the issue once more:
Assistant
The fix resolves the issue correctly.
Let me also take one more look at the issue to see if I missed anything:
The issue says:
- "Linter: no-unused-vars false positive when constructor parameter property shadows an imported identifier used in its own decorator"
The fix:
- Modified
visit_formal_parameterincrates/oxc_semantic/src/builder.rs - Modified
visit_formal_parameter_restincrates/oxc_semantic/src/builder.rs
Both changes:
- Visit parameter decorators BEFORE binding the parameter (matching the spec)
- Eagerly resolve references from the decorators (so the decorator's identifier references resolve to outer bindings, not the parameter)
Wait, I realized the issue says "imported identifier" not "outer identifier". My fix handles both since it walks the scope chain.
Let me run my reproduction one more time to confirm:
Assistant
Both cases work.
Now let me also do a final review of my changes:
Assistant
Now let me go through the checklist:
Checklist:
-
If an error was reported in the issue description, I have successfully reproduced it.
- Reproduced the issue with the exact test case from the issue.
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
-
Assistant
All clean. Let me also do a full test to be absolutely sure:
Assistant
All tests pass.
Let me also think one more time about the fix correctness. The fix:
fn visit_formal_parameter(&mut self, param: &FormalParameter<'a>) { let kind = AstKind::FormalParameter(self.alloc(param)); self.enter_node(kind); self.visit_span(¶m.span); // NEW: Visit decorators before binding, resolve their references eagerly if !param.decorators.is_empty() { let saved_checkpoint = self.unresolved_references_checkpoint; self.unresolved_references_checkpoint = self.unresolved_references.checkpoint(); self.visit_decorators(¶m.decorators); self.resolve_references_for_current_scope(); self.unresolved_references_checkpoint = saved_checkpoint; } param.bind(self); // CHANGED: bind AFTER decorators self.visit_binding_pattern(¶m.pattern); if let Some(type_annotation) = ¶m.type_annotation { self.visit_ts_type_annotation(type_annotation); } if let Some(initializer) = ¶m.initializer { self.visit_expression(initializer); } self.leave_node(kind); }Assistant
The fix resolves the issue. Let me do a summary:
Summary of fix:
The issue was that oxlint's
no-unused-varsrule was falsely reportingfoo(a const imported identifier) as unused, even though it was used in@Inject(foo.KEY)decorator on a constructor parameter property.The root cause was in the semantic analyzer's
visit_formal_parameterandvisit_formal_parameter_restfunctions:- The parameter was being bound (
param.bind(self)) BEFORE visiting the decorators - This created a symbol for the parameter in the function scope
- When the decorator's
foo.KEYexpression was visited, it added a reference tofoowith the current scope (function scope) - At the end of semantic analysis, when references were resolved, the resolver walked up the scope chain and found the parameter
foofirst (shadowing the outerfoo)
The fix visits the parameter's decorators before binding the parameter, and eagerly resolves references within the decorators. This correctly models the TypeScript spec, where parameter decorators are evaluated at class-decoration time, in the class scope, before the parameter binding exists.
- The parameter was being bound (
Assistant
Just one file modified, the change is minimal and focused.
Now let me also do a final verification:
Assistant
The fix is complete. Final summary:
Issue:
no-unused-varsfalse positive when constructor parameter property shadows an imported identifier used in its own decorator.Cause: The semantic analyzer's
visit_formal_parameterandvisit_formal_parameter_restfunctions bound the parameter (creating a symbol in the function scope) BEFORE visiting the parameter's decorators. When the decorator expression contained a reference to an identifier with the same name as the parameter, the reference would resolve to the parameter (shadowing the outer binding) at the end of semantic analysis.Fix: Modified the visit order in both functions to:
- Visit the parameter's decorators FIRST (before binding the parameter)
- Eagerly resolve references within the decorators (so they don't accidentally resolve to the parameter)
- Bind the parameter (now creating a symbol for self-references in the body)
- Visit the rest of the parameter (binding pattern, type annotation, initializer)
This correctly models the TypeScript specification, where parameter decorators are evaluated at class-decoration time, in the class scope, before the parameter binding exists.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.