Skip to content

Specific diagnostic suggestions for unexpected keyword or identifier #43005

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
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
0c967f9
Specific diagnostic suggestions for unexpected keywords or identifier
Feb 28, 2021
107e10d
Don't reach into there, that's not allowed
Mar 4, 2021
12088e9
Improved error when there is already an initializer
Mar 23, 2021
73a9852
Specific module error message for invalid template literal strings
Mar 28, 2021
cc70a1b
Skip 'unexpected keyword or identifier' diagnostics for declare nodes
Mar 28, 2021
23e0acb
Improve error for function calls in type positions
Mar 28, 2021
5cf8606
Merge branch 'master'
Mar 28, 2021
05e8d0f
Switch class properties to old diagnostic
Apr 7, 2021
f547914
Merge branch 'master'
Apr 7, 2021
972da93
Corrected errors in class members and reused existing textToKeywordOb…
Apr 11, 2021
c554519
Merge branch 'master'
Apr 11, 2021
5a0804b
Corrected more baselines from the merge
Apr 11, 2021
182f75a
Update src/compiler/parser.ts
JoshuaKGoldberg Apr 13, 2021
dabe89a
Mostly addressed feedback
Apr 13, 2021
6d40a4c
Clarified function call type message
Apr 17, 2021
7e49aa6
Split up and clarified parsing vs error functions
Apr 17, 2021
a052314
Swap interface name complaints back, and skip new errors on unknown (…
Apr 17, 2021
8e9e46d
Merge branch 'master'
Apr 17, 2021
dd47c39
Used tokenToString, not a raw semicolon
Apr 17, 2021
ad6f591
Merge branch 'master' into jg-unexpected-keyword-identifier-diagnostics
May 28, 2021
cd4d28d
Merge branch 'main'
Jul 14, 2021
b878e74
Inline getExpressionText helper
Jul 14, 2021
b16d5eb
Remove remarks in src/compiler/parser.ts
JoshuaKGoldberg Jul 14, 2021
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
48 changes: 48 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -1360,6 +1360,50 @@
"category": "Error",
"code": 1432
},
"Unexpected keyword or identifier.": {
"category": "Error",
"code": 1433
},
"Unknown keyword or identifier. Did you mean '{0}'?": {
"category": "Error",
"code": 1434
},
"Decorators must precede all other keywords for property declarations.": {
"category": "Error",
"code": 1435
},
"Namespace must be given a name.": {
"category": "Error",
"code": 1436
},
"Interface must be given a name.": {
"category": "Error",
"code": 1437
},
"Type alias must be given a name.": {
"category": "Error",
"code": 1438
},
"Variable declaration not allowed at this location.": {
"category": "Error",
"code": 1439
},
"Function call not allowed at this location.": {
"category": "Error",
"code": 1440
},
"Missing '=' before default property value.": {
"category": "Error",
"code": 1441
},
"Template literal not allowed as a string at this position.": {
"category": "Error",
"code": 1442
},
"Template literal not allowed as a string at this position. Did you mean '{0}'?": {
"category": "Error",
"code": 1443
},

"The types of '{0}' are incompatible between these types.": {
"category": "Error",
Expand Down Expand Up @@ -3264,6 +3308,10 @@
"category": "Error",
"code": 2802
},
"Namespace name cannot be '{0}'.": {
"category": "Error",
"code": 2803
},

"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
Expand Down
138 changes: 135 additions & 3 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1518,6 +1518,138 @@ namespace ts {
return false;
}

const commonKeywords = [
"async",
"class",
"const",
"declare",
"export",
"function",
"interface",
"let",
"type",
"var",
];

function parseSemicolonAfter(expression: Expression | PropertyName, initializer?: Node) {
// Consume the semicolon if it was explicitly provided.
if (canParseSemicolon()) {
if (token() === SyntaxKind.SemicolonToken) {
nextToken();
}

return;
}

// The only way not having a semicolon after an expression when expected shouldn't create an error
// would be if we've there's an initializer, which would indicate the initializer already has an error
if (initializer) {
return;
}

// Tagged template literals are sometimes used in places where only simple strings are allowed, e.g.:
// module `M1` {
// ^^^^^^^^^^^ This block is parsed as a template literal as with module`M1`.
if (isTaggedTemplateExpression(expression)) {
parseErrorAt(skipTrivia(sourceText, expression.template.pos), expression.template.end, Diagnostics.Template_literal_not_allowed_as_a_string_at_this_position);
return;
}

// Otherwise, if this isn't a well-known keyword-like identifier, give the generic fallback message.
const expressionText = getExpressionText(expression);
if (!expressionText || !isIdentifierText(expressionText, languageVersion)) {
parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.SemicolonToken));
return;
}

const pos = skipTrivia(sourceText, expression.pos);

// Some known keywords are likely signs of syntax being used improperly.
switch (expressionText) {
case "const":
case "let":
case "var":
parseErrorAt(pos, expression.end, Diagnostics.Variable_declaration_not_allowed_at_this_location);
return;

case "interface":
parseErrorForExpectedName(scanner.getTokenText(), "{", Diagnostics.Interface_must_be_given_a_name, Diagnostics.Interface_name_cannot_be_0);
return;

case "is":
parseErrorAt(pos, scanner.getTextPos(), Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
return;

case "module":
case "namespace":
parseErrorForExpectedName(scanner.getTokenText(), "{", Diagnostics.Namespace_must_be_given_a_name, Diagnostics.Namespace_name_cannot_be_0);
return;

case "type":
parseErrorForExpectedName(scanner.getTokenText(), "=", Diagnostics.Type_alias_must_be_given_a_name, Diagnostics.Type_alias_name_cannot_be_0);
return;
}

// The user alternately might have misspelled or forgotten to add a space after a common keyword.
const suggestion = getSpellingSuggestion(expressionText, commonKeywords, n => n) || getSpaceSuggestion(expressionText);
if (suggestion) {
parseErrorAt(pos, expression.end, Diagnostics.Unknown_keyword_or_identifier_Did_you_mean_0, suggestion);
}

// We know this is a slightly more precise case than a missing expected semicolon.
parseErrorAt(pos, expression.end, Diagnostics.Unexpected_keyword_or_identifier);
}

function parseErrorForExpectedName(name: string, normalToken: string, blankDiagnostic: DiagnosticMessage, nameDiagnostic: DiagnosticMessage) {
if (name === normalToken) {
parseErrorAtCurrentToken(blankDiagnostic);
}
else {
parseErrorAtCurrentToken(nameDiagnostic, name);
}
}

function getSpaceSuggestion(expressionText: string) {
for (const keyword of commonKeywords) {
if (expressionText.length > keyword.length + 2 && startsWith(expressionText, keyword)) {
return `${keyword} ${expressionText.slice(keyword.length)}`;
}
}

return undefined;
}

function parseSemicolonAfterPropertyName(name: PropertyName, type: TypeNode | undefined, initializer: Expression | undefined) {
switch (scanner.getTokenText()) {
case "@":
parseErrorAtCurrentToken(Diagnostics.Decorators_must_precede_all_other_keywords_for_property_declarations);
return;

case "(":
parseErrorAtCurrentToken(Diagnostics.Function_call_not_allowed_at_this_location);
nextToken();
return;
}

if (type && !canParseSemicolon()) {
if (initializer) {
parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.SemicolonToken));
}
else {
parseErrorAtCurrentToken(Diagnostics.Missing_before_default_property_value);
}
return;
}

return parseSemicolonAfter(name, initializer);
}

function getExpressionText(expression: Expression | PropertyName) {
return expression && ts.isIdentifier(expression)
? expression.escapedText.toString()
: undefined;
}

function parseExpectedJSDoc(kind: JSDocSyntaxKind) {
if (token() === kind) {
nextTokenJSDoc();
Expand Down Expand Up @@ -5786,7 +5918,7 @@ namespace ts {
identifierCount++;
expression = finishNode(factory.createIdentifier(""), getNodePos());
}
parseSemicolon();
parseSemicolonAfter(expression);
return finishNode(factory.createThrowStatement(expression), pos);
}

Expand Down Expand Up @@ -5847,7 +5979,7 @@ namespace ts {
node = factory.createLabeledStatement(expression, parseStatement());
}
else {
parseSemicolon();
parseSemicolonAfter(expression);
node = factory.createExpressionStatement(expression);
if (hasParen) {
// do not parse the same jsdoc twice
Expand Down Expand Up @@ -6440,7 +6572,7 @@ namespace ts {
const exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(SyntaxKind.ExclamationToken) : undefined;
const type = parseTypeAnnotation();
const initializer = doOutsideOfContext(NodeFlags.YieldContext | NodeFlags.AwaitContext | NodeFlags.DisallowInContext, parseInitializer);
parseSemicolon();
parseSemicolonAfterPropertyName(name, type, initializer);
const node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer);
return withJSDoc(finishNode(node, pos), hasJSDoc);
}
Expand Down
6 changes: 3 additions & 3 deletions tests/baselines/reference/ClassDeclaration26.errors.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
tests/cases/compiler/ClassDeclaration26.ts(2,22): error TS1005: ';' expected.
tests/cases/compiler/ClassDeclaration26.ts(2,18): error TS1439: Variable declaration not allowed at this location.
tests/cases/compiler/ClassDeclaration26.ts(4,5): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
tests/cases/compiler/ClassDeclaration26.ts(4,20): error TS1005: ',' expected.
tests/cases/compiler/ClassDeclaration26.ts(4,23): error TS1005: '=>' expected.
Expand All @@ -8,8 +8,8 @@ tests/cases/compiler/ClassDeclaration26.ts(5,1): error TS1128: Declaration or st
==== tests/cases/compiler/ClassDeclaration26.ts (5 errors) ====
class C {
public const var export foo = 10;
~~~~~~
!!! error TS1005: ';' expected.
~~~
!!! error TS1439: Variable declaration not allowed at this location.

var constructor() { }
~~~
Expand Down
12 changes: 6 additions & 6 deletions tests/baselines/reference/anonymousModules.errors.txt
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
tests/cases/compiler/anonymousModules.ts(1,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
tests/cases/compiler/anonymousModules.ts(1,8): error TS1005: ';' expected.
tests/cases/compiler/anonymousModules.ts(1,8): error TS1436: Namespace must be given a name.
tests/cases/compiler/anonymousModules.ts(4,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
tests/cases/compiler/anonymousModules.ts(4,9): error TS1005: ';' expected.
tests/cases/compiler/anonymousModules.ts(4,9): error TS1436: Namespace must be given a name.
tests/cases/compiler/anonymousModules.ts(10,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected.
tests/cases/compiler/anonymousModules.ts(10,9): error TS1436: Namespace must be given a name.


==== tests/cases/compiler/anonymousModules.ts (6 errors) ====
module {
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
~
!!! error TS1005: ';' expected.
!!! error TS1436: Namespace must be given a name.
export var foo = 1;

module {
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
~
!!! error TS1005: ';' expected.
!!! error TS1436: Namespace must be given a name.
export var bar = 1;
}

Expand All @@ -28,7 +28,7 @@ tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected.
~~~~~~
!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
~
!!! error TS1005: ';' expected.
!!! error TS1436: Namespace must be given a name.
var x = bar;
}
}
16 changes: 11 additions & 5 deletions tests/baselines/reference/classUpdateTests.errors.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ tests/cases/compiler/classUpdateTests.ts(95,1): error TS1128: Declaration or sta
tests/cases/compiler/classUpdateTests.ts(99,3): error TS1128: Declaration or statement expected.
tests/cases/compiler/classUpdateTests.ts(101,1): error TS1128: Declaration or statement expected.
tests/cases/compiler/classUpdateTests.ts(105,3): error TS1128: Declaration or statement expected.
tests/cases/compiler/classUpdateTests.ts(105,14): error TS1005: ';' expected.
tests/cases/compiler/classUpdateTests.ts(105,10): error TS1433: Unexpected keyword or identifier.
tests/cases/compiler/classUpdateTests.ts(105,14): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
tests/cases/compiler/classUpdateTests.ts(107,1): error TS1128: Declaration or statement expected.
tests/cases/compiler/classUpdateTests.ts(111,3): error TS1128: Declaration or statement expected.
tests/cases/compiler/classUpdateTests.ts(111,15): error TS1005: ';' expected.
tests/cases/compiler/classUpdateTests.ts(111,11): error TS1433: Unexpected keyword or identifier.
tests/cases/compiler/classUpdateTests.ts(111,15): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
tests/cases/compiler/classUpdateTests.ts(113,1): error TS1128: Declaration or statement expected.


==== tests/cases/compiler/classUpdateTests.ts (16 errors) ====
==== tests/cases/compiler/classUpdateTests.ts (18 errors) ====
//
// test codegen for instance properties
//
Expand Down Expand Up @@ -154,8 +156,10 @@ tests/cases/compiler/classUpdateTests.ts(113,1): error TS1128: Declaration or st
public this.p1 = 0; // ERROR
~~~~~~
!!! error TS1128: Declaration or statement expected.
~~~~
!!! error TS1433: Unexpected keyword or identifier.
~
!!! error TS1005: ';' expected.
!!! error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
}
}
~
Expand All @@ -166,8 +170,10 @@ tests/cases/compiler/classUpdateTests.ts(113,1): error TS1128: Declaration or st
private this.p1 = 0; // ERROR
~~~~~~~
!!! error TS1128: Declaration or statement expected.
~~~~
!!! error TS1433: Unexpected keyword or identifier.
~
!!! error TS1005: ';' expected.
!!! error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
}
}
~
Expand Down
Loading