forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenize.js
513 lines (431 loc) · 15.5 KB
/
tokenize.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// Token types:
//
// { t: 'Doctype',
// v: String (entire Doctype declaration from the source),
// name: String,
// systemId: String (optional),
// publicId: String (optional)
// }
//
// { t: 'Comment',
// v: String (not including "<!--" and "-->")
// }
//
// { t: 'Chars',
// v: String (pure text like you might pass to document.createTextNode,
// no character references)
// }
//
// { t: 'Tag',
// isEnd: Boolean (optional),
// isSelfClosing: Boolean (optional),
// n: String (tag name, in lowercase or camel case),
// attrs: dictionary of { String: [tokens] }
// OR [{ String: [tokens] }, TemplateTag tokens...]
// (only for start tags; required)
// }
//
// { t: 'CharRef',
// v: String (entire character reference from the source, e.g. "&"),
// cp: [Integer] (array of Unicode code point numbers it expands to)
// }
//
// We keep around both the original form of the character reference and its
// expansion so that subsequent processing steps have the option to
// re-emit it (if they are generating HTML) or interpret it. Named and
// numerical code points may be more than 16 bits, in which case they
// need to passed through codePointToString to make a JavaScript string.
// Most named entities and all numeric character references are one codepoint
// (e.g. "&" is [38]), but a few are two codepoints.
//
// { t: 'TemplateTag',
// v: HTMLTools.TemplateTag
// }
// The HTML tokenization spec says to preprocess the input stream to replace
// CR(LF)? with LF. However, preprocessing `scanner` would complicate things
// by making indexes not match the input (e.g. for error messages), so we just
// keep in mind as we go along that an LF might be represented by CRLF or CR.
// In most cases, it doesn't actually matter what combination of whitespace
// characters are present (e.g. inside tags).
var HTML_SPACE = /^[\f\n\r\t ]/;
var convertCRLF = function (str) {
return str.replace(/\r\n?/g, '\n');
};
getComment = HTMLTools.Parse.getComment = function (scanner) {
if (scanner.rest().slice(0, 4) !== '<!--')
return null;
scanner.pos += 4;
// Valid comments are easy to parse; they end at the first `--`!
// Our main job is throwing errors.
var rest = scanner.rest();
if (rest.charAt(0) === '>' || rest.slice(0, 2) === '->')
scanner.fatal("HTML comment can't start with > or ->");
var closePos = rest.indexOf('-->');
if (closePos < 0)
scanner.fatal("Unclosed HTML comment");
var commentContents = rest.slice(0, closePos);
if (commentContents.slice(-1) === '-')
scanner.fatal("HTML comment must end at first `--`");
if (commentContents.indexOf("--") >= 0)
scanner.fatal("HTML comment cannot contain `--` anywhere");
if (commentContents.indexOf('\u0000') >= 0)
scanner.fatal("HTML comment cannot contain NULL");
scanner.pos += closePos + 3;
return { t: 'Comment',
v: convertCRLF(commentContents) };
};
var skipSpaces = function (scanner) {
while (HTML_SPACE.test(scanner.peek()))
scanner.pos++;
};
var requireSpaces = function (scanner) {
if (! HTML_SPACE.test(scanner.peek()))
scanner.fatal("Expected space");
skipSpaces(scanner);
};
var getDoctypeQuotedString = function (scanner) {
var quote = scanner.peek();
if (! (quote === '"' || quote === "'"))
scanner.fatal("Expected single or double quote in DOCTYPE");
scanner.pos++;
if (scanner.peek() === quote)
// prevent a falsy return value (empty string)
scanner.fatal("Malformed DOCTYPE");
var str = '';
var ch;
while ((ch = scanner.peek()), ch !== quote) {
if ((! ch) || (ch === '\u0000') || (ch === '>'))
scanner.fatal("Malformed DOCTYPE");
str += ch;
scanner.pos++;
}
scanner.pos++;
return str;
};
// See http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#the-doctype.
//
// If `getDocType` sees "<!DOCTYPE" (case-insensitive), it will match or fail fatally.
getDoctype = HTMLTools.Parse.getDoctype = function (scanner) {
if (HTMLTools.asciiLowerCase(scanner.rest().slice(0, 9)) !== '<!doctype')
return null;
var start = scanner.pos;
scanner.pos += 9;
requireSpaces(scanner);
var ch = scanner.peek();
if ((! ch) || (ch === '>') || (ch === '\u0000'))
scanner.fatal('Malformed DOCTYPE');
var name = ch;
scanner.pos++;
while ((ch = scanner.peek()), ! (HTML_SPACE.test(ch) || ch === '>')) {
if ((! ch) || (ch === '\u0000'))
scanner.fatal('Malformed DOCTYPE');
name += ch;
scanner.pos++;
}
name = HTMLTools.asciiLowerCase(name);
// Now we're looking at a space or a `>`.
skipSpaces(scanner);
var systemId = null;
var publicId = null;
if (scanner.peek() !== '>') {
// Now we're essentially in the "After DOCTYPE name state" of the tokenizer,
// but we're not looking at space or `>`.
// this should be "public" or "system".
var publicOrSystem = HTMLTools.asciiLowerCase(scanner.rest().slice(0, 6));
if (publicOrSystem === 'system') {
scanner.pos += 6;
requireSpaces(scanner);
systemId = getDoctypeQuotedString(scanner);
skipSpaces(scanner);
if (scanner.peek() !== '>')
scanner.fatal("Malformed DOCTYPE");
} else if (publicOrSystem === 'public') {
scanner.pos += 6;
requireSpaces(scanner);
publicId = getDoctypeQuotedString(scanner);
if (scanner.peek() !== '>') {
requireSpaces(scanner);
if (scanner.peek() !== '>') {
systemId = getDoctypeQuotedString(scanner);
skipSpaces(scanner);
if (scanner.peek() !== '>')
scanner.fatal("Malformed DOCTYPE");
}
}
} else {
scanner.fatal("Expected PUBLIC or SYSTEM in DOCTYPE");
}
}
// looking at `>`
scanner.pos++;
var result = { t: 'Doctype',
v: scanner.input.slice(start, scanner.pos),
name: name };
if (systemId)
result.systemId = systemId;
if (publicId)
result.publicId = publicId;
return result;
};
// The special character `{` is only allowed as the first character
// of a Chars, so that we have a chance to detect template tags.
var getChars = makeRegexMatcher(/^[^&<\u0000][^&<\u0000{]*/);
var assertIsTemplateTag = function (x) {
if (! (x instanceof HTMLTools.TemplateTag))
throw new Error("Expected an instance of HTMLTools.TemplateTag");
return x;
};
// Returns the next HTML token, or `null` if we reach EOF.
//
// Note that if we have a `getTemplateTag` function that sometimes
// consumes characters and emits nothing (e.g. in the case of template
// comments), we may go from not-at-EOF to at-EOF and return `null`,
// while otherwise we always find some token to return.
getHTMLToken = HTMLTools.Parse.getHTMLToken = function (scanner, dataMode) {
var result = null;
if (scanner.getTemplateTag) {
// Try to parse a template tag by calling out to the provided
// `getTemplateTag` function. If the function returns `null` but
// consumes characters, it must have parsed a comment or something,
// so we loop and try it again. If it ever returns `null` without
// consuming anything, that means it didn't see anything interesting
// so we look for a normal token. If it returns a truthy value,
// the value must be instanceof HTMLTools.TemplateTag. We wrap it
// in a Special token.
var lastPos = scanner.pos;
result = scanner.getTemplateTag(
scanner,
(dataMode === 'rcdata' ? TEMPLATE_TAG_POSITION.IN_RCDATA :
(dataMode === 'rawtext' ? TEMPLATE_TAG_POSITION.IN_RAWTEXT :
TEMPLATE_TAG_POSITION.ELEMENT)));
if (result)
return { t: 'TemplateTag', v: assertIsTemplateTag(result) };
else if (scanner.pos > lastPos)
return null;
}
var chars = getChars(scanner);
if (chars)
return { t: 'Chars',
v: convertCRLF(chars) };
var ch = scanner.peek();
if (! ch)
return null; // EOF
if (ch === '\u0000')
scanner.fatal("Illegal NULL character");
if (ch === '&') {
if (dataMode !== 'rawtext') {
var charRef = getCharacterReference(scanner);
if (charRef)
return charRef;
}
scanner.pos++;
return { t: 'Chars',
v: '&' };
}
// If we're here, we're looking at `<`.
if (scanner.peek() === '<' && dataMode) {
// don't interpret tags
scanner.pos++;
return { t: 'Chars',
v: '<' };
}
// `getTag` will claim anything starting with `<` not followed by `!`.
// `getComment` takes `<!--` and getDoctype takes `<!doctype`.
result = (getTagToken(scanner) || getComment(scanner) || getDoctype(scanner));
if (result)
return result;
scanner.fatal("Unexpected `<!` directive.");
};
var getTagName = makeRegexMatcher(/^[a-zA-Z][^\f\n\r\t />{]*/);
var getClangle = makeRegexMatcher(/^>/);
var getSlash = makeRegexMatcher(/^\//);
var getAttributeName = makeRegexMatcher(/^[^>/\u0000"'<=\f\n\r\t ][^\f\n\r\t /=>"'<\u0000]*/);
// Try to parse `>` or `/>`, mutating `tag` to be self-closing in the latter
// case (and failing fatally if `/` isn't followed by `>`).
// Return tag if successful.
var handleEndOfTag = function (scanner, tag) {
if (getClangle(scanner))
return tag;
if (getSlash(scanner)) {
if (! getClangle(scanner))
scanner.fatal("Expected `>` after `/`");
tag.isSelfClosing = true;
return tag;
}
return null;
};
// Scan a quoted or unquoted attribute value (omit `quote` for unquoted).
var getAttributeValue = function (scanner, quote) {
if (quote) {
if (scanner.peek() !== quote)
return null;
scanner.pos++;
}
var tokens = [];
var charsTokenToExtend = null;
var charRef;
while (true) {
var ch = scanner.peek();
var templateTag;
var curPos = scanner.pos;
if (quote && ch === quote) {
scanner.pos++;
return tokens;
} else if ((! quote) && (HTML_SPACE.test(ch) || ch === '>')) {
return tokens;
} else if (! ch) {
scanner.fatal("Unclosed attribute in tag");
} else if (quote ? ch === '\u0000' : ('\u0000"\'<=`'.indexOf(ch) >= 0)) {
scanner.fatal("Unexpected character in attribute value");
} else if (ch === '&' &&
(charRef = getCharacterReference(scanner, true,
quote || '>'))) {
tokens.push(charRef);
charsTokenToExtend = null;
} else if (scanner.getTemplateTag &&
((templateTag = scanner.getTemplateTag(
scanner, TEMPLATE_TAG_POSITION.IN_ATTRIBUTE)) ||
scanner.pos > curPos /* `{{! comment}}` */)) {
if (templateTag) {
tokens.push({t: 'TemplateTag',
v: assertIsTemplateTag(templateTag)});
charsTokenToExtend = null;
}
} else {
if (! charsTokenToExtend) {
charsTokenToExtend = { t: 'Chars', v: '' };
tokens.push(charsTokenToExtend);
}
charsTokenToExtend.v += (ch === '\r' ? '\n' : ch);
scanner.pos++;
if (quote && ch === '\r' && scanner.peek() === '\n')
scanner.pos++;
}
}
};
var hasOwnProperty = Object.prototype.hasOwnProperty;
getTagToken = HTMLTools.Parse.getTagToken = function (scanner) {
if (! (scanner.peek() === '<' && scanner.rest().charAt(1) !== '!'))
return null;
scanner.pos++;
var tag = { t: 'Tag' };
// now looking at the character after `<`, which is not a `!`
if (scanner.peek() === '/') {
tag.isEnd = true;
scanner.pos++;
}
var tagName = getTagName(scanner);
if (! tagName)
scanner.fatal("Expected tag name after `<`");
tag.n = HTMLTools.properCaseTagName(tagName);
if (scanner.peek() === '/' && tag.isEnd)
scanner.fatal("End tag can't have trailing slash");
if (handleEndOfTag(scanner, tag))
return tag;
if (scanner.isEOF())
scanner.fatal("Unclosed `<`");
if (! HTML_SPACE.test(scanner.peek()))
// e.g. `<a{{b}}>`
scanner.fatal("Expected space after tag name");
// we're now in "Before attribute name state" of the tokenizer
skipSpaces(scanner);
if (scanner.peek() === '/' && tag.isEnd)
scanner.fatal("End tag can't have trailing slash");
if (handleEndOfTag(scanner, tag))
return tag;
if (tag.isEnd)
scanner.fatal("End tag can't have attributes");
tag.attrs = {};
var nondynamicAttrs = tag.attrs;
while (true) {
// Note: at the top of this loop, we've already skipped any spaces.
// This will be set to true if after parsing the attribute, we should
// require spaces (or else an end of tag, i.e. `>` or `/>`).
var spacesRequiredAfter = false;
// first, try for a template tag.
var curPos = scanner.pos;
var templateTag = (scanner.getTemplateTag &&
scanner.getTemplateTag(
scanner, TEMPLATE_TAG_POSITION.IN_START_TAG));
if (templateTag || (scanner.pos > curPos)) {
if (templateTag) {
if (tag.attrs === nondynamicAttrs)
tag.attrs = [nondynamicAttrs];
tag.attrs.push({ t: 'TemplateTag',
v: assertIsTemplateTag(templateTag) });
} // else, must have scanned a `{{! comment}}`
spacesRequiredAfter = true;
} else {
var attributeName = getAttributeName(scanner);
if (! attributeName)
scanner.fatal("Expected attribute name in tag");
// Throw error on `{` in attribute name. This provides *some* error message
// if someone writes `<a x{{y}}>` or `<a x{{y}}=z>`. The HTML tokenization
// spec doesn't say that `{` is invalid, but the DOM API (setAttribute) won't
// allow it, so who cares.
if (attributeName.indexOf('{') >= 0)
scanner.fatal("Unexpected `{` in attribute name.");
attributeName = HTMLTools.properCaseAttributeName(attributeName);
if (hasOwnProperty.call(nondynamicAttrs, attributeName))
scanner.fatal("Duplicate attribute in tag: " + attributeName);
nondynamicAttrs[attributeName] = [];
skipSpaces(scanner);
if (handleEndOfTag(scanner, tag))
return tag;
var ch = scanner.peek();
if (! ch)
scanner.fatal("Unclosed <");
if ('\u0000"\'<'.indexOf(ch) >= 0)
scanner.fatal("Unexpected character after attribute name in tag");
if (ch === '=') {
scanner.pos++;
skipSpaces(scanner);
ch = scanner.peek();
if (! ch)
scanner.fatal("Unclosed <");
if ('\u0000><=`'.indexOf(ch) >= 0)
scanner.fatal("Unexpected character after = in tag");
if ((ch === '"') || (ch === "'"))
nondynamicAttrs[attributeName] = getAttributeValue(scanner, ch);
else
nondynamicAttrs[attributeName] = getAttributeValue(scanner);
spacesRequiredAfter = true;
}
}
// now we are in the "post-attribute" position, whether it was a template tag
// attribute (like `{{x}}`) or a normal one (like `x` or `x=y`).
if (handleEndOfTag(scanner, tag))
return tag;
if (scanner.isEOF())
scanner.fatal("Unclosed `<`");
if (spacesRequiredAfter)
requireSpaces(scanner);
else
skipSpaces(scanner);
if (handleEndOfTag(scanner, tag))
return tag;
}
};
TEMPLATE_TAG_POSITION = HTMLTools.TEMPLATE_TAG_POSITION = {
ELEMENT: 1,
IN_START_TAG: 2,
IN_ATTRIBUTE: 3,
IN_RCDATA: 4,
IN_RAWTEXT: 5
};
// tagName must be proper case
isLookingAtEndTag = function (scanner, tagName) {
var rest = scanner.rest();
var pos = 0; // into rest
var firstPart = /^<\/([a-zA-Z]+)/.exec(rest);
if (firstPart &&
HTMLTools.properCaseTagName(firstPart[1]) === tagName) {
// we've seen `</foo`, now see if the end tag continues
pos += firstPart[0].length;
while (pos < rest.length && HTML_SPACE.test(rest.charAt(pos)))
pos++;
if (pos < rest.length && rest.charAt(pos) === '>')
return true;
}
return false;
};