Repository navigation
Skip classes that pass this to a call in no-unused-services - #2887
NullVoxPopuli merged 5 commits into
Conversation
|
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 as in -- I'd think we can merge this PR IFF it doesn't follow function calling, but just disables when it detects a |
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
018285b to
56b1216
Compare
this in no-unused-servicesthis to a call in no-unused-services
|
Makes sense, agreed. Reworked in 56b1216: all the call following is gone. Now if a class passes its |
| function isThisPassedToCall(node) { | ||
| let child = node; | ||
| let parent = node.parent; | ||
| while ( |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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).
| case 'ArrayExpression': { | ||
| return node.elements.some(containsPassedThis); | ||
| } | ||
| case 'ObjectExpression': { |
There was a problem hiding this comment.
we don't need to do this, because this is its own node -- a ThisExpression -- so we can use that in the visitors
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Good call on both, done in 9913b0a.
- The
thisStackis gone. The class for athisnow comes from the scope manager: start atgetScope(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 afunctioninsideFoo.extend({...})gives that classic class. ESLint's ScopeManager doesn't recordthisas 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 aCallExpressionin ESTree. - I dropped the object / array /
const self = thiscases 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.
There was a problem hiding this comment.
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.
| */ | ||
| function getThisClass(node) { | ||
| let scope = sourceCode.getScope(node); | ||
| while (scope.block.type === 'ArrowFunctionExpression' && !isClassMemberValue(scope.block)) { |
There was a problem hiding this comment.
why we doin' while loops again?
There was a problem hiding this comment.
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:
- Look at just one scope. Then
thisinside 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). - Go back to a small stack kept by the function/method enter + exit visitors, so the owner of
thisis known with no lookup.
Happy to switch to either. Which do you prefer?
There was a problem hiding this comment.
why tho? the Visitors will see the ThisExpression here?
There was a problem hiding this comment.
this is the arrow's scope
arrows have no scope
There was a problem hiding this comment.
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 = [ |
There was a problem hiding this comment.
why are we checking these specifically?
There was a problem hiding this comment.
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).
Fixes #1258
Problem
no-unused-servicesonly sees uses likethis.someServiceinside the class. When the class handsthisto some other code, that code may use the service, but the rule can't see it and reports the injection as unused:Change
As suggested in review, the rule does not try to follow calls. If a class passes its
thisto any function ornewcall, the rule reports nothing for that class.fn(this),obj.method(a, this),new Foo(this),fn?.(this). Arrow functions keep the classthis, soitems.map(() => fn(this))andfoo = () => fn(this)count too. Works for native classes and classicFoo.extend({...})(incl.computed(function () { fn(this) })).CallExpression > ThisExpression.arguments/NewExpression > ThisExpression.argumentsvisitor, and the scope manager to find which class thethisbelongs to (no AST parent walking).thisin a nested regularfunction, a nested class, a static method/field or astatic {}block (that is a differentthis), andget/set/getProperties/setPropertiesimported from@ember/object(the rule already readsget/getPropertieskeys).Tests
new,fn?.(this), arrow callback, arrow class field, class field, constructor, classic class method, classiccomputedcallback, plus the two existing "un-importedget(this, ...)" cases, which moved from invalid to valid since thatgetis now just an unknown function that getsthis.helper(this.other), static field, static method,static {}block,thispassed 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, andset(this, ...)from@ember/object.masterand pass with this change.pnpm test: 269 files, 9965 tests pass (1 todo).pnpm lint(eslint, markdownlint, eslint-docs, prettier) is clean.