Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[eslint] Fix no-use-before-define for class ref in fields #16210

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 24 additions & 2 deletions eslint/babel-eslint-parser/src/analyze-scope.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,30 @@ class Referencer extends OriginalReferencer {
}

_visitClassProperty(node) {
this._visitTypeAnnotation(node.typeAnnotation);
this.visitProperty(node);
const { computed, key, typeAnnotation, value } = node;

if (computed) this.visit(key);
this._visitTypeAnnotation(typeAnnotation);

if (value) {
if (this.scopeManager.__nestClassFieldInitializerScope) {
this.scopeManager.__nestClassFieldInitializerScope(value);
} else {
// Given that ESLint 7 didn't have a "class field initializer" scope,
// we create a plain method scope. Semantics are the same.
this.scopeManager.__nestScope(
new Scope(
this.scopeManager,
"function",
this.scopeManager.__currentScope,
value,
true,
),
);
}
this.visit(value);
this.close(value);
}
}

_visitDeclareX(node) {
Expand Down
22 changes: 22 additions & 0 deletions eslint/babel-eslint-tests/test/integration/eslint/verify.js
Original file line number Diff line number Diff line change
Expand Up @@ -1749,6 +1749,17 @@ describe("verify", () => {
{ "no-unused-vars": 1 },
);
});

it("no-use-before-define allows referencing the class in a field", () => {
verifyAndAssertMessages(
`
class C {
d = C.name;
}
`,
{ "no-use-before-define": 1 },
);
});
});

describe("private field declarations", () => {
Expand All @@ -1774,6 +1785,17 @@ describe("verify", () => {
);
});

it("no-use-before-define allows referencing the class in a field", () => {
verifyAndAssertMessages(
`
class C {
#d = C.name;
}
`,
{ "no-use-before-define": 1 },
);
});

it("type annotations should work", () => {
verifyAndAssertMessages(
`class C {
Expand Down