1 | import {eat, finishToken, lookaheadTypeAndKeyword, match} from "../tokenizer/index";
|
2 |
|
3 | import {formatTokenType, TokenType as tt} from "../tokenizer/types";
|
4 | import {charCodes} from "../util/charcodes";
|
5 | import {input, state} from "./base";
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | export function isContextual(contextualKeyword) {
|
11 | return state.contextualKeyword === contextualKeyword;
|
12 | }
|
13 |
|
14 | export function isLookaheadContextual(contextualKeyword) {
|
15 | const l = lookaheadTypeAndKeyword();
|
16 | return l.type === tt.name && l.contextualKeyword === contextualKeyword;
|
17 | }
|
18 |
|
19 |
|
20 | export function eatContextual(contextualKeyword) {
|
21 | return state.contextualKeyword === contextualKeyword && eat(tt.name);
|
22 | }
|
23 |
|
24 |
|
25 | export function expectContextual(contextualKeyword) {
|
26 | if (!eatContextual(contextualKeyword)) {
|
27 | unexpected();
|
28 | }
|
29 | }
|
30 |
|
31 |
|
32 | export function canInsertSemicolon() {
|
33 | return match(tt.eof) || match(tt.braceR) || hasPrecedingLineBreak();
|
34 | }
|
35 |
|
36 | export function hasPrecedingLineBreak() {
|
37 | const prevToken = state.tokens[state.tokens.length - 1];
|
38 | const lastTokEnd = prevToken ? prevToken.end : 0;
|
39 | for (let i = lastTokEnd; i < state.start; i++) {
|
40 | const code = input.charCodeAt(i);
|
41 | if (
|
42 | code === charCodes.lineFeed ||
|
43 | code === charCodes.carriageReturn ||
|
44 | code === 0x2028 ||
|
45 | code === 0x2029
|
46 | ) {
|
47 | return true;
|
48 | }
|
49 | }
|
50 | return false;
|
51 | }
|
52 |
|
53 | export function isLineTerminator() {
|
54 | return eat(tt.semi) || canInsertSemicolon();
|
55 | }
|
56 |
|
57 |
|
58 |
|
59 | export function semicolon() {
|
60 | if (!isLineTerminator()) {
|
61 | unexpected('Unexpected token, expected ";"');
|
62 | }
|
63 | }
|
64 |
|
65 |
|
66 |
|
67 | export function expect(type) {
|
68 | const matched = eat(type);
|
69 | if (!matched) {
|
70 | unexpected(`Unexpected token, expected "${formatTokenType(type)}"`);
|
71 | }
|
72 | }
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 | export function unexpected(message = "Unexpected token", pos = state.start) {
|
79 | if (state.error) {
|
80 | return;
|
81 | }
|
82 |
|
83 | const err = new SyntaxError(message);
|
84 | err.pos = pos;
|
85 | state.error = err;
|
86 | state.pos = input.length;
|
87 | finishToken(tt.eof);
|
88 | }
|