From 56b121669fe749c7625c3860508fc393482495c6 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Tue, 17 Nov 2026 00:21:57 +0530 Subject: [PATCH 1/5] Skip classes that pass `this` to a call in no-unused-services 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 --- docs/rules/no-unused-services.md | 2 + lib/rules/no-unused-services.js | 109 +++++++++++++++++++++++++- tests/lib/rules/no-unused-services.js | 83 ++++++++++++-------- 3 files changed, 159 insertions(+), 35 deletions(-) diff --git a/docs/rules/no-unused-services.md b/docs/rules/no-unused-services.md index ca84a87480..c9b6a3d3db 100644 --- a/docs/rules/no-unused-services.md +++ b/docs/rules/no-unused-services.md @@ -14,6 +14,8 @@ By removing unused service injections, we can reduce the amount of code we have - A mixin or parent class that the current class extends from - A child class that extends from the current class +The rule also skips any class that passes its `this` to a function or `new` call (for example `helper(this)`, `obj.method(this)`, `new Foo(this)` or `helper({ owner: this })`). The called code could use any service, so the rule cannot tell which ones are unused. `this` inside a nested regular `function` or nested class is a different `this` and does not count. Neither does `get`, `set`, `getProperties` or `setProperties` from `@ember/object`. + Given these significant limitations, the rule is not currently recommended for production usage, but some may find it useful to experiment with. The rule will not be added to the `recommended` configuration unless the limitations can be addressed. ## Examples diff --git a/lib/rules/no-unused-services.js b/lib/rules/no-unused-services.js index 6d7c7c2855..34451095ca 100644 --- a/lib/rules/no-unused-services.js +++ b/lib/rules/no-unused-services.js @@ -40,8 +40,13 @@ module.exports = { let importedInjectName; let importedObserverName; let importedObservesName; + let importedSetName; + let importedSetPropertiesName; const macros = getMacros(); const importedMacros = {}; + // Classes that pass their `this` to a call. We cannot know what the call + // reads from it, so the rule is turned off for them. + const classesPassingThis = new Set(); /** * Gets the trailing comma token of the given node. @@ -60,8 +65,8 @@ module.exports = { */ function reportInstances() { const currentClass = classStack.pop(); - const { services, uses } = currentClass; - if (Object.keys(services).length === 0) { + const { node: classNode, services, uses } = currentClass; + if (Object.keys(services).length === 0 || classesPassingThis.has(classNode)) { return; } @@ -92,6 +97,93 @@ module.exports = { } } + /** + * Checks if `this` is passed to a function call or `new` expression, either + * directly (`fn(this)`) or inside an array or object (`fn({ owner: this })`). + * `get(this, 'foo')` and similar calls from `@ember/object` do not count. + * @param {ThisExpression} node + * @returns {boolean} + */ + function isThisPassedToCall(node) { + let child = node; + let parent = node.parent; + while ( + parent.type === 'ArrayExpression' || + parent.type === 'ObjectExpression' || + parent.type === 'SpreadElement' || + (parent.type === 'Property' && parent.value === child) + ) { + child = parent; + parent = parent.parent; + } + if ( + !['CallExpression', 'OptionalCallExpression', 'NewExpression'].includes(parent.type) || + !parent.arguments.includes(child) + ) { + return false; + } + const emberObjectFunctions = [ + importedGetName, + importedGetPropertiesName, + importedSetName, + importedSetPropertiesName, + ].filter(Boolean); + return !( + parent.arguments[0] === node && + parent.callee.type === 'Identifier' && + emberObjectFunctions.includes(parent.callee.name) + ); + } + + /** + * Finds the class whose instance `this` refers to. Arrow functions keep the + * outer `this`, while regular functions and nested classes have their own. + * @param {ThisExpression} node + * @returns {ASTNode|undefined} the class node, or the `Foo.extend()` call of a classic class + */ + function getThisClass(node) { + for (let current = node; current.parent; current = current.parent) { + const parent = current.parent; + if (current.type === 'FunctionExpression' || current.type === 'FunctionDeclaration') { + return getFunctionClass(current); + } + if ( + (types.isClassPropertyOrPropertyDefinition(parent) && parent.value === current) || + parent.type === 'StaticBlock' + ) { + // Class field value or static block: parent -> ClassBody -> class + return parent.parent.parent; + } + } + return undefined; + } + + /** + * @param {FunctionExpression|FunctionDeclaration} fn + * @returns {ASTNode|undefined} the class that `fn` is a method of + */ + function getFunctionClass(fn) { + if (fn.parent.type === 'MethodDefinition' && fn.parent.value === fn) { + // Native class method: MethodDefinition -> ClassBody -> class + return fn.parent.parent.parent; + } + // Classic class method, maybe wrapped in a call like `computed(function () {})` + let current = fn; + for (;;) { + const parent = current.parent; + if (parent.type === 'Property' && parent.value === current) { + current = parent.parent; + } else if (parent.type === 'CallExpression' && parent.arguments.includes(current)) { + if (emberUtils.isAnyEmberCoreModule(context, parent)) { + return parent; + } + current = parent; + } else { + return undefined; + } + } + } + // Handle either ClassProperty (ESLint v7) or PropertyDefinition (ESLint v8). function visitClassPropertyOrPropertyDefinition(node) { // Handles: @@ -127,6 +219,10 @@ module.exports = { getImportIdentifier(node, '@ember/object', 'getProperties'); importedObserverName = importedObserverName || getImportIdentifier(node, '@ember/object', 'observer'); + importedSetName = importedSetName || getImportIdentifier(node, '@ember/object', 'set'); + importedSetPropertiesName = + importedSetPropertiesName || + getImportIdentifier(node, '@ember/object', 'setProperties'); } if (node.source.value === '@ember/object/computed') { for (const spec of node.specifiers) { @@ -370,6 +466,15 @@ module.exports = { currentClass.uses.add(name); } }, + // fn(this), new Foo(this) + ThisExpression(node) { + if (classStack.size() > 0 && isThisPassedToCall(node)) { + const classNode = getThisClass(node); + if (classNode) { + classesPassingThis.add(classNode); + } + } + }, VariableDeclarator(node) { const currentClass = classStack.peek(); if ( diff --git a/tests/lib/rules/no-unused-services.js b/tests/lib/rules/no-unused-services.js index 6cdf113457..d24257ff4f 100644 --- a/tests/lib/rules/no-unused-services.js +++ b/tests/lib/rules/no-unused-services.js @@ -188,8 +188,58 @@ ruleTester.run('no-unused-services', rule, { `${SERVICE_IMPORT} Component.extend({});`, 'const foo = service();', "import ComputedProperty from '@ember/object/computed';", + /* `this` is passed somewhere, so the rule is turned off for the class */ + `${SERVICE_IMPORT} const helper = (c) => c.${SERVICE_NAME}; class MyClass { @service() ${SERVICE_NAME}; get foo() { return helper(this); } }`, + `${SERVICE_IMPORT} import helper from './helper'; class MyClass { @service() ${SERVICE_NAME}; foo() { return helper(1, this); } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return this.other.method(this); } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return new Foo(this); } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo = () => helper({ owner: this }); }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return helper(...[this]); } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return [1].map(() => helper(this)); } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; constructor() { super(); register(this); } }`, + `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo() { return helper(this); } });`, + // `get` is not from @ember/object here, so it is an unknown function that gets `this` + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; fooFunc() {${emberObjectUses1}} }`, + `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), fooFunc() {${emberObjectUses1}} });`, + `${SERVICE_IMPORT}${EO_IMPORTS} Component.extend({ ${SERVICE_NAME}: service(), foo: computed(function () { return helper(this); }) });`, ], invalid: [ + /* `this` is not passed anywhere, or the `this` that is passed is not the class instance */ + { + code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return helper(this.other); } }`, + output: null, + errors: [{ messageId: 'main' }], + }, + { + code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return function () { return helper(this); }; } }`, + output: null, + errors: [{ messageId: 'main' }], + }, + { + code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return class { bar() { return helper(this); } }; } }`, + output: null, + errors: [{ messageId: 'main' }], + }, + { + code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { class Inner { bar() { return helper(this); } } return Inner; } }`, + output: null, + errors: [{ messageId: 'main' }], + }, + { + code: `${SERVICE_IMPORT} import {set} from '@ember/object'; class MyClass { @service() ${SERVICE_NAME}; foo() { set(this, 'unrelatedProp', 1); } }`, + output: null, + errors: [{ messageId: 'main' }], + }, + { + code: `${SERVICE_IMPORT} helper(this); class MyClass { @service() ${SERVICE_NAME}; }`, + output: null, + errors: [{ messageId: 'main' }], + }, + { + code: `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo() { return [1].map(function () { return helper(this); }); } });`, + output: null, + errors: [{ messageId: 'main' }], + }, { code: `${SERVICE_IMPORT} class MyClass { @service('foo') ${SERVICE_NAME}; fooFunc() {${nonUses}} }`, output: null, @@ -303,39 +353,6 @@ ruleTester.run('no-unused-services', rule, { }, ], }, - /* Using get/getProperties without @ember/object import */ - { - code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; fooFunc() {${emberObjectUses1}} }`, - output: null, - errors: [ - { - messageId: 'main', - suggestions: [ - { - messageId: 'removeServiceInjection', - output: `${SERVICE_IMPORT} class MyClass { fooFunc() {${emberObjectUses1}} }`, - }, - ], - // type could be ClassProperty (ESLint v7) or PropertyDefinition (ESLint v8) - }, - ], - }, - { - code: `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), fooFunc() {${emberObjectUses1}} });`, - output: null, - errors: [ - { - messageId: 'main', - suggestions: [ - { - messageId: 'removeServiceInjection', - output: `${SERVICE_IMPORT} Component.extend({ fooFunc() {${emberObjectUses1}} });`, - }, - ], - type: 'Property', - }, - ], - }, /* Using get/getProperties with @ember/object import for an unrelatedProp */ { code: `${SERVICE_IMPORT}${EO_IMPORTS} class MyClass { @service() ${SERVICE_NAME}; fooFunc() {${emberObjectUses2}} }`, From 6fd02f4a40493a01ad35307439fb54a46d822746 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Tue, 17 Nov 2026 03:03:15 +0530 Subject: [PATCH 2/5] Track `this` with visitors instead of walking parents in no-unused-services --- lib/rules/no-unused-services.js | 180 +++++++++++++++----------- tests/lib/rules/no-unused-services.js | 11 ++ 2 files changed, 115 insertions(+), 76 deletions(-) diff --git a/lib/rules/no-unused-services.js b/lib/rules/no-unused-services.js index 34451095ca..98d213c192 100644 --- a/lib/rules/no-unused-services.js +++ b/lib/rules/no-unused-services.js @@ -97,30 +97,34 @@ module.exports = { } } + // `thisStack` tells which class instance `this` is at the current point of + // the traversal. Each entry is `{ node, owner, nextFunctionOwner }`: + // - `owner`: class whose instance `this` is here (undefined if none) + // - `nextFunctionOwner`: inside a classic class property (`foo: ...`), a regular + // function gets the class instance as `this` (`foo() {}`, `computed(function () {})`) + // Arrow functions keep the outer `this`, so they do not get an entry. + const thisStack = new Stack(); + thisStack.push({ node: null, owner: undefined, nextFunctionOwner: undefined }); + + function enterThisScope(node, owner, nextFunctionOwner) { + thisStack.push({ node, owner, nextFunctionOwner }); + } + + function exitThisScope(node) { + if (thisStack.peek().node === node) { + thisStack.pop(); + } + } + /** - * Checks if `this` is passed to a function call or `new` expression, either - * directly (`fn(this)`) or inside an array or object (`fn({ owner: this })`). + * Marks the class as passing `this` when the call gets the class instance. * `get(this, 'foo')` and similar calls from `@ember/object` do not count. - * @param {ThisExpression} node - * @returns {boolean} + * @param {CallExpression|NewExpression} node */ - function isThisPassedToCall(node) { - let child = node; - let parent = node.parent; - while ( - parent.type === 'ArrayExpression' || - parent.type === 'ObjectExpression' || - parent.type === 'SpreadElement' || - (parent.type === 'Property' && parent.value === child) - ) { - child = parent; - parent = parent.parent; - } - if ( - !['CallExpression', 'OptionalCallExpression', 'NewExpression'].includes(parent.type) || - !parent.arguments.includes(child) - ) { - return false; + function checkThisPassedToCall(node) { + const owner = thisStack.peek().owner; + if (!owner || classesPassingThis.has(owner)) { + return; } const emberObjectFunctions = [ importedGetName, @@ -128,64 +132,47 @@ module.exports = { importedSetName, importedSetPropertiesName, ].filter(Boolean); - return !( - parent.arguments[0] === node && - parent.callee.type === 'Identifier' && - emberObjectFunctions.includes(parent.callee.name) - ); + const args = + types.isThisExpression(node.arguments[0]) && + node.callee.type === 'Identifier' && + emberObjectFunctions.includes(node.callee.name) + ? node.arguments.slice(1) + : node.arguments; + if (args.some(containsPassedThis)) { + classesPassingThis.add(owner); + } } - /** - * Finds the class whose instance `this` refers to. Arrow functions keep the - * outer `this`, while regular functions and nested classes have their own. - * @param {ThisExpression} node - * @returns {ASTNode|undefined} the class node, or the `Foo.extend()` call of a classic class - */ - function getThisClass(node) { - for (let current = node; current.parent; current = current.parent) { - const parent = current.parent; - if (current.type === 'FunctionExpression' || current.type === 'FunctionDeclaration') { - return getFunctionClass(current); - } - if ( - (types.isClassPropertyOrPropertyDefinition(parent) && parent.value === current) || - parent.type === 'StaticBlock' - ) { - // Class field value or static block: parent -> ClassBody -> class - return parent.parent.parent; - } - } - return undefined; + function enterFunction(node) { + const owner = + node.parent.type === 'MethodDefinition' && node.parent.value === node + ? node.parent.parent.parent // MethodDefinition -> ClassBody -> class + : thisStack.peek().nextFunctionOwner; + enterThisScope(node, owner, undefined); } /** - * @param {FunctionExpression|FunctionDeclaration} fn - * @returns {ASTNode|undefined} the class that `fn` is a method of + * @param {Property} node + * @returns {ASTNode|undefined} the `Foo.extend()` call if `node` is one of its properties */ - function getFunctionClass(fn) { - if (fn.parent.type === 'MethodDefinition' && fn.parent.value === fn) { - // Native class method: MethodDefinition -> ClassBody -> class - return fn.parent.parent.parent; - } - // Classic class method, maybe wrapped in a call like `computed(function () {})` - let current = fn; - for (;;) { - const parent = current.parent; - if (parent.type === 'Property' && parent.value === current) { - current = parent.parent; - } else if (parent.type === 'CallExpression' && parent.arguments.includes(current)) { - if (emberUtils.isAnyEmberCoreModule(context, parent)) { - return parent; - } - current = parent; - } else { - return undefined; - } + function getClassicClassOfProperty(node) { + const currentClass = classStack.peek(); + if ( + currentClass && + currentClass.node.type === 'CallExpression' && + node.parent.type === 'ObjectExpression' && + currentClass.node.arguments.includes(node.parent) + ) { + return currentClass.node; } + return undefined; } // Handle either ClassProperty (ESLint v7) or PropertyDefinition (ESLint v8). function visitClassPropertyOrPropertyDefinition(node) { + // A class field value gets the class instance as `this`. + enterThisScope(node, node.static ? undefined : node.parent.parent, undefined); + // Handles: // @service(...) foo; // If Ember and Ember.inject weren't imported, skip out early @@ -257,6 +244,7 @@ module.exports = { }, // eslint-disable-next-line complexity CallExpression(node) { + checkThisPassedToCall(node); if (emberUtils.isAnyEmberCoreModule(context, node)) { // Classic class classStack.push({ node, services: {}, uses: new Set() }); @@ -424,6 +412,11 @@ module.exports = { }, // foo: service(...) Property(node) { + const classicClass = getClassicClassOfProperty(node); + if (classicClass) { + enterThisScope(node, thisStack.peek().owner, classicClass); + } + // If Ember and Ember.inject weren't imported, skip out early if (!importedEmberName && !importedInjectName) { return; @@ -466,15 +459,18 @@ module.exports = { currentClass.uses.add(name); } }, - // fn(this), new Foo(this) - ThisExpression(node) { - if (classStack.size() > 0 && isThisPassedToCall(node)) { - const classNode = getThisClass(node); - if (classNode) { - classesPassingThis.add(classNode); - } - } + 'Property:exit': exitThisScope, + 'ClassProperty:exit': exitThisScope, + 'PropertyDefinition:exit': exitThisScope, + StaticBlock(node) { + enterThisScope(node, undefined, undefined); }, + 'StaticBlock:exit': exitThisScope, + 'FunctionExpression, FunctionDeclaration': enterFunction, + 'FunctionExpression, FunctionDeclaration:exit': exitThisScope, + // fn(this), new Foo(this) + NewExpression: checkThisPassedToCall, + OptionalCallExpression: checkThisPassedToCall, VariableDeclarator(node) { const currentClass = classStack.peek(); if ( @@ -500,3 +496,35 @@ module.exports = { function splitValue(value) { return value ? value.split('.')[0] : undefined; } + +/** + * Checks if `this` is a call or `new` argument, either directly (`fn(this)`) + * or inside an array or object (`fn({ owner: this })`, `fn(...[this])`). + * Only goes down into the arguments, never up the tree. + * @param {ASTNode} node + * @returns {boolean} + */ +function containsPassedThis(node) { + if (!node) { + return false; + } + switch (node.type) { + case 'ThisExpression': { + return true; + } + case 'SpreadElement': { + return containsPassedThis(node.argument); + } + case 'ArrayExpression': { + return node.elements.some(containsPassedThis); + } + case 'ObjectExpression': { + return node.properties.some((prop) => + containsPassedThis(prop.type === 'Property' ? prop.value : prop) + ); + } + default: { + return false; + } + } +} diff --git a/tests/lib/rules/no-unused-services.js b/tests/lib/rules/no-unused-services.js index d24257ff4f..cb7a483cda 100644 --- a/tests/lib/rules/no-unused-services.js +++ b/tests/lib/rules/no-unused-services.js @@ -197,6 +197,7 @@ ruleTester.run('no-unused-services', rule, { `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return helper(...[this]); } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return [1].map(() => helper(this)); } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; constructor() { super(); register(this); } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo = helper(this); }`, `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo() { return helper(this); } });`, // `get` is not from @ember/object here, so it is an unknown function that gets `this` `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; fooFunc() {${emberObjectUses1}} }`, @@ -235,6 +236,16 @@ ruleTester.run('no-unused-services', rule, { output: null, errors: [{ messageId: 'main' }], }, + { + code: `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo: helper(this) });`, + output: null, + errors: [{ messageId: 'main' }], + }, + { + code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; static foo = helper(this); }`, + output: null, + errors: [{ messageId: 'main' }], + }, { code: `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo() { return [1].map(function () { return helper(this); }); } });`, output: null, From 4e8d14c060a1783a5b3dc0547bb5fbf3042dc421 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Tue, 17 Nov 2026 03:21:49 +0530 Subject: [PATCH 3/5] Use a ThisExpression visitor to find a passed `this` in no-unused-services --- lib/rules/no-unused-services.js | 77 ++++++++++----------------- tests/lib/rules/no-unused-services.js | 7 +++ 2 files changed, 36 insertions(+), 48 deletions(-) diff --git a/lib/rules/no-unused-services.js b/lib/rules/no-unused-services.js index 98d213c192..18ec776a97 100644 --- a/lib/rules/no-unused-services.js +++ b/lib/rules/no-unused-services.js @@ -117,30 +117,45 @@ module.exports = { } /** - * Marks the class as passing `this` when the call gets the class instance. - * `get(this, 'foo')` and similar calls from `@ember/object` do not count. - * @param {CallExpression|NewExpression} node + * Turns the rule off for the class when its `this` leaves the class + * (`fn(this)`, `new Foo(this)`, `{ owner: this }`, `[this]`, `const self = this`). + * `get(this, 'foo')` / `set(this, ...)` from `@ember/object` do not count. + * Only looks at the direct parent of `this`, so nothing walks up the tree. + * @param {ThisExpression} node */ - function checkThisPassedToCall(node) { + function checkThisPassed(node) { const owner = thisStack.peek().owner; if (!owner || classesPassingThis.has(owner)) { return; } + const parent = node.parent; + const isPassed = + (['CallExpression', 'NewExpression', 'OptionalCallExpression'].includes(parent.type) && + parent.arguments.includes(node)) || + ['ArrayExpression', 'SpreadElement'].includes(parent.type) || + (parent.type === 'Property' && parent.value === node) || + (parent.type === 'AssignmentExpression' && parent.right === node) || + (parent.type === 'VariableDeclarator' && + parent.init === node && + parent.id.type === 'Identifier'); + if (!isPassed) { + return; + } const emberObjectFunctions = [ importedGetName, importedGetPropertiesName, importedSetName, importedSetPropertiesName, ].filter(Boolean); - const args = - types.isThisExpression(node.arguments[0]) && - node.callee.type === 'Identifier' && - emberObjectFunctions.includes(node.callee.name) - ? node.arguments.slice(1) - : node.arguments; - if (args.some(containsPassedThis)) { - classesPassingThis.add(owner); + if ( + parent.type === 'CallExpression' && + parent.arguments[0] === node && + parent.callee.type === 'Identifier' && + emberObjectFunctions.includes(parent.callee.name) + ) { + return; } + classesPassingThis.add(owner); } function enterFunction(node) { @@ -244,7 +259,6 @@ module.exports = { }, // eslint-disable-next-line complexity CallExpression(node) { - checkThisPassedToCall(node); if (emberUtils.isAnyEmberCoreModule(context, node)) { // Classic class classStack.push({ node, services: {}, uses: new Set() }); @@ -468,9 +482,8 @@ module.exports = { 'StaticBlock:exit': exitThisScope, 'FunctionExpression, FunctionDeclaration': enterFunction, 'FunctionExpression, FunctionDeclaration:exit': exitThisScope, - // fn(this), new Foo(this) - NewExpression: checkThisPassedToCall, - OptionalCallExpression: checkThisPassedToCall, + // fn(this), new Foo(this), { owner: this } + ThisExpression: checkThisPassed, VariableDeclarator(node) { const currentClass = classStack.peek(); if ( @@ -496,35 +509,3 @@ module.exports = { function splitValue(value) { return value ? value.split('.')[0] : undefined; } - -/** - * Checks if `this` is a call or `new` argument, either directly (`fn(this)`) - * or inside an array or object (`fn({ owner: this })`, `fn(...[this])`). - * Only goes down into the arguments, never up the tree. - * @param {ASTNode} node - * @returns {boolean} - */ -function containsPassedThis(node) { - if (!node) { - return false; - } - switch (node.type) { - case 'ThisExpression': { - return true; - } - case 'SpreadElement': { - return containsPassedThis(node.argument); - } - case 'ArrayExpression': { - return node.elements.some(containsPassedThis); - } - case 'ObjectExpression': { - return node.properties.some((prop) => - containsPassedThis(prop.type === 'Property' ? prop.value : prop) - ); - } - default: { - return false; - } - } -} diff --git a/tests/lib/rules/no-unused-services.js b/tests/lib/rules/no-unused-services.js index cb7a483cda..e653d88592 100644 --- a/tests/lib/rules/no-unused-services.js +++ b/tests/lib/rules/no-unused-services.js @@ -195,6 +195,8 @@ ruleTester.run('no-unused-services', rule, { `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return new Foo(this); } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo = () => helper({ owner: this }); }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return helper(...[this]); } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { const self = this; return helper(self); } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { this.items = [this]; } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return [1].map(() => helper(this)); } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; constructor() { super(); register(this); } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo = helper(this); }`, @@ -231,6 +233,11 @@ ruleTester.run('no-unused-services', rule, { output: null, errors: [{ messageId: 'main' }], }, + { + code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { const { other } = this; return other === this; } }`, + output: null, + errors: [{ messageId: 'main' }], + }, { code: `${SERVICE_IMPORT} helper(this); class MyClass { @service() ${SERVICE_NAME}; }`, output: null, From 9913b0a2df52783c589baadc71719228d74619ec Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Tue, 17 Nov 2026 03:40:18 +0530 Subject: [PATCH 4/5] Find the class of `this` with the scope manager in no-unused-services 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. --- docs/rules/no-unused-services.md | 2 +- lib/rules/no-unused-services.js | 141 ++++++++++---------------- tests/lib/rules/no-unused-services.js | 16 ++- 3 files changed, 68 insertions(+), 91 deletions(-) diff --git a/docs/rules/no-unused-services.md b/docs/rules/no-unused-services.md index c9b6a3d3db..9da8156e3a 100644 --- a/docs/rules/no-unused-services.md +++ b/docs/rules/no-unused-services.md @@ -14,7 +14,7 @@ By removing unused service injections, we can reduce the amount of code we have - A mixin or parent class that the current class extends from - A child class that extends from the current class -The rule also skips any class that passes its `this` to a function or `new` call (for example `helper(this)`, `obj.method(this)`, `new Foo(this)` or `helper({ owner: this })`). The called code could use any service, so the rule cannot tell which ones are unused. `this` inside a nested regular `function` or nested class is a different `this` and does not count. Neither does `get`, `set`, `getProperties` or `setProperties` from `@ember/object`. +The rule also skips any class that passes its `this` to a function or `new` call (for example `helper(this)`, `obj.method(this)` or `new Foo(this)`). The called code could use any service, so the rule cannot tell which ones are unused. `this` inside a nested regular `function` or nested class is a different `this` and does not count. Neither does `get`, `set`, `getProperties` or `setProperties` from `@ember/object`. Given these significant limitations, the rule is not currently recommended for production usage, but some may find it useful to experiment with. The rule will not be added to the `recommended` configuration unless the limitations can be addressed. diff --git a/lib/rules/no-unused-services.js b/lib/rules/no-unused-services.js index 18ec776a97..90b1f5a55f 100644 --- a/lib/rules/no-unused-services.js +++ b/lib/rules/no-unused-services.js @@ -10,6 +10,18 @@ const { } = require('../utils/computed-property-macros'); const Stack = require('../utils/stack'); +/** + * @param {ASTNode} node + * @returns {boolean} whether `node` is the value of a class method or field + */ +function isClassMemberValue(node) { + const { parent } = node; + return ( + ['MethodDefinition', 'PropertyDefinition', 'ClassProperty'].includes(parent.type) && + parent.value === node + ); +} + /** @type {import('eslint').Rule.RuleModule} */ module.exports = { meta: { @@ -97,97 +109,67 @@ module.exports = { } } - // `thisStack` tells which class instance `this` is at the current point of - // the traversal. Each entry is `{ node, owner, nextFunctionOwner }`: - // - `owner`: class whose instance `this` is here (undefined if none) - // - `nextFunctionOwner`: inside a classic class property (`foo: ...`), a regular - // function gets the class instance as `this` (`foo() {}`, `computed(function () {})`) - // Arrow functions keep the outer `this`, so they do not get an entry. - const thisStack = new Stack(); - thisStack.push({ node: null, owner: undefined, nextFunctionOwner: undefined }); - - function enterThisScope(node, owner, nextFunctionOwner) { - thisStack.push({ node, owner, nextFunctionOwner }); - } - - function exitThisScope(node) { - if (thisStack.peek().node === node) { - thisStack.pop(); + /** + * Uses the scope manager to find the class whose instance `this` is. + * Arrow functions keep the outer `this`, so their scopes are skipped. + * @param {ThisExpression} node + * @returns {ASTNode|undefined} the class, or undefined if `this` is not a class instance + */ + function getThisClass(node) { + let scope = sourceCode.getScope(node); + while (scope.block.type === 'ArrowFunctionExpression' && !isClassMemberValue(scope.block)) { + scope = scope.upper; } + const { block } = scope; + const parent = block.parent; + if (!parent) { + return undefined; + } + // Method `foo() {}` or field `foo = ...`. Static ones get the class itself as `this`. + if (isClassMemberValue(block)) { + return parent.static ? undefined : parent.parent.parent; + } + // Classic class: `foo() {}` or `foo: computed(function () {})` in `Foo.extend({...})`. + const currentClass = classStack.peek(); + if (block.type === 'FunctionExpression' && currentClass) { + const property = parent.type === 'CallExpression' ? parent.parent : parent; + if ( + property.type === 'Property' && + property.parent.type === 'ObjectExpression' && + currentClass.node.type === 'CallExpression' && + currentClass.node.arguments.includes(property.parent) + ) { + return currentClass.node; + } + } + return undefined; } /** - * Turns the rule off for the class when its `this` leaves the class - * (`fn(this)`, `new Foo(this)`, `{ owner: this }`, `[this]`, `const self = this`). + * Turns the rule off for the class when it passes its `this` to a call: + * `fn(this)`, `obj.method(this)`, `new Foo(this)`, `fn?.(this)`. * `get(this, 'foo')` / `set(this, ...)` from `@ember/object` do not count. - * Only looks at the direct parent of `this`, so nothing walks up the tree. * @param {ThisExpression} node */ function checkThisPassed(node) { - const owner = thisStack.peek().owner; - if (!owner || classesPassingThis.has(owner)) { - return; - } - const parent = node.parent; - const isPassed = - (['CallExpression', 'NewExpression', 'OptionalCallExpression'].includes(parent.type) && - parent.arguments.includes(node)) || - ['ArrayExpression', 'SpreadElement'].includes(parent.type) || - (parent.type === 'Property' && parent.value === node) || - (parent.type === 'AssignmentExpression' && parent.right === node) || - (parent.type === 'VariableDeclarator' && - parent.init === node && - parent.id.type === 'Identifier'); - if (!isPassed) { - return; - } + const { callee } = node.parent; const emberObjectFunctions = [ importedGetName, importedGetPropertiesName, importedSetName, importedSetPropertiesName, ].filter(Boolean); - if ( - parent.type === 'CallExpression' && - parent.arguments[0] === node && - parent.callee.type === 'Identifier' && - emberObjectFunctions.includes(parent.callee.name) - ) { + if (callee.type === 'Identifier' && emberObjectFunctions.includes(callee.name)) { return; } - classesPassingThis.add(owner); - } - - function enterFunction(node) { - const owner = - node.parent.type === 'MethodDefinition' && node.parent.value === node - ? node.parent.parent.parent // MethodDefinition -> ClassBody -> class - : thisStack.peek().nextFunctionOwner; - enterThisScope(node, owner, undefined); - } - - /** - * @param {Property} node - * @returns {ASTNode|undefined} the `Foo.extend()` call if `node` is one of its properties - */ - function getClassicClassOfProperty(node) { - const currentClass = classStack.peek(); - if ( - currentClass && - currentClass.node.type === 'CallExpression' && - node.parent.type === 'ObjectExpression' && - currentClass.node.arguments.includes(node.parent) - ) { - return currentClass.node; + const thisClass = getThisClass(node); + if (thisClass) { + classesPassingThis.add(thisClass); } - return undefined; } // Handle either ClassProperty (ESLint v7) or PropertyDefinition (ESLint v8). function visitClassPropertyOrPropertyDefinition(node) { - // A class field value gets the class instance as `this`. - enterThisScope(node, node.static ? undefined : node.parent.parent, undefined); - // Handles: // @service(...) foo; // If Ember and Ember.inject weren't imported, skip out early @@ -426,11 +408,6 @@ module.exports = { }, // foo: service(...) Property(node) { - const classicClass = getClassicClassOfProperty(node); - if (classicClass) { - enterThisScope(node, thisStack.peek().owner, classicClass); - } - // If Ember and Ember.inject weren't imported, skip out early if (!importedEmberName && !importedInjectName) { return; @@ -473,17 +450,9 @@ module.exports = { currentClass.uses.add(name); } }, - 'Property:exit': exitThisScope, - 'ClassProperty:exit': exitThisScope, - 'PropertyDefinition:exit': exitThisScope, - StaticBlock(node) { - enterThisScope(node, undefined, undefined); - }, - 'StaticBlock:exit': exitThisScope, - 'FunctionExpression, FunctionDeclaration': enterFunction, - 'FunctionExpression, FunctionDeclaration:exit': exitThisScope, - // fn(this), new Foo(this), { owner: this } - ThisExpression: checkThisPassed, + // fn(this), new Foo(this) + 'CallExpression > ThisExpression.arguments, NewExpression > ThisExpression.arguments': + checkThisPassed, VariableDeclarator(node) { const currentClass = classStack.peek(); if ( diff --git a/tests/lib/rules/no-unused-services.js b/tests/lib/rules/no-unused-services.js index e653d88592..51a077f1c6 100644 --- a/tests/lib/rules/no-unused-services.js +++ b/tests/lib/rules/no-unused-services.js @@ -193,13 +193,11 @@ ruleTester.run('no-unused-services', rule, { `${SERVICE_IMPORT} import helper from './helper'; class MyClass { @service() ${SERVICE_NAME}; foo() { return helper(1, this); } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return this.other.method(this); } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return new Foo(this); } }`, - `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo = () => helper({ owner: this }); }`, - `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return helper(...[this]); } }`, - `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { const self = this; return helper(self); } }`, - `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { this.items = [this]; } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return [1].map(() => helper(this)); } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; constructor() { super(); register(this); } }`, `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo = helper(this); }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo = () => helper(this); }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return helper?.(this); } }`, `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo() { return helper(this); } });`, // `get` is not from @ember/object here, so it is an unknown function that gets `this` `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; fooFunc() {${emberObjectUses1}} }`, @@ -253,6 +251,16 @@ ruleTester.run('no-unused-services', rule, { output: null, errors: [{ messageId: 'main' }], }, + { + code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; static foo() { return helper(this); } }`, + output: null, + errors: [{ messageId: 'main' }], + }, + { + code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; static { helper(this); } }`, + output: null, + errors: [{ messageId: 'main' }], + }, { code: `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo() { return [1].map(function () { return helper(this); }); } });`, output: null, From 1cb3713bdaff3a136836fda3f953343a5102457e Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Tue, 17 Nov 2026 04:56:41 +0530 Subject: [PATCH 5/5] Use the current class from classStack for a passed `this` in no-unused-services --- docs/rules/no-unused-services.md | 2 +- lib/rules/no-unused-services.js | 67 ++++----------------------- tests/lib/rules/no-unused-services.js | 45 ++++-------------- 3 files changed, 19 insertions(+), 95 deletions(-) diff --git a/docs/rules/no-unused-services.md b/docs/rules/no-unused-services.md index 9da8156e3a..e00ab4838d 100644 --- a/docs/rules/no-unused-services.md +++ b/docs/rules/no-unused-services.md @@ -14,7 +14,7 @@ By removing unused service injections, we can reduce the amount of code we have - A mixin or parent class that the current class extends from - A child class that extends from the current class -The rule also skips any class that passes its `this` to a function or `new` call (for example `helper(this)`, `obj.method(this)` or `new Foo(this)`). The called code could use any service, so the rule cannot tell which ones are unused. `this` inside a nested regular `function` or nested class is a different `this` and does not count. Neither does `get`, `set`, `getProperties` or `setProperties` from `@ember/object`. +The rule also skips any class that passes its `this` to a function or `new` call (for example `helper(this)`, `obj.method(this)` or `new Foo(this)`). The called code could use any service, so the rule cannot tell which ones are unused. Calls to `get`, `set`, `getProperties` or `setProperties` from `@ember/object` do not count. Given these significant limitations, the rule is not currently recommended for production usage, but some may find it useful to experiment with. The rule will not be added to the `recommended` configuration unless the limitations can be addressed. diff --git a/lib/rules/no-unused-services.js b/lib/rules/no-unused-services.js index 90b1f5a55f..e6ede09dfc 100644 --- a/lib/rules/no-unused-services.js +++ b/lib/rules/no-unused-services.js @@ -10,18 +10,6 @@ const { } = require('../utils/computed-property-macros'); const Stack = require('../utils/stack'); -/** - * @param {ASTNode} node - * @returns {boolean} whether `node` is the value of a class method or field - */ -function isClassMemberValue(node) { - const { parent } = node; - return ( - ['MethodDefinition', 'PropertyDefinition', 'ClassProperty'].includes(parent.type) && - parent.value === node - ); -} - /** @type {import('eslint').Rule.RuleModule} */ module.exports = { meta: { @@ -56,9 +44,6 @@ module.exports = { let importedSetPropertiesName; const macros = getMacros(); const importedMacros = {}; - // Classes that pass their `this` to a call. We cannot know what the call - // reads from it, so the rule is turned off for them. - const classesPassingThis = new Set(); /** * Gets the trailing comma token of the given node. @@ -77,8 +62,9 @@ module.exports = { */ function reportInstances() { const currentClass = classStack.pop(); - const { node: classNode, services, uses } = currentClass; - if (Object.keys(services).length === 0 || classesPassingThis.has(classNode)) { + const { services, uses, passesThis } = currentClass; + // A class that passes its `this` to a call: we cannot know what the call reads from it. + if (Object.keys(services).length === 0 || passesThis) { return; } @@ -110,48 +96,16 @@ module.exports = { } /** - * Uses the scope manager to find the class whose instance `this` is. - * Arrow functions keep the outer `this`, so their scopes are skipped. - * @param {ThisExpression} node - * @returns {ASTNode|undefined} the class, or undefined if `this` is not a class instance - */ - function getThisClass(node) { - let scope = sourceCode.getScope(node); - while (scope.block.type === 'ArrowFunctionExpression' && !isClassMemberValue(scope.block)) { - scope = scope.upper; - } - const { block } = scope; - const parent = block.parent; - if (!parent) { - return undefined; - } - // Method `foo() {}` or field `foo = ...`. Static ones get the class itself as `this`. - if (isClassMemberValue(block)) { - return parent.static ? undefined : parent.parent.parent; - } - // Classic class: `foo() {}` or `foo: computed(function () {})` in `Foo.extend({...})`. - const currentClass = classStack.peek(); - if (block.type === 'FunctionExpression' && currentClass) { - const property = parent.type === 'CallExpression' ? parent.parent : parent; - if ( - property.type === 'Property' && - property.parent.type === 'ObjectExpression' && - currentClass.node.type === 'CallExpression' && - currentClass.node.arguments.includes(property.parent) - ) { - return currentClass.node; - } - } - return undefined; - } - - /** - * Turns the rule off for the class when it passes its `this` to a call: + * Turns the rule off for the current class when it passes `this` to a call: * `fn(this)`, `obj.method(this)`, `new Foo(this)`, `fn?.(this)`. * `get(this, 'foo')` / `set(this, ...)` from `@ember/object` do not count. * @param {ThisExpression} node */ function checkThisPassed(node) { + const currentClass = classStack.peek(); + if (!currentClass) { + return; + } const { callee } = node.parent; const emberObjectFunctions = [ importedGetName, @@ -162,10 +116,7 @@ module.exports = { if (callee.type === 'Identifier' && emberObjectFunctions.includes(callee.name)) { return; } - const thisClass = getThisClass(node); - if (thisClass) { - classesPassingThis.add(thisClass); - } + currentClass.passesThis = true; } // Handle either ClassProperty (ESLint v7) or PropertyDefinition (ESLint v8). diff --git a/tests/lib/rules/no-unused-services.js b/tests/lib/rules/no-unused-services.js index 51a077f1c6..5a8468f3c0 100644 --- a/tests/lib/rules/no-unused-services.js +++ b/tests/lib/rules/no-unused-services.js @@ -203,24 +203,22 @@ ruleTester.run('no-unused-services', rule, { `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; fooFunc() {${emberObjectUses1}} }`, `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), fooFunc() {${emberObjectUses1}} });`, `${SERVICE_IMPORT}${EO_IMPORTS} Component.extend({ ${SERVICE_NAME}: service(), foo: computed(function () { return helper(this); }) });`, + // Any `this` passed inside the class body counts, like any `this.foo` counts as a use. + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return function () { return helper(this); }; } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return class { bar() { return helper(this); } }; } }`, + `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo: helper(this) });`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; static foo = helper(this); }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; static foo() { return helper(this); } }`, + `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; static { helper(this); } }`, + `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo() { return [1].map(function () { return helper(this); }); } });`, ], invalid: [ - /* `this` is not passed anywhere, or the `this` that is passed is not the class instance */ + /* `this` is not passed anywhere */ { code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return helper(this.other); } }`, output: null, errors: [{ messageId: 'main' }], }, - { - code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return function () { return helper(this); }; } }`, - output: null, - errors: [{ messageId: 'main' }], - }, - { - code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { return class { bar() { return helper(this); } }; } }`, - output: null, - errors: [{ messageId: 'main' }], - }, { code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; foo() { class Inner { bar() { return helper(this); } } return Inner; } }`, output: null, @@ -241,31 +239,6 @@ ruleTester.run('no-unused-services', rule, { output: null, errors: [{ messageId: 'main' }], }, - { - code: `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo: helper(this) });`, - output: null, - errors: [{ messageId: 'main' }], - }, - { - code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; static foo = helper(this); }`, - output: null, - errors: [{ messageId: 'main' }], - }, - { - code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; static foo() { return helper(this); } }`, - output: null, - errors: [{ messageId: 'main' }], - }, - { - code: `${SERVICE_IMPORT} class MyClass { @service() ${SERVICE_NAME}; static { helper(this); } }`, - output: null, - errors: [{ messageId: 'main' }], - }, - { - code: `${SERVICE_IMPORT} Component.extend({ ${SERVICE_NAME}: service(), foo() { return [1].map(function () { return helper(this); }); } });`, - output: null, - errors: [{ messageId: 'main' }], - }, { code: `${SERVICE_IMPORT} class MyClass { @service('foo') ${SERVICE_NAME}; fooFunc() {${nonUses}} }`, output: null,