Introduce parser error codes (#13033)

This commit is contained in:
Sosuke Suzuki
2021-04-04 02:31:07 +09:00
committed by Nicolò Ribaudo
parent d0fcbfccdd
commit 0ee98139a6
16 changed files with 551 additions and 442 deletions

View File

@@ -25,7 +25,7 @@ import {
SCOPE_OTHER,
} from "../../util/scopeflags";
import type { ExpressionErrors } from "../../parser/util";
import { Errors } from "../../parser/error";
import { Errors, makeErrorTemplates, ErrorCodes } from "../../parser/error";
const reservedTypes = new Set([
"_",
@@ -48,91 +48,95 @@ const reservedTypes = new Set([
/* eslint sort-keys: "error" */
// The Errors key follows https://github.com/facebook/flow/blob/master/src/parser/parse_error.ml unless it does not exist
const FlowErrors = Object.freeze({
AmbiguousConditionalArrow:
"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
AmbiguousDeclareModuleKind:
"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module",
AssignReservedType: "Cannot overwrite reserved type %0",
DeclareClassElement:
"The `declare` modifier can only appear on class fields.",
DeclareClassFieldInitializer:
"Initializers are not allowed in fields with the `declare` modifier.",
DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
EnumBooleanMemberNotInitialized:
"Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
EnumDuplicateMemberName:
"Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
EnumInconsistentMemberValues:
"Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
EnumInvalidExplicitType:
"Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
EnumInvalidExplicitTypeUnknownSupplied:
"Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
EnumInvalidMemberInitializerPrimaryType:
"Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
EnumInvalidMemberInitializerSymbolType:
"Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
EnumInvalidMemberInitializerUnknownType:
"The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
EnumInvalidMemberName:
"Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
EnumNumberMemberNotInitialized:
"Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
EnumStringMemberInconsistentlyInitailized:
"String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
ImportTypeShorthandOnlyInPureImport:
"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements",
InexactInsideExact:
"Explicit inexact syntax cannot appear inside an explicit exact object type",
InexactInsideNonObject:
"Explicit inexact syntax cannot appear in class or interface definitions",
InexactVariance: "Explicit inexact syntax cannot have variance",
InvalidNonTypeImportInDeclareModule:
"Imports within a `declare module` body must always be `import type` or `import typeof`",
MissingTypeParamDefault:
"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
NestedDeclareModule:
"`declare module` cannot be used inside another `declare module`",
NestedFlowComment: "Cannot have a flow comment inside another flow comment",
OptionalBindingPattern:
"A binding pattern parameter cannot be optional in an implementation signature.",
SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
SpreadVariance: "Spread properties cannot have variance",
ThisParamAnnotationRequired:
"A type annotation is required for the `this` parameter.",
ThisParamBannedInConstructor:
"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
ThisParamMustBeFirst:
"The `this` parameter must be the first function parameter.",
ThisParamNoDefault: "The `this` parameter may not have a default value.",
TypeBeforeInitializer:
"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
TypeCastInPattern:
"The type cast expression is expected to be wrapped with parenthesis",
UnexpectedExplicitInexactInObject:
"Explicit inexact syntax must appear at the end of an inexact object",
UnexpectedReservedType: "Unexpected reserved type %0",
UnexpectedReservedUnderscore:
"`_` is only allowed as a type argument to call or new",
UnexpectedSpaceBetweenModuloChecks:
"Spaces between `%` and `checks` are not allowed here.",
UnexpectedSpreadType:
"Spread operator cannot appear in class or interface definitions",
UnexpectedSubtractionOperand:
'Unexpected token, expected "number" or "bigint"',
UnexpectedTokenAfterTypeParameter:
"Expected an arrow function after this type parameter declaration",
UnexpectedTypeParameterBeforeAsyncArrowFunction:
"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
UnsupportedDeclareExportKind:
"`declare export %0` is not supported. Use `%1` instead",
UnsupportedStatementInDeclareModule:
"Only declares and type imports are allowed inside declare module",
UnterminatedFlowComment: "Unterminated flow-comment",
});
const FlowErrors = makeErrorTemplates(
{
AmbiguousConditionalArrow:
"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
AmbiguousDeclareModuleKind:
"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module",
AssignReservedType: "Cannot overwrite reserved type %0",
DeclareClassElement:
"The `declare` modifier can only appear on class fields.",
DeclareClassFieldInitializer:
"Initializers are not allowed in fields with the `declare` modifier.",
DuplicateDeclareModuleExports:
"Duplicate `declare module.exports` statement",
EnumBooleanMemberNotInitialized:
"Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
EnumDuplicateMemberName:
"Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
EnumInconsistentMemberValues:
"Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
EnumInvalidExplicitType:
"Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
EnumInvalidExplicitTypeUnknownSupplied:
"Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
EnumInvalidMemberInitializerPrimaryType:
"Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
EnumInvalidMemberInitializerSymbolType:
"Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
EnumInvalidMemberInitializerUnknownType:
"The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
EnumInvalidMemberName:
"Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
EnumNumberMemberNotInitialized:
"Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
EnumStringMemberInconsistentlyInitailized:
"String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
ImportTypeShorthandOnlyInPureImport:
"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements",
InexactInsideExact:
"Explicit inexact syntax cannot appear inside an explicit exact object type",
InexactInsideNonObject:
"Explicit inexact syntax cannot appear in class or interface definitions",
InexactVariance: "Explicit inexact syntax cannot have variance",
InvalidNonTypeImportInDeclareModule:
"Imports within a `declare module` body must always be `import type` or `import typeof`",
MissingTypeParamDefault:
"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
NestedDeclareModule:
"`declare module` cannot be used inside another `declare module`",
NestedFlowComment: "Cannot have a flow comment inside another flow comment",
OptionalBindingPattern:
"A binding pattern parameter cannot be optional in an implementation signature.",
SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
SpreadVariance: "Spread properties cannot have variance",
ThisParamAnnotationRequired:
"A type annotation is required for the `this` parameter.",
ThisParamBannedInConstructor:
"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
ThisParamMustBeFirst:
"The `this` parameter must be the first function parameter.",
ThisParamNoDefault: "The `this` parameter may not have a default value.",
TypeBeforeInitializer:
"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
TypeCastInPattern:
"The type cast expression is expected to be wrapped with parenthesis",
UnexpectedExplicitInexactInObject:
"Explicit inexact syntax must appear at the end of an inexact object",
UnexpectedReservedType: "Unexpected reserved type %0",
UnexpectedReservedUnderscore:
"`_` is only allowed as a type argument to call or new",
UnexpectedSpaceBetweenModuloChecks:
"Spaces between `%` and `checks` are not allowed here.",
UnexpectedSpreadType:
"Spread operator cannot appear in class or interface definitions",
UnexpectedSubtractionOperand:
'Unexpected token, expected "number" or "bigint"',
UnexpectedTokenAfterTypeParameter:
"Expected an arrow function after this type parameter declaration",
UnexpectedTypeParameterBeforeAsyncArrowFunction:
"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
UnsupportedDeclareExportKind:
"`declare export %0` is not supported. Use `%1` instead",
UnsupportedStatementInDeclareModule:
"Only declares and type imports are allowed inside declare module",
UnterminatedFlowComment: "Unterminated flow-comment",
},
/* code */ ErrorCodes.SyntaxError,
);
/* eslint-disable sort-keys */
function isEsModuleType(bodyElement: N.Node): boolean {

View File

@@ -14,25 +14,28 @@ import * as N from "../../types";
import { isIdentifierChar, isIdentifierStart } from "../../util/identifier";
import type { Position } from "../../util/location";
import { isNewLine } from "../../util/whitespace";
import { Errors } from "../../parser/error";
import { Errors, makeErrorTemplates, ErrorCodes } from "../../parser/error";
const HEX_NUMBER = /^[\da-fA-F]+$/;
const DECIMAL_NUMBER = /^\d+$/;
/* eslint sort-keys: "error" */
const JsxErrors = Object.freeze({
AttributeIsEmpty:
"JSX attributes must only be assigned a non-empty expression",
MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
UnexpectedSequenceExpression:
"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
UnsupportedJsxValue:
"JSX value should be either an expression or a quoted JSX text",
UnterminatedJsxContent: "Unterminated JSX contents",
UnwrappedAdjacentJSXElements:
"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?",
});
const JsxErrors = makeErrorTemplates(
{
AttributeIsEmpty:
"JSX attributes must only be assigned a non-empty expression",
MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
UnexpectedSequenceExpression:
"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
UnsupportedJsxValue:
"JSX value should be either an expression or a quoted JSX text",
UnterminatedJsxContent: "Unterminated JSX contents",
UnwrappedAdjacentJSXElements:
"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?",
},
/* code */ ErrorCodes.SyntaxError,
);
/* eslint-disable sort-keys */
// Be aware that this file is always executed and not only when the plugin is enabled.
@@ -133,10 +136,11 @@ export default (superClass: Class<Parser>): Class<Parser> =>
const htmlEntity =
ch === charCodes.rightCurlyBrace ? "&rbrace;" : "&gt;";
const char = this.input[this.state.pos];
this.raise(
this.state.pos,
`Unexpected token \`${char}\`. Did you mean \`${htmlEntity}\` or \`{'${char}'}\`?`,
);
this.raise(this.state.pos, {
code: ErrorCodes.SyntaxError,
reasonCode: "UnexpectedToken",
template: `Unexpected token \`${char}\`. Did you mean \`${htmlEntity}\` or \`{'${char}'}\`?`,
});
}
/* falls through */

View File

@@ -5,6 +5,7 @@ import * as charCodes from "charcodes";
import { types as tt, TokenType } from "../tokenizer/types";
import type Parser from "../parser";
import * as N from "../types";
import { makeErrorTemplates, ErrorCodes } from "../parser/error";
tt.placeholder = new TokenType("%%", { startsExpr: true });
@@ -47,6 +48,13 @@ type NodeOf<T: PlaceholderTypes> = $Switch<
// the substituted nodes.
type MaybePlaceholder<T: PlaceholderTypes> = NodeOf<T>; // | Placeholder<T>
const PlaceHolderErrors = makeErrorTemplates(
{
ClassNameIsRequired: "A class name is required",
},
/* code */ ErrorCodes.SyntaxError,
);
export default (superClass: Class<Parser>): Class<Parser> =>
class extends superClass {
parsePlaceholder<T: PlaceholderTypes>(
@@ -240,7 +248,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
node.body = this.finishPlaceholder(placeholder, "ClassBody");
return this.finishNode(node, type);
} else {
this.unexpected(null, "A class name is required");
this.unexpected(null, PlaceHolderErrors.ClassNameIsRequired);
}
} else {
this.parseClassId(node, isStatement, optionalId);

View File

@@ -29,7 +29,12 @@ import TypeScriptScopeHandler from "./scope";
import * as charCodes from "charcodes";
import type { ExpressionErrors } from "../../parser/util";
import { PARAM } from "../../util/production-parameter";
import { Errors } from "../../parser/error";
import {
Errors,
makeErrorTemplates,
type ErrorTemplate,
ErrorCodes,
} from "../../parser/error";
type TsModifier =
| "readonly"
@@ -60,67 +65,75 @@ type ParsingContext =
| "TypeParametersOrArguments";
/* eslint sort-keys: "error" */
const TSErrors = Object.freeze({
AbstractMethodHasImplementation:
"Method '%0' cannot have an implementation because it is marked abstract.",
ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
ConstructorHasTypeParameters:
"Type parameters cannot appear on a constructor declaration.",
const TSErrors = makeErrorTemplates(
{
AbstractMethodHasImplementation:
"Method '%0' cannot have an implementation because it is marked abstract.",
ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
ConstructorHasTypeParameters:
"Type parameters cannot appear on a constructor declaration.",
DeclareAccessor: "'declare' is not allowed in %0ters.",
DeclareClassFieldHasInitializer:
"Initializers are not allowed in ambient contexts.",
DeclareFunctionHasImplementation:
"An implementation cannot be declared in ambient contexts.",
DuplicateAccessibilityModifier: "Accessibility modifier already seen.",
DuplicateModifier: "Duplicate modifier: '%0'",
EmptyHeritageClauseType: "'%0' list cannot be empty.",
EmptyTypeArguments: "Type argument list cannot be empty.",
EmptyTypeParameters: "Type parameter list cannot be empty.",
ExpectedAmbientAfterExportDeclare:
"'export declare' must be followed by an ambient declaration.",
ImportAliasHasImportType: "An import alias can not use 'import type'",
IndexSignatureHasAbstract:
"Index signatures cannot have the 'abstract' modifier",
IndexSignatureHasAccessibility:
"Index signatures cannot have an accessibility modifier ('%0')",
IndexSignatureHasDeclare:
"Index signatures cannot have the 'declare' modifier",
IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
InvalidModifierOnTypeMember: "'%0' modifier cannot appear on a type member.",
InvalidTupleMemberLabel:
"Tuple members must be labeled with a simple identifier.",
MixedLabeledAndUnlabeledElements:
"Tuple members must all have names or all not have names.",
NonAbstractClassHasAbstractMethod:
"Abstract methods can only appear within an abstract class.",
NonClassMethodPropertyHasAbstractModifer:
"'abstract' modifier can only appear on a class, method, or property declaration.",
OptionalTypeBeforeRequired:
"A required element cannot follow an optional element.",
PatternIsOptional:
"A binding pattern parameter cannot be optional in an implementation signature.",
PrivateElementHasAbstract:
"Private elements cannot have the 'abstract' modifier.",
PrivateElementHasAccessibility:
"Private elements cannot have an accessibility modifier ('%0')",
ReadonlyForMethodSignature:
"'readonly' modifier can only appear on a property declaration or index signature.",
TypeAnnotationAfterAssign:
"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
UnexpectedParameterModifier:
"A parameter property is only allowed in a constructor implementation.",
UnexpectedReadonly:
"'readonly' type modifier is only permitted on array and tuple literal types.",
UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
UnsupportedImportTypeArgument:
"Argument in a type import must be a string literal",
UnsupportedParameterPropertyKind:
"A parameter property may not be declared using a binding pattern.",
UnsupportedSignatureParameterKind:
"Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0",
});
DeclareClassFieldHasInitializer:
"Initializers are not allowed in ambient contexts.",
DeclareFunctionHasImplementation:
"An implementation cannot be declared in ambient contexts.",
DuplicateAccessibilityModifier: "Accessibility modifier already seen.",
DuplicateModifier: "Duplicate modifier: '%0'",
EmptyHeritageClauseType: "'%0' list cannot be empty.",
EmptyTypeArguments: "Type argument list cannot be empty.",
EmptyTypeParameters: "Type parameter list cannot be empty.",
ExpectedAmbientAfterExportDeclare:
"'export declare' must be followed by an ambient declaration.",
ImportAliasHasImportType: "An import alias can not use 'import type'",
IndexSignatureHasAbstract:
"Index signatures cannot have the 'abstract' modifier",
IndexSignatureHasAccessibility:
"Index signatures cannot have an accessibility modifier ('%0')",
IndexSignatureHasDeclare:
"Index signatures cannot have the 'declare' modifier",
IndexSignatureHasStatic:
"Index signatures cannot have the 'static' modifier",
InvalidModifierOnTypeMember:
"'%0' modifier cannot appear on a type member.",
InvalidTupleMemberLabel:
"Tuple members must be labeled with a simple identifier.",
MixedLabeledAndUnlabeledElements:
"Tuple members must all have names or all not have names.",
NonAbstractClassHasAbstractMethod:
"Abstract methods can only appear within an abstract class.",
NonClassMethodPropertyHasAbstractModifer:
"'abstract' modifier can only appear on a class, method, or property declaration.",
OptionalTypeBeforeRequired:
"A required element cannot follow an optional element.",
PatternIsOptional:
"A binding pattern parameter cannot be optional in an implementation signature.",
PrivateElementHasAbstract:
"Private elements cannot have the 'abstract' modifier.",
PrivateElementHasAccessibility:
"Private elements cannot have an accessibility modifier ('%0')",
ReadonlyForMethodSignature:
"'readonly' modifier can only appear on a property declaration or index signature.",
TypeAnnotationAfterAssign:
"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
TypeImportCannotSpecifyDefaultAndNamed:
"A type-only import can specify a default import or named bindings, but not both.",
UnexpectedParameterModifier:
"A parameter property is only allowed in a constructor implementation.",
UnexpectedReadonly:
"'readonly' type modifier is only permitted on array and tuple literal types.",
UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
UnexpectedTypeCastInParameter:
"Unexpected type cast in parameter position.",
UnsupportedImportTypeArgument:
"Argument in a type import must be a string literal",
UnsupportedParameterPropertyKind:
"A parameter property may not be declared using a binding pattern.",
UnsupportedSignatureParameterKind:
"Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0",
},
/* code */ ErrorCodes.SyntaxError,
);
/* eslint-disable sort-keys */
// Doesn't handle "void" or "null" because those are keywords, not identifiers.
@@ -217,7 +230,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
},
allowedModifiers: TsModifier[],
disallowedModifiers?: TsModifier[],
errorTemplate?: string,
errorTemplate?: ErrorTemplate,
): void {
for (;;) {
const startPos = this.state.start;
@@ -2098,7 +2111,7 @@ export default (superClass: Class<Parser>): Class<Parser> =>
) {
this.raise(
importNode.start,
"A type-only import can specify a default import or named bindings, but not both.",
TSErrors.TypeImportCannotSpecifyDefaultAndNamed,
);
}