Skip to content

fix: Disallow type recursion during type declaration #2331

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

Merged
merged 10 commits into from
Jun 23, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
29 changes: 29 additions & 0 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3478,6 +3478,28 @@ export class Parser extends DiagnosticEmitter {
return null;
}

private checkRecurseDefinitionForType(identifierName: string, type: TypeNode): bool {
switch (type.kind) {
case NodeKind.NAMEDTYPE:
return (<NamedTypeNode>type).name.identifier.text == identifierName;

case NodeKind.FUNCTIONTYPE: {
let fnType = <FunctionTypeNode>type;
if (this.checkRecurseDefinitionForType(identifierName, fnType.returnType)) {
return true;
}
let params = fnType.parameters;
for (let i = 0, k = params.length; i < k; i++) {
if (this.checkRecurseDefinitionForType(identifierName, params[i].type)) {
return true;
}
}
break;
}
}
return false;
}

parseTypeDeclaration(
tn: Tokenizer,
flags: CommonFlags,
Expand All @@ -3499,6 +3521,13 @@ export class Parser extends DiagnosticEmitter {
tn.skip(Token.BAR);
let type = this.parseType(tn);
if (!type) return null;
if (this.checkRecurseDefinitionForType(name.text, type)) {
this.error(
DiagnosticCode.Not_implemented_0,
tn.range(), "recursion in type aliases"
);
return null;
}
let ret = Node.createTypeDeclaration(
name,
decorators,
Expand Down
6 changes: 6 additions & 0 deletions tests/parser/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,9 @@ export type uint64_t = u64;
export type T1 = | int32_t;
export type T2 =
| int32_t;

// disallow type recursion
export type T3 = T3 | null;
export type T4 = (x: T4) => i32;
export type T5 = () => T5;
export type T6<T> = () => T6<T>;
4 changes: 4 additions & 0 deletions tests/parser/type.ts.fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@ type int32_t = i32;
export type uint64_t = u64;
export type T1 = int32_t;
export type T2 = int32_t;
// ERROR 100: "Not implemented: recursion in type aliases" in type.ts(11,23+4)
// ERROR 100: "Not implemented: recursion in type aliases" in type.ts(12,29+3)
// ERROR 100: "Not implemented: recursion in type aliases" in type.ts(13,24+2)
// ERROR 100: "Not implemented: recursion in type aliases" in type.ts(14,31+1)