Skip to content

Commit 67afee4

Browse files
authored
improve errors around around dots (#4176)
extracted from @leebyron 's excellent #3807 will reduce that diff
1 parent 6731c76 commit 67afee4

File tree

2 files changed

+32
-7
lines changed

2 files changed

+32
-7
lines changed

src/language/__tests__/lexer-test.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,13 @@ describe('Lexer', () => {
165165
});
166166
});
167167

168+
it('reports unexpected characters', () => {
169+
expectSyntaxError('.').to.deep.equal({
170+
message: 'Syntax Error: Unexpected character: ".".',
171+
locations: [{ line: 1, column: 1 }],
172+
});
173+
});
174+
168175
it('errors respect whitespace', () => {
169176
let caughtError;
170177
try {
@@ -852,7 +859,8 @@ describe('Lexer', () => {
852859
});
853860

854861
expectSyntaxError('.123').to.deep.equal({
855-
message: 'Syntax Error: Unexpected character: ".".',
862+
message:
863+
'Syntax Error: Invalid number, expected digit before ".", did you mean "0.123"?',
856864
locations: [{ line: 1, column: 1 }],
857865
});
858866

@@ -1030,7 +1038,7 @@ describe('Lexer', () => {
10301038

10311039
it('lex reports useful unknown character error', () => {
10321040
expectSyntaxError('..').to.deep.equal({
1033-
message: 'Syntax Error: Unexpected character: ".".',
1041+
message: 'Syntax Error: Unexpected "..", did you mean "..."?',
10341042
locations: [{ line: 1, column: 1 }],
10351043
});
10361044

src/language/lexer.ts

+22-5
Original file line numberDiff line numberDiff line change
@@ -258,14 +258,31 @@ function readNextToken(lexer: Lexer, start: number): Token {
258258
return createToken(lexer, TokenKind.PAREN_L, position, position + 1);
259259
case 0x0029: // )
260260
return createToken(lexer, TokenKind.PAREN_R, position, position + 1);
261-
case 0x002e: // .
262-
if (
263-
body.charCodeAt(position + 1) === 0x002e &&
264-
body.charCodeAt(position + 2) === 0x002e
265-
) {
261+
case 0x002e: {
262+
// .
263+
const nextCode = body.charCodeAt(position + 1);
264+
if (nextCode === 0x002e && body.charCodeAt(position + 2) === 0x002e) {
266265
return createToken(lexer, TokenKind.SPREAD, position, position + 3);
267266
}
267+
if (nextCode === 0x002e) {
268+
throw syntaxError(
269+
lexer.source,
270+
position,
271+
'Unexpected "..", did you mean "..."?',
272+
);
273+
} else if (isDigit(nextCode)) {
274+
const digits = lexer.source.body.slice(
275+
position + 1,
276+
readDigits(lexer, position + 1, nextCode),
277+
);
278+
throw syntaxError(
279+
lexer.source,
280+
position,
281+
`Invalid number, expected digit before ".", did you mean "0.${digits}"?`,
282+
);
283+
}
268284
break;
285+
}
269286
case 0x003a: // :
270287
return createToken(lexer, TokenKind.COLON, position, position + 1);
271288
case 0x003d: // =

0 commit comments

Comments
 (0)