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

feat: treat this in typeof this as a ThisExpression #4382

Merged
merged 19 commits into from Jun 27, 2022
Merged
Show file tree
Hide file tree
Changes from 10 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
3 changes: 2 additions & 1 deletion packages/ast-spec/src/unions/EntityName.ts
@@ -1,4 +1,5 @@
import type { Identifier } from '../expression/Identifier/spec';
import type { ThisExpression } from '../expression/ThisExpression/spec';
import type { TSQualifiedName } from '../type/TSQualifiedName/spec';

export type EntityName = Identifier | TSQualifiedName;
export type EntityName = Identifier | ThisExpression | TSQualifiedName;
10 changes: 10 additions & 0 deletions packages/eslint-plugin/tests/eslint-rules/no-undef.test.ts
Expand Up @@ -248,6 +248,16 @@ class Foo {}
`
export type AppState = typeof import('./src/store/reducers').default;
`,
`
let self: typeof this;
let foo: typeof this.foo;
const obj = {
foo: '',
bar() {
let self: typeof this;
},
};
`,
],
invalid: [
{
Expand Down
6 changes: 5 additions & 1 deletion packages/scope-manager/src/referencer/ClassVisitor.ts
Expand Up @@ -293,7 +293,7 @@ class ClassVisitor extends Visitor {
node.typeAnnotation.type === AST_NODE_TYPES.TSTypeReference &&
this.#emitDecoratorMetadata
) {
let identifier: TSESTree.Identifier;
let identifier: TSESTree.Identifier | TSESTree.ThisExpression;
if (
node.typeAnnotation.typeName.type === AST_NODE_TYPES.TSQualifiedName
) {
Expand All @@ -306,6 +306,10 @@ class ClassVisitor extends Visitor {
identifier = node.typeAnnotation.typeName;
}

if (identifier.type === AST_NODE_TYPES.ThisExpression) {
return;
}

if (withDecorators) {
this.#referencer.currentScope().referenceDualValueType(identifier);

Expand Down
21 changes: 14 additions & 7 deletions packages/scope-manager/src/referencer/TypeVisitor.ts
Expand Up @@ -256,15 +256,22 @@ class TypeVisitor extends Visitor {

// a type query `typeof foo` is a special case that references a _non-type_ variable,
protected TSTypeQuery(node: TSESTree.TSTypeQuery): void {
if (node.exprName.type === AST_NODE_TYPES.Identifier) {
this.#referencer.currentScope().referenceValue(node.exprName);
} else {
let expr = node.exprName.left;
while (expr.type !== AST_NODE_TYPES.Identifier) {
expr = expr.left;
let identifier: TSESTree.Identifier | TSESTree.ThisExpression;
if (node.exprName.type === AST_NODE_TYPES.TSQualifiedName) {
let iter = node.exprName;
while (iter.left.type === AST_NODE_TYPES.TSQualifiedName) {
iter = iter.left;
}
this.#referencer.currentScope().referenceValue(expr);
identifier = iter.left;
} else {
identifier = node.exprName;
}

if (identifier.type === AST_NODE_TYPES.ThisExpression) {
return;
}

this.#referencer.currentScope().referenceValue(identifier);
}

protected TSTypeAnnotation(node: TSESTree.TSTypeAnnotation): void {
Expand Down
@@ -0,0 +1,2 @@
let self: typeof this;
let foo: typeof this.foo;
9 changes: 9 additions & 0 deletions packages/typescript-estree/src/convert.ts
Expand Up @@ -20,6 +20,7 @@ import {
isComputedProperty,
isESTreeClassMember,
isOptional,
isThisInTypeQuery,
TSError,
unescapeStringLiteralText,
} from './node-utils';
Expand Down Expand Up @@ -799,6 +800,14 @@ export class Converter {
}

case SyntaxKind.Identifier: {
if (isThisInTypeQuery(node)) {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Changing the AST feels hacky and is gonna break some plugins. The no-undef rule uses globalScope.through to check undefined variables. Creating a variable called this for functions should prevent eslint from reporting this.

https://github.com/eslint/eslint/blob/main/lib/rules/no-undef.js#L59L75

Copy link
Member

@armano2 armano2 Jan 6, 2022

Choose a reason for hiding this comment

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

this looks like an issue in typescript, we should either get SyntaxKind.ThisType or SyntaxKind.ThisKeyword

playground 4.3.5
playground 4.5.4

class Test {
    fn () {
        const a: typeof this = this
        a.fn()
        const b: this = this
        b.fn()
    }
}

const b: this = this - is correctly reported as ThisType

older versions of typescript (<4.4) reported typeof this as error Cannot find name 'this'. (2304)


we should add test cases for parser and visitor

return this.createNode<TSESTree.ThisExpression>(
node as unknown as ts.ThisExpression,
bradzacher marked this conversation as resolved.
Show resolved Hide resolved
{
type: AST_NODE_TYPES.ThisExpression,
},
);
}
return this.createNode<TSESTree.Identifier>(node, {
type: AST_NODE_TYPES.Identifier,
name: node.text,
Expand Down
26 changes: 26 additions & 0 deletions packages/typescript-estree/src/node-utils.ts
Expand Up @@ -662,3 +662,29 @@ export function firstDefined<T, U>(
}
return undefined;
}

export function identifierIsThisKeyword(id: ts.Identifier): boolean {
return id.originalKeywordKind === SyntaxKind.ThisKeyword;
}

export function isThisIdentifier(
node: ts.Node | undefined,
): node is ts.Identifier {
return (
!!node &&
node.kind === SyntaxKind.Identifier &&
identifierIsThisKeyword(node as ts.Identifier)
);
}

export function isThisInTypeQuery(node: ts.Node): boolean {
Copy link
Member

Choose a reason for hiding this comment

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

ditto above - use a predicate return type

if (!isThisIdentifier(node)) {
return false;
}

while (ts.isQualifiedName(node.parent) && node.parent.left === node) {
node = node.parent;
}

return node.parent.kind === SyntaxKind.TypeQuery;
}
23 changes: 22 additions & 1 deletion packages/typescript-estree/tests/ast-alignment/utils.ts
@@ -1,6 +1,6 @@
// babel types are something we don't really care about
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/restrict-plus-operands */
import type { File, Program } from '@babel/types';
import type { File, Identifier, Program, TSTypeQuery } from '@babel/types';
import { AST_NODE_TYPES, TSESTree } from '../../src/ts-estree';
import { deeplyCopy, omitDeep } from '../../tools/test-utils';

Expand Down Expand Up @@ -295,6 +295,27 @@ export function preprocessBabylonAST(ast: File): any {
delete node.loc.start.index;
}
},
TSTypeQuery(node: TSTypeQuery) {
Copy link
Member

@armano2 armano2 May 28, 2022

Choose a reason for hiding this comment

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

can you add an comment with explanation why we need this and if there is babel ticket please link it here,
(this is necessary to ease maintenance of this file)

const { exprName } = node;
const processIdentifier = (identifier: Identifier) => {
if (identifier.name === 'this') {
(identifier.type as string) = 'ThisExpression';
delete (identifier as { name?: string }).name;
}
};
if (exprName.type === 'Identifier') {
processIdentifier(exprName);
} else if (exprName.type === 'TSQualifiedName') {
let qualifiedName = exprName;
while (true) {
if (qualifiedName.left.type === 'Identifier') {
processIdentifier(qualifiedName.left);
return;
}
qualifiedName = qualifiedName.left;
}
}
},
},
);
}
Expand Down
Expand Up @@ -2786,6 +2786,8 @@ exports[`Parse all fixtures with "errorOnTypeScriptSyntacticAndSemanticIssues" e

exports[`Parse all fixtures with "errorOnTypeScriptSyntacticAndSemanticIssues" enabled fixtures/typescript/types/typeof.src 1`] = `"TEST OUTPUT: No semantic or syntactic issues found"`;

exports[`Parse all fixtures with "errorOnTypeScriptSyntacticAndSemanticIssues" enabled fixtures/typescript/types/typeof-this.src 1`] = `"TEST OUTPUT: No semantic or syntactic issues found"`;

exports[`Parse all fixtures with "errorOnTypeScriptSyntacticAndSemanticIssues" enabled fixtures/typescript/types/typeof-with-type-parameters.src 1`] = `"TEST OUTPUT: No semantic or syntactic issues found"`;

exports[`Parse all fixtures with "errorOnTypeScriptSyntacticAndSemanticIssues" enabled fixtures/typescript/types/union-intersection.src 1`] = `"TEST OUTPUT: No semantic or syntactic issues found"`;
Expand Down