Skip to content

Skip classes that pass this to a call in no-unused-services - #2887

Merged
NullVoxPopuli merged 5 commits into
ember-cli:masterfrom
bardrop-oss:fix-no-unused-services-local-helper
Nov 18, 2026
Merged

NullVoxPopuli merged 5 commits into
ember-cli:masterfrom
bardrop-oss:fix-no-unused-services-local-helper

Conversation

@bardrop

@bardrop bardrop commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1258

Problem

no-unused-services only sees uses like this.someService inside the class. When the class hands this to some other code, that code may use the service, but the rule can't see it and reports the injection as unused:

const SomeUtilityFn = (component) => component.someService.someMethod();

export default class MyComponent extends Component {
  @service someService; // reported today

  get foo() {
    return SomeUtilityFn(this);
  }
}

Change

As suggested in review, the rule does not try to follow calls. If a class passes its this to any function or new call, the rule reports nothing for that class.

  • Counts: fn(this), obj.method(a, this), new Foo(this), fn?.(this). Arrow functions keep the class this, so items.map(() => fn(this)) and foo = () => fn(this) count too. Works for native classes and classic Foo.extend({...}) (incl. computed(function () { fn(this) })).
  • How: a CallExpression > ThisExpression.arguments / NewExpression > ThisExpression.arguments visitor, and the scope manager to find which class the this belongs to (no AST parent walking).
  • Does not count: this in a nested regular function, a nested class, a static method/field or a static {} block (that is a different this), and get / set / getProperties / setProperties imported from @ember/object (the rule already reads get/getProperties keys).

Tests

  • New valid cases: local helper, imported helper, method call, new, fn?.(this), arrow callback, arrow class field, class field, constructor, classic class method, classic computed callback, plus the two existing "un-imported get(this, ...)" cases, which moved from invalid to valid since that get is now just an unknown function that gets this.
  • New invalid cases: helper(this.other), static field, static method, static {} block, this passed in a nested regular function, in a nested class expression, in a nested class declaration, at module level, in a regular-function callback inside a classic class method, and set(this, ...) from @ember/object.
  • 13 of the cases fail on master and pass with this change.
  • Docs: short note in the rule doc.

pnpm test: 269 files, 9965 tests pass (1 todo). pnpm lint (eslint, markdownlint, eslint-docs, prettier) is clean.

@NullVoxPopuli

Copy link
Copy Markdown
Contributor

idk if it makes sense to lint this (precisely) -- there are infinite ways cause indirection in code, and trying to follow them precisely is an impossible task.

But! what I think we should do, is if we detect this passed anywhere, turn off the rule for that class

as in -- I'd think we can merge this PR IFF it doesn't follow function calling, but just disables when it detects a this is passed

@NullVoxPopuli NullVoxPopuli left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see note

If a class passes its `this` to a function or `new` call (e.g. `helper(this)`,
`obj.method(this)`, `new Foo(this)`, `helper({ owner: this })`), the called
code could use any of its services, so the rule now reports nothing for that
class. Calls are not followed. `this` in a nested regular function or nested
class is not the class's `this` and does not count. `get`, `set`,
`getProperties` and `setProperties` from `@ember/object` are not counted.

Fixes #1258
@bardrop
bardrop force-pushed the fix-no-unused-services-local-helper branch from 018285b to 56b1216 Compare November 16, 2026 18:52
@bardrop bardrop changed the title Count services read by a same-file helper that receives this in no-unused-services Skip classes that pass this to a call in no-unused-services Nov 16, 2026
@bardrop

bardrop commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Makes sense, agreed. Reworked in 56b1216: all the call following is gone. Now if a class passes its this anywhere (fn(this), obj.method(this), new Foo(this), fn({ owner: this })), the rule just reports nothing for that class. this inside a nested regular function or nested class does not count. get/set/getProperties/setProperties from @ember/object are also ignored, since they only take string keys (and the rule already reads the get ones).

Comment thread lib/rules/no-unused-services.js Outdated
function isThisPassedToCall(node) {
let child = node;
let parent = node.parent;
while (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this crawl all the way back up to the program doesn't it? we really don't want to while loop our way around the tree

we can use visitors to do this same work that we already do with basic traversal

every time we crawl parent paths, we N^2'd our traversals

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, fixed in 6fd02f4. No more parent walking at all. The rule now keeps a small stack while it visits the tree: entering a method / class field / function pushes whose this it is, exiting pops. Arrow functions push nothing, so they keep the outer this. Then CallExpression / NewExpression just look down into their own arguments (this, or this inside an array / object / spread). So each node is visited once, same as the rest of the rule. Also added two cases: foo = helper(this) as a field turns the rule off, while static foo = helper(this) and foo: helper(this) in a classic class do not (that this is not the instance).

Comment thread lib/rules/no-unused-services.js Outdated
case 'ArrayExpression': {
return node.elements.some(containsPassedThis);
}
case 'ObjectExpression': {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't need to do this, because this is its own node -- a ThisExpression -- so we can use that in the visitors

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, that's simpler. Done in 4e8d14c: containsPassedThis is gone. There is now a ThisExpression visitor that only looks at the direct parent of this. If this is a call / new argument, an array element, a spread, an object property value, or the right side of an assignment / const self = this, the class is skipped. this.foo, const { foo } = this, and get(this, ...) / set(this, ...) from @ember/object still count as normal uses. Nothing walks up the tree any more. Added cases for const self = this, this.items = [this], and a destructuring one that should still report.

* Only looks at the direct parent of `this`, so nothing walks up the tree.
* @param {ThisExpression} node
*/
function checkThisPassed(node) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we need all this -- we already have a ThisExpression, and we can already know via other visitors if we are within an Optional/Call/New Expression.

but also! for the this tracking -- have you explored if ESLint's ScopeManager correctly associates a this with the class?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call on both, done in 9913b0a.

  • The thisStack is gone. The class for a this now comes from the scope manager: start at getScope(thisNode), skip arrow function scopes, then look at that scope's block. A method or field value gives its class (static ones don't count), and a function inside Foo.extend({...}) gives that classic class. ESLint's ScopeManager doesn't record this as a reference (it only tracks identifiers), so this short walk over the scope chain is still needed, but it only touches scopes, not the AST.
  • The visitor is now just 'CallExpression > ThisExpression.arguments, NewExpression > ThisExpression.arguments'. fn?.(this) is covered too, since it's a CallExpression in ESTree.
  • I dropped the object / array / const self = this cases to keep it small. Happy to add { owner: this } back if you want it.

Checked with both @babel/eslint-parser and @typescript-eslint/parser (arrow field foo = () => helper(this) counts; static {} blocks and static methods don't). Full suite and lint pass.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is looking much better already

the impl of this PR is already like 200 lines shorten than when it started!

Drop the hand-kept this stack and the extra parent checks. A
'CallExpression > ThisExpression.arguments' selector finds a passed
`this`, and the scope manager tells which class it belongs to.
Comment thread lib/rules/no-unused-services.js Outdated
*/
function getThisClass(node) {
let scope = sourceCode.getScope(node);
while (scope.block.type === 'ArrowFunctionExpression' && !isClassMemberValue(scope.block)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why we doin' while loops again?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's only for arrow functions. An arrow has no this of its own, so in

foo() { return [1].map(() => helper(this)); }

the scope of this is the arrow's scope, and the class is one scope up. The loop steps over enclosing arrow scopes only and stops at the first non-arrow one, so it runs 0 times for a plain helper(this) and once per nested arrow otherwise. It never goes up to the program.

If you'd rather have no loop at all, I see two options:

  1. Look at just one scope. Then this inside an arrow in a method isn't linked to the class, and the [1].map(() => helper(this)) case would be reported again (it's one of the valid tests now).
  2. Go back to a small stack kept by the function/method enter + exit visitors, so the owner of this is known with no lookup.

Happy to switch to either. Which do you prefer?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why tho? the Visitors will see the ThisExpression here?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the arrow's scope

arrows have no scope

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right that the visitors already tell us the class. Small correction on my side though: in eslint-scope an arrow does get its own function scope (getScope(this) inside () => helper(this) returns the ArrowFunctionExpression scope), it just has no this binding. That is why the loop was there.

But it is not worth it. Done in 1cb3713: the scope lookup and isClassMemberValue are gone. When the ThisExpression visitor sees this as a call / new argument, it just sets a flag on classStack.peek(), the same way the this.foo visitor already counts a use anywhere in the class.

The trade-off: this passed from a nested function () {} or a static member now also turns the rule off for that class. That is only a missed report, never a false one. I moved those 7 cases from invalid to valid. 9965 tests and lint pass.

return;
}
const { callee } = node.parent;
const emberObjectFunctions = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are we checking these specifically?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the rule already understands those four. get(this, 'foo') and getProperties(this, 'foo', ...) are read like this.foo: the rule takes the names from the string arguments and counts them as uses (the CallExpression visitor further down). set / setProperties only write a named key. So in all four, this does not leave the class, and we know exactly which property is touched.

If they counted as a passed this, any classic class that uses get(this, ...) would turn the rule off. I tried removing the check: 3 existing invalid tests start passing as valid (the get/getProperties ones for a class and for Component.extend, and the set(this, 'unrelatedProp', 1) one).

@NullVoxPopuli
NullVoxPopuli merged commit decc2bc into ember-cli:master Nov 18, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

False positive for no-unused-services when component is passed to function expressions

2 participants