Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/rules/no-unused-services.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)` 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.

## Examples
Expand Down
38 changes: 36 additions & 2 deletions lib/rules/no-unused-services.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ module.exports = {
let importedInjectName;
let importedObserverName;
let importedObservesName;
let importedSetName;
let importedSetPropertiesName;
const macros = getMacros();
const importedMacros = {};

Expand All @@ -60,8 +62,9 @@ module.exports = {
*/
function reportInstances() {
const currentClass = classStack.pop();
const { services, uses } = currentClass;
if (Object.keys(services).length === 0) {
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;
}

Expand Down Expand Up @@ -92,6 +95,30 @@ module.exports = {
}
}

/**
* 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) {

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!

const currentClass = classStack.peek();
if (!currentClass) {
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).

importedGetName,
importedGetPropertiesName,
importedSetName,
importedSetPropertiesName,
].filter(Boolean);
if (callee.type === 'Identifier' && emberObjectFunctions.includes(callee.name)) {
return;
}
currentClass.passesThis = true;
}

// Handle either ClassProperty (ESLint v7) or PropertyDefinition (ESLint v8).
function visitClassPropertyOrPropertyDefinition(node) {
// Handles:
Expand Down Expand Up @@ -127,6 +154,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) {
Expand Down Expand Up @@ -370,6 +401,9 @@ module.exports = {
currentClass.uses.add(name);
}
},
// fn(this), new Foo(this)
'CallExpression > ThisExpression.arguments, NewExpression > ThisExpression.arguments':
checkThisPassed,
VariableDeclarator(node) {
const currentClass = classStack.peek();
if (
Expand Down
82 changes: 49 additions & 33 deletions tests/lib/rules/no-unused-services.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,57 @@ 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() { 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}} }`,
`${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 */
{
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() { 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} 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,
errors: [{ messageId: 'main' }],
},
{
code: `${SERVICE_IMPORT} class MyClass { @service('foo') ${SERVICE_NAME}; fooFunc() {${nonUses}} }`,
output: null,
Expand Down Expand Up @@ -303,39 +352,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}} }`,
Expand Down
Loading