-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
tokeniser.js
345 lines (320 loc) · 7.07 KB
/
tokeniser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import { syntaxError } from "./error.js";
import { unescape } from "./productions/helpers.js";
// These regular expressions use the sticky flag so they will only match at
// the current location (ie. the offset of lastIndex).
const tokenRe = {
// This expression uses a lookahead assertion to catch false matches
// against integers early.
decimal:
/-?(?=[0-9]*\.|[0-9]+[eE])(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][-+]?[0-9]+)?|[0-9]+[Ee][-+]?[0-9]+)/y,
integer: /-?(0([Xx][0-9A-Fa-f]+|[0-7]*)|[1-9][0-9]*)/y,
identifier: /[_-]?[A-Za-z][0-9A-Z_a-z-]*/y,
string: /"[^"]*"/y,
whitespace: /[\t\n\r ]+/y,
comment: /\/\/.*|\/\*[\s\S]*?\*\//y,
other: /[^\t\n\r 0-9A-Za-z]/y,
};
export const typeNameKeywords = [
"ArrayBuffer",
"SharedArrayBuffer",
"DataView",
"Int8Array",
"Int16Array",
"Int32Array",
"Uint8Array",
"Uint16Array",
"Uint32Array",
"Uint8ClampedArray",
"BigInt64Array",
"BigUint64Array",
"Float16Array",
"Float32Array",
"Float64Array",
"any",
"object",
"symbol",
];
export const stringTypes = ["ByteString", "DOMString", "USVString"];
export const argumentNameKeywords = [
"async",
"attribute",
"callback",
"const",
"constructor",
"deleter",
"dictionary",
"enum",
"getter",
"includes",
"inherit",
"interface",
"iterable",
"maplike",
"namespace",
"partial",
"required",
"setlike",
"setter",
"static",
"stringifier",
"typedef",
"unrestricted",
];
const nonRegexTerminals = [
"-Infinity",
"FrozenArray",
"Infinity",
"NaN",
"ObservableArray",
"Promise",
"bigint",
"boolean",
"byte",
"double",
"false",
"float",
"long",
"mixin",
"null",
"octet",
"optional",
"or",
"readonly",
"record",
"sequence",
"short",
"true",
"undefined",
"unsigned",
"void",
].concat(argumentNameKeywords, stringTypes, typeNameKeywords);
const punctuations = [
"(",
")",
",",
"...",
":",
";",
"<",
"=",
">",
"?",
"*",
"[",
"]",
"{",
"}",
];
const reserved = [
// "constructor" is now a keyword
"_constructor",
"toString",
"_toString",
];
/**
* @typedef {ArrayItemType<ReturnType<typeof tokenise>>} Token
* @param {string} str
*/
function tokenise(str) {
const tokens = [];
let lastCharIndex = 0;
let trivia = "";
let line = 1;
let index = 0;
while (lastCharIndex < str.length) {
const nextChar = str.charAt(lastCharIndex);
let result = -1;
if (/[\t\n\r ]/.test(nextChar)) {
result = attemptTokenMatch("whitespace", { noFlushTrivia: true });
} else if (nextChar === "/") {
result = attemptTokenMatch("comment", { noFlushTrivia: true });
}
if (result !== -1) {
const currentTrivia = tokens.pop().value;
line += (currentTrivia.match(/\n/g) || []).length;
trivia += currentTrivia;
index -= 1;
} else if (/[-0-9.A-Z_a-z]/.test(nextChar)) {
result = attemptTokenMatch("decimal");
if (result === -1) {
result = attemptTokenMatch("integer");
}
if (result === -1) {
result = attemptTokenMatch("identifier");
const lastIndex = tokens.length - 1;
const token = tokens[lastIndex];
if (result !== -1) {
if (reserved.includes(token.value)) {
const message = `${unescape(
token.value,
)} is a reserved identifier and must not be used.`;
throw new WebIDLParseError(
syntaxError(tokens, lastIndex, null, message),
);
} else if (nonRegexTerminals.includes(token.value)) {
token.type = "inline";
}
}
}
} else if (nextChar === '"') {
result = attemptTokenMatch("string");
}
for (const punctuation of punctuations) {
if (str.startsWith(punctuation, lastCharIndex)) {
tokens.push({
type: "inline",
value: punctuation,
trivia,
line,
index,
});
trivia = "";
lastCharIndex += punctuation.length;
result = lastCharIndex;
break;
}
}
// other as the last try
if (result === -1) {
result = attemptTokenMatch("other");
}
if (result === -1) {
throw new Error("Token stream not progressing");
}
lastCharIndex = result;
index += 1;
}
// remaining trivia as eof
tokens.push({
type: "eof",
value: "",
trivia,
line,
index,
});
return tokens;
/**
* @param {keyof typeof tokenRe} type
* @param {object} options
* @param {boolean} [options.noFlushTrivia]
*/
function attemptTokenMatch(type, { noFlushTrivia } = {}) {
const re = tokenRe[type];
re.lastIndex = lastCharIndex;
const result = re.exec(str);
if (result) {
tokens.push({ type, value: result[0], trivia, line, index });
if (!noFlushTrivia) {
trivia = "";
}
return re.lastIndex;
}
return -1;
}
}
export class Tokeniser {
/**
* @param {string} idl
*/
constructor(idl) {
this.source = tokenise(idl);
this.position = 0;
}
/**
* @param {string} message
* @return {never}
*/
error(message) {
throw new WebIDLParseError(
syntaxError(this.source, this.position, this.current, message),
);
}
/**
* @param {string} type
*/
probeKind(type) {
return (
this.source.length > this.position &&
this.source[this.position].type === type
);
}
/**
* @param {string} value
*/
probe(value) {
return (
this.probeKind("inline") && this.source[this.position].value === value
);
}
/**
* @param {...string} candidates
*/
consumeKind(...candidates) {
for (const type of candidates) {
if (!this.probeKind(type)) continue;
const token = this.source[this.position];
this.position++;
return token;
}
}
/**
* @param {...string} candidates
*/
consume(...candidates) {
if (!this.probeKind("inline")) return;
const token = this.source[this.position];
for (const value of candidates) {
if (token.value !== value) continue;
this.position++;
return token;
}
}
/**
* @param {string} value
*/
consumeIdentifier(value) {
if (!this.probeKind("identifier")) {
return;
}
if (this.source[this.position].value !== value) {
return;
}
return this.consumeKind("identifier");
}
/**
* @param {number} position
*/
unconsume(position) {
this.position = position;
}
}
export class WebIDLParseError extends Error {
/**
* @param {object} options
* @param {string} options.message
* @param {string} options.bareMessage
* @param {string} options.context
* @param {number} options.line
* @param {*} options.sourceName
* @param {string} options.input
* @param {*[]} options.tokens
*/
constructor({
message,
bareMessage,
context,
line,
sourceName,
input,
tokens,
}) {
super(message);
this.name = "WebIDLParseError"; // not to be mangled
this.bareMessage = bareMessage;
this.context = context;
this.line = line;
this.sourceName = sourceName;
this.input = input;
this.tokens = tokens;
}
}