Skip to content

Commit

Permalink
fix(parser): Refactoring SyntaxError messages
Browse files Browse the repository at this point in the history
  • Loading branch information
KFlash committed Jun 27, 2019
1 parent 42f1afa commit 66098ea
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 49 deletions.
46 changes: 14 additions & 32 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ export const enum Errors {
InvalidStringLT,
InvalidEscapeIdentifier,
ExpectedToken,
InvalidLHS,
InvalidLHSInAsyncArrow,
InvalidLHSValidRHS,
CantAssignTo,
CantAssignToAsyncArrow,
CantAssignToValidRHS,
SuperNoConstructor,
InvalidSuperProperty,
UnexpectedToken,
Expand All @@ -43,7 +43,7 @@ export const enum Errors {
DeclNoName,
StrictFunctionName,
RestMissingArg,
InvalidLHSInit,
CantAssignToInit,
InvalidGeneratorGetter,
InvalidComputedPropName,
InvalidGetSetGenerator,
Expand Down Expand Up @@ -75,20 +75,16 @@ export const enum Errors {
IllegalBreak,
InvalidLetBracket,
InvalidDestructuringTarget,
InvalidRestObjBinding,
RestDefaultInitializer,
NotDestructibeRestArg,
InvalidRestNotLast,
InvalidRestArg,
InvalidRestDefault,
InvalidArrowDefaultYield,
InvalidExprInGroupAssign,
StrictFunction,
SloppyFunction,
WebCompatFunction,
ClassForbiddenAsStatement,
InvalidAwaitIdent,
InvalidLHSInOfForLoop,
CantAssignToInOfForLoop,
InvalidAssignmentInOfForLoop,
InvalidForAwait,
InvalidTemplateContinuation,
Expand All @@ -101,7 +97,6 @@ export const enum Errors {
NewlineAfterThrow,
StrictWith,
IllegalReturn,
InvalidForLHSBinding,
InvalidNewTarget,
InvalidEscapedKeyword,
MissingPrivateName,
Expand All @@ -114,13 +109,10 @@ export const enum Errors {
InvalidLetClassName,
KeywordNotId,
InvalidImportExportSloppy,
InvalidExportAtTopLevel,
InvalidNestedExport,
UnicodeOverflow,
InvalidExportImportSource,
InvalidKeywordAsAlias,
InvalidDefaultImport,
NoIdentOrDynamicName,
TrailingDecorators,
GeneratorConstructor,
AwaitOrYieldIdentInModule,
Expand All @@ -136,7 +128,7 @@ export const enum Errors {
InvalidStatementStart,
StrictDelete,
InvalidPatternTail,
ForLoopInvalidLHS,
ForLoopCantAssignTo,
AsyncFunctionInSingleStatementContext,
InvalidTernaryYield,
InvalidArrowPostfix,
Expand Down Expand Up @@ -189,14 +181,14 @@ export const errorMessages: {
[Errors.UnterminatedComment]: 'Multiline comment was not closed properly',
[Errors.InvalidDynamicUnicode]: 'The identifier contained dynamic unicode escape that was not closed',
[Errors.IllegalCaracter]: "Illegal character '%0'",
[Errors.MissingHexDigits]: 'Missing hex digits',
[Errors.MissingHexDigits]: 'Missing hexadecimal digits',
[Errors.InvalidImplicitOctals]: 'Invalid implicit octal',
[Errors.InvalidStringLT]: 'Invalid line break in string literal',
[Errors.InvalidEscapeIdentifier]: 'Only unicode escapes are legal in identifier names',
[Errors.ExpectedToken]: "Expected '%0'",
[Errors.InvalidLHS]: 'Invalid left-hand side in assignment',
[Errors.InvalidLHSInAsyncArrow]: 'Invalid left-hand side in async arrow',
[Errors.InvalidLHSValidRHS]: 'Only the right-hand side is destructible. The left-hand side is invalid',
[Errors.CantAssignTo]: 'Invalid left-hand side in assignment',
[Errors.CantAssignToAsyncArrow]: 'Invalid left-hand side in async arrow',
[Errors.CantAssignToValidRHS]: 'Invalid left-hand side assignment to a destructible right-hand side',
[Errors.SuperNoConstructor]:
'Calls to super must be in the "constructor" method of a class expression or class declaration that has a superclass',
[Errors.InvalidSuperProperty]: 'Member access on super must be in a method',
Expand All @@ -214,7 +206,7 @@ export const errorMessages: {
[Errors.DeclNoName]: '%0 declaration must have a name in this context',
[Errors.StrictFunctionName]: 'Function name may not be eval or arguments in strict mode',
[Errors.RestMissingArg]: 'The rest operator is missing an argument',
[Errors.InvalidLHSInit]: 'Cannot assign to lhs, not destructible with this initializer',
[Errors.CantAssignToInit]: 'Cannot assign to lhs, not destructible with this initializer',
[Errors.InvalidGeneratorGetter]: 'A getter cannot be a generator',
[Errors.InvalidComputedPropName]: 'A computed property name must be followed by a colon or paren',
[Errors.InvalidObjLitKey]: 'Object literal keys that are strings or numbers must be a method or have a colon',
Expand All @@ -237,7 +229,7 @@ export const errorMessages: {
[Errors.DeclarationMissingInitializer]: 'Missing initializer in %0 declaration',
[Errors.ForInOfLoopInitializer]: "'for-%0' loop head declarations can not have an initializer",
[Errors.ForInOfLoopMultiBindings]: 'Invalid left-hand side in for-%0 loop: Must have a single binding',
[Errors.ForLoopInvalidLHS]: 'Invalid left-hand side in for-loop',
[Errors.ForLoopCantAssignTo]: 'Invalid left-hand side in for-loop',
[Errors.InvalidShorthandPropInit]: 'Invalid shorthand property initializer',
[Errors.DuplicateProto]: 'Property name __proto__ appears more than once in object literal',
[Errors.InvalidLetBoundName]: 'Let is disallowed as a lexically bound name',
Expand All @@ -248,23 +240,17 @@ export const errorMessages: {
[Errors.IllegalBreak]: 'Illegal break statement',
[Errors.InvalidLetBracket]: 'Cannot have `let[...]` as a var name in strict mode',
[Errors.InvalidDestructuringTarget]: 'Invalid destructuring assignment target',
[Errors.InvalidRestObjBinding]:
'The rest argument of an object binding pattern must always be a simple ident and not an array pattern',
[Errors.RestDefaultInitializer]: 'Rest parameter may not have a default initializer',
[Errors.NotDestructibeRestArg]:
'The rest argument was not destructible as it must be last and can not have a trailing comma',
[Errors.InvalidRestNotLast]: 'The rest argument must the be last parameter',
[Errors.InvalidRestArg]: 'Invalid rest argument',
[Errors.InvalidArrowDefaultYield]: 'The arguments of an arrow cannot contain a yield expression in their defaults',
[Errors.InvalidExprInGroupAssign]: 'Cannot assign to list of expressions in a group',
[Errors.StrictFunction]: 'In strict mode code, functions can only be declared at top level or inside a block',
[Errors.SloppyFunction]:
'In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement',
[Errors.WebCompatFunction]:
'Without web compability enabled functions can not be declared at top level, inside a block, or as the body of an if statement',
[Errors.ClassForbiddenAsStatement]: "Class declaration can't appear in single-statement context",
[Errors.InvalidAwaitIdent]: "'await' may not be used as an identifier in this context",
[Errors.InvalidLHSInOfForLoop]: 'Invalid left-hand side in for-%0',
[Errors.CantAssignToInOfForLoop]: 'Invalid left-hand side in for-%0',
[Errors.InvalidAssignmentInOfForLoop]: 'Invalid assignment in for-%0',
[Errors.InvalidForAwait]: 'for await (... of ...) is only valid in async functions and async generators',
[Errors.InvalidTemplateContinuation]:
Expand All @@ -279,10 +265,9 @@ export const errorMessages: {
[Errors.NewlineAfterThrow]: 'Illegal newline after throw',
[Errors.StrictWith]: 'Strict mode code may not include a with statement',
[Errors.IllegalReturn]: 'Illegal return statement',
[Errors.InvalidForLHSBinding]: 'The for-header left hand side binding declaration is not destructible',
[Errors.InvalidNewTarget]: 'new.target only allowed within functions',
[Errors.InvalidEscapedKeyword]: 'Keywords must be written literally, without embedded escapes',
[Errors.MissingPrivateName]: "''#' not followed by identifier",
[Errors.MissingPrivateName]: "'#' not followed by identifier",
[Errors.InvalidStrictStatic]: '`Static` is a reserved word in strict mode',
[Errors.FutureReservedWordInStrictModeNotId]:
'The use of a future reserved word for an identifier is invalid. The identifier name is reserved in strict mode',
Expand All @@ -293,13 +278,10 @@ export const errorMessages: {
[Errors.DisallowedInContext]: "'%0' may not be used as an identifier in this context",
[Errors.AwaitOutsideAsync]: 'Await is only valid in async functions',
[Errors.InvalidImportExportSloppy]: 'The %0 keyword can only be used with the module goal',
[Errors.InvalidExportAtTopLevel]: 'The `export` keyword is only supported at the top level',
[Errors.InvalidNestedExport]: 'The `export` keyword can not be nested in another statement',
[Errors.UnicodeOverflow]: 'Unicode codepoint must not be greater than 0x10FFFF',
[Errors.InvalidExportImportSource]: '%0 source must be string',
[Errors.InvalidKeywordAsAlias]: 'Only a identifier can be used to indicate alias',
[Errors.InvalidDefaultImport]: "Only '*' or '{...}' can be imported after default",
[Errors.NoIdentOrDynamicName]: 'Method must have an identifier or dynamic name',
[Errors.TrailingDecorators]: 'Trailing decorator may be followed by method',
[Errors.GeneratorConstructor]: "Decorators can't be used with a constructor",
[Errors.AwaitOrYieldIdentInModule]: "'%0' may not be used as an identifier in this context",
Expand Down
12 changes: 7 additions & 5 deletions src/lexer/identifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Token, descKeywordTable } from '../token';
import { Chars } from '../chars';
import { nextCP, consumeMultiUnitCodePoint, fromCodePoint, toHex } from './';
import { CharTypes, CharFlags, isIdentifierPart } from './charClassifier';
import { report, Errors } from '../errors';
import { report, reportAt, Errors } from '../errors';
import { unicodeLookup } from '../unicode';

/**
Expand Down Expand Up @@ -132,8 +132,10 @@ export function scanIdentifierUnicodeEscape(parser: ParserState): number | void
*/
export function scanUnicodeEscapeValue(parser: ParserState): number {
let codePoint = 0;

// First handle a delimited Unicode escape, e.g. \u{1F4A9}
if (parser.nextCP === Chars.LeftBrace) {
const startPos = parser.index;
while (CharTypes[nextCP(parser)] & CharFlags.Hex) {
codePoint = (codePoint << 4) | toHex(parser.nextCP);
// Check this early to avoid `code` wrapping to a negative on overflow (which is
Expand All @@ -145,7 +147,7 @@ export function scanUnicodeEscapeValue(parser: ParserState): number {

// At least 4 characters have to be read
if (codePoint < 1 || (parser.nextCP as number) !== Chars.RightBrace) {
report(parser, Errors.InvalidHexEscapeSequence);
reportAt(startPos, parser.line, startPos - 1, Errors.InvalidHexEscapeSequence);
}
nextCP(parser); // consumes '}'
return codePoint;
Expand All @@ -154,11 +156,11 @@ export function scanUnicodeEscapeValue(parser: ParserState): number {
if ((CharTypes[parser.nextCP] & CharFlags.Hex) === 0) report(parser, Errors.InvalidHexEscapeSequence); // first one is mandatory

const c2 = parser.source.charCodeAt(parser.index + 1);
if ((CharTypes[c2] & CharFlags.Hex) === 0) report(parser, Errors.Unexpected);
if ((CharTypes[c2] & CharFlags.Hex) === 0) report(parser, Errors.InvalidHexEscapeSequence);
const c3 = parser.source.charCodeAt(parser.index + 2);
if ((CharTypes[c3] & CharFlags.Hex) === 0) report(parser, Errors.Unexpected);
if ((CharTypes[c3] & CharFlags.Hex) === 0) report(parser, Errors.InvalidHexEscapeSequence);
const c4 = parser.source.charCodeAt(parser.index + 3);
if ((CharTypes[c4] & CharFlags.Hex) === 0) report(parser, Errors.Unexpected);
if ((CharTypes[c4] & CharFlags.Hex) === 0) report(parser, Errors.InvalidHexEscapeSequence);

codePoint = (toHex(parser.nextCP) << 12) | (toHex(c2) << 8) | (toHex(c3) << 4) | toHex(c4);

Expand Down
24 changes: 12 additions & 12 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2161,7 +2161,7 @@ export function parseForStatement(
const isOf = parser.token === Token.OfKeyword;

if (parser.assignable & AssignmentKind.NotAssignable) {
report(parser, Errors.InvalidLHSInOfForLoop, isOf && forAwait ? 'await' : isOf ? 'of' : 'in');
report(parser, Errors.CantAssignToInOfForLoop, isOf && forAwait ? 'await' : isOf ? 'of' : 'in');
}
reinterpretToPattern(parser, init);
nextToken(parser, context | Context.AllowRegExp);
Expand Down Expand Up @@ -2198,7 +2198,7 @@ export function parseForStatement(

if (!isVarDecl) {
if (destructible & DestructuringKind.MustDestruct && parser.token !== Token.Assign) {
report(parser, Errors.ForLoopInvalidLHS);
report(parser, Errors.ForLoopCantAssignTo);
}

init = parseAssignmentExpression(parser, context | Context.DisallowIn, 0, tokenIndex, linePos, colPos, init);
Expand Down Expand Up @@ -2986,7 +2986,7 @@ export function parseAssignmentExpression(
*/
if ((parser.token & Token.IsAssignOp) > 0) {
if (parser.assignable & AssignmentKind.NotAssignable) {
report(parser, Errors.InvalidLHS);
report(parser, Errors.CantAssignTo);
}
if (
(parser.token === Token.Assign && (left.type as string) === 'ArrayExpression') ||
Expand Down Expand Up @@ -3141,7 +3141,7 @@ export function parseBinaryExpression(
} as ESTree.BinaryExpression | ESTree.LogicalExpression);
}

if (parser.token === Token.Assign) report(parser, Errors.InvalidLHS);
if (parser.token === Token.Assign) report(parser, Errors.CantAssignTo);

return left;
}
Expand Down Expand Up @@ -4573,7 +4573,7 @@ export function parseArrayExpressionOrPattern(

if (consumeOpt(parser, context | Context.AllowRegExp, Token.Assign)) {
if (parser.assignable & AssignmentKind.NotAssignable) {
reportAt(parser.index, parser.line, parser.index - 3, Errors.InvalidLHS);
reportAt(parser.index, parser.line, parser.index - 3, Errors.CantAssignTo);
} else if (context & Context.OptionsLexical) {
declareName(parser, context, scope, tokenValue, type, 0, 0);
if (origin & BindingOrigin.Export) {
Expand Down Expand Up @@ -4761,11 +4761,11 @@ function parseArrayOrObjectAssignmentPattern(
// DestructuringAssignmentTarget[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]
//

if (parser.token !== Token.Assign) report(parser, Errors.InvalidLHS);
if (parser.token !== Token.Assign) report(parser, Errors.CantAssignTo);

nextToken(parser, context | Context.AllowRegExp);

if (destructible & DestructuringKind.CannotDestruct) report(parser, Errors.InvalidLHS);
if (destructible & DestructuringKind.CannotDestruct) report(parser, Errors.CantAssignTo);

reinterpretToPattern(parser, node);

Expand Down Expand Up @@ -4896,7 +4896,7 @@ function parseSpreadElement(
: parser.destructible;
}
} else {
if (type) report(parser, Errors.InvalidLHSInit);
if (type) report(parser, Errors.CantAssignToInit);

argument = parseLeftHandSideExpression(
parser,
Expand All @@ -4911,7 +4911,7 @@ function parseSpreadElement(
const { token, tokenIndex } = parser;

if (token === Token.Assign && token !== closingToken && token !== Token.Comma) {
if (parser.assignable & AssignmentKind.NotAssignable) report(parser, Errors.InvalidLHSInit);
if (parser.assignable & AssignmentKind.NotAssignable) report(parser, Errors.CantAssignToInit);

argument = parseAssignmentExpression(parser, context, inGroup, tokenIndex, linePos, colPos, argument);

Expand Down Expand Up @@ -4950,7 +4950,7 @@ function parseSpreadElement(
}

if (consumeOpt(parser, context | Context.AllowRegExp, Token.Assign)) {
if (destructible & DestructuringKind.CannotDestruct) report(parser, Errors.InvalidLHS);
if (destructible & DestructuringKind.CannotDestruct) report(parser, Errors.CantAssignTo);

reinterpretToPattern(parser, argument);

Expand Down Expand Up @@ -6390,7 +6390,7 @@ export function parseParenthesizedExpression(
consume(parser, context, Token.RightParen);

if (destructible & DestructuringKind.CannotDestruct && destructible & DestructuringKind.MustDestruct)
report(parser, Errors.InvalidLHSValidRHS);
report(parser, Errors.CantAssignToValidRHS);

destructible |=
parser.destructible & DestructuringKind.Yield
Expand Down Expand Up @@ -7072,7 +7072,7 @@ export function parseAsyncArrowOrCallExpression(
if (parser.token === Token.Arrow) {
if (isComplex) parser.flags |= Flags.SimpleParameterList;
if (!assignable) report(parser, Errors.IllegalArrowFunctionParams);
if (destructible & DestructuringKind.CannotDestruct) report(parser, Errors.InvalidLHSInAsyncArrow);
if (destructible & DestructuringKind.CannotDestruct) report(parser, Errors.CantAssignToAsyncArrow);
if (destructible & DestructuringKind.AssignableDestruct) report(parser, Errors.InvalidArrowDestructLHS);
if (parser.flags & Flags.NewLine || flags & Flags.NewLine) report(parser, Errors.InvalidLineBreak);
if (destructible & DestructuringKind.Await) report(parser, Errors.AwaitInParameter);
Expand Down

0 comments on commit 66098ea

Please sign in to comment.