Debian Codegraph @

js/src/frontend/TokenStream.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // JS lexical scanner.
8
9 #include "frontend/TokenStream.h"
10
11 #include "mozilla/ArrayUtils.h"
12 #include "mozilla/Attributes.h"
13 #include "mozilla/Likely.h"
14 #include "mozilla/Maybe.h"
15 #include "mozilla/MemoryChecking.h"
16 #include "mozilla/ScopeExit.h"
17 #include "mozilla/Span.h"
18 #include "mozilla/TemplateLib.h"
19 #include "mozilla/TextUtils.h"
20 #include "mozilla/Utf8.h"
21
22 #include <algorithm>
23 #include <iterator>
24 #include <limits>
25 #include <stdarg.h>
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <type_traits>
29 #include <utility>
30
31 #include "jsnum.h"
32
33 #include "frontend/FrontendContext.h"
34 #include "frontend/Parser.h"
35 #include "frontend/ParserAtom.h"
36 #include "frontend/ReservedWords.h"
37 #include "js/CharacterEncoding.h" // JS::ConstUTF8CharsZ
38 #include "js/ColumnNumber.h" // JS::LimitedColumnNumberOneOrigin, JS::ColumnNumberOneOrigin, JS::TaggedColumnNumberOneOrigin
39 #include "js/ErrorReport.h" // JSErrorBase
40 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
41 #include "js/Printf.h" // JS_smprintf
42 #include "js/RegExpFlags.h" // JS::RegExpFlags
43 #include "js/UniquePtr.h"
44 #include "util/Text.h"
45 #include "util/Unicode.h"
46 #include "vm/FrameIter.h" // js::{,NonBuiltin}FrameIter
47 #include "vm/JSContext.h"
48 #include "vm/Realm.h"
49
50 using mozilla::AsciiAlphanumericToNumber;
51 using mozilla::AssertedCast;
52 using mozilla::DecodeOneUtf8CodePoint;
53 using mozilla::IsAscii;
54 using mozilla::IsAsciiAlpha;
55 using mozilla::IsAsciiDigit;
56 using mozilla::IsAsciiHexDigit;
57 using mozilla::IsTrailingUnit;
58 using mozilla::MakeScopeExit;
59 using mozilla::Maybe;
60 using mozilla::PointerRangeSize;
61 using mozilla::Span;
62 using mozilla::Utf8Unit;
63
64 using JS::ReadOnlyCompileOptions;
65 using JS::RegExpFlag;
66 using JS::RegExpFlags;
67
68 struct ReservedWordInfo {
69 const char* chars; // C string with reserved word text
70 js::frontend::TokenKind tokentype;
71 };
72
73 static const ReservedWordInfo reservedWords[] = {
74 #define RESERVED_WORD_INFO(word, name, type) {#word, js::frontend::type},
75 FOR_EACH_JAVASCRIPT_RESERVED_WORD(RESERVED_WORD_INFO)
76 #undef RESERVED_WORD_INFO
77 };
78
79 enum class ReservedWordsIndex : size_t {
80 #define ENTRY_(_1, NAME, _3) NAME,
81 FOR_EACH_JAVASCRIPT_RESERVED_WORD(ENTRY_)
82 #undef ENTRY_
83 };
84
85 // Returns a ReservedWordInfo for the specified characters, or nullptr if the
86 // string is not a reserved word.
87 template <typename CharT>
88 static const ReservedWordInfo* FindReservedWord(const CharT* s, size_t length) {
89 MOZ_ASSERT(length != 0);
90
91 size_t i;
92 const ReservedWordInfo* rw;
93 const char* chars;
94
95 #define JSRW_LENGTH() length
96 #define JSRW_AT(column) s[column]
97 #define JSRW_GOT_MATCH(index) \
98 i = (index); \
99 goto got_match;
100 #define JSRW_TEST_GUESS(index) \
101 i = (index); \
102 goto test_guess;
103 #define JSRW_NO_MATCH() goto no_match;
104 #include "frontend/ReservedWordsGenerated.h"
105 #undef JSRW_NO_MATCH
106 #undef JSRW_TEST_GUESS
107 #undef JSRW_GOT_MATCH
108 #undef JSRW_AT
109 #undef JSRW_LENGTH
110
111 got_match:
112 return &reservedWords[i];
113
114 test_guess:
115 rw = &reservedWords[i];
116 chars = rw->chars;
117 do {
118 if (*s++ != static_cast<unsigned char>(*chars++)) {
119 goto no_match;
120 }
121 } while (--length != 0);
122 return rw;
123
124 no_match:
125 return nullptr;
126 }
127
128 template <>
129 MOZ_ALWAYS_INLINE const ReservedWordInfo* FindReservedWord<Utf8Unit>(
130 const Utf8Unit* units, size_t length) {
131 return FindReservedWord(Utf8AsUnsignedChars(units), length);
132 }
133
134 static const ReservedWordInfo* FindReservedWord(
135 const js::frontend::TaggedParserAtomIndex atom) {
136 switch (atom.rawData()) {
137 #define CASE_(_1, NAME, _3) \
138 case js::frontend::TaggedParserAtomIndex::WellKnownRawData::NAME(): \
139 return &reservedWords[size_t(ReservedWordsIndex::NAME)];
140 FOR_EACH_JAVASCRIPT_RESERVED_WORD(CASE_)
141 #undef CASE_
142 }
143
144 return nullptr;
145 }
146
147 template <typename CharT>
148 static constexpr bool IsAsciiBinary(CharT c) {
149 using UnsignedCharT = std::make_unsigned_t<CharT>;
150 auto uc = static_cast<UnsignedCharT>(c);
151 return uc == '0' || uc == '1';
152 }
153
154 template <typename CharT>
155 static constexpr bool IsAsciiOctal(CharT c) {
156 using UnsignedCharT = std::make_unsigned_t<CharT>;
157 auto uc = static_cast<UnsignedCharT>(c);
158 return '0' <= uc && uc <= '7';
159 }
160
161 template <typename CharT>
162 static constexpr uint8_t AsciiOctalToNumber(CharT c) {
163 using UnsignedCharT = std::make_unsigned_t<CharT>;
164 auto uc = static_cast<UnsignedCharT>(c);
165 return uc - '0';
166 }
167
168 namespace js {
169
170 namespace frontend {
171
172 bool IsKeyword(TaggedParserAtomIndex atom) {
173 if (const ReservedWordInfo* rw = FindReservedWord(atom)) {
174 return TokenKindIsKeyword(rw->tokentype);
175 }
176
177 return false;
178 }
179
180 TokenKind ReservedWordTokenKind(TaggedParserAtomIndex name) {
181 if (const ReservedWordInfo* rw = FindReservedWord(name)) {
182 return rw->tokentype;
183 }
184
185 return TokenKind::Limit;
186 }
187
188 const char* ReservedWordToCharZ(TaggedParserAtomIndex name) {
189 if (const ReservedWordInfo* rw = FindReservedWord(name)) {
190 return ReservedWordToCharZ(rw->tokentype);
191 }
192
193 return nullptr;
194 }
195
196 const char* ReservedWordToCharZ(TokenKind tt) {
197 MOZ_ASSERT(tt != TokenKind::Name);
198 switch (tt) {
199 #define EMIT_CASE(word, name, type) \
200 case type: \
201 return #word;
202 FOR_EACH_JAVASCRIPT_RESERVED_WORD(EMIT_CASE)
203 #undef EMIT_CASE
204 default:
205 MOZ_ASSERT_UNREACHABLE("Not a reserved word PropertyName.");
206 }
207 return nullptr;
208 }
209
210 TaggedParserAtomIndex TokenStreamAnyChars::reservedWordToPropertyName(
211 TokenKind tt) const {
212 MOZ_ASSERT(tt != TokenKind::Name);
213 switch (tt) {
214 #define EMIT_CASE(word, name, type) \
215 case type: \
216 return TaggedParserAtomIndex::WellKnown::name();
217 FOR_EACH_JAVASCRIPT_RESERVED_WORD(EMIT_CASE)
218 #undef EMIT_CASE
219 default:
220 MOZ_ASSERT_UNREACHABLE("Not a reserved word TokenKind.");
221 }
222 return TaggedParserAtomIndex::null();
223 }
224
225 SourceCoords::SourceCoords(FrontendContext* fc, uint32_t initialLineNumber,
226 uint32_t initialOffset)
227 : lineStartOffsets_(fc), initialLineNum_(initialLineNumber), lastIndex_(0) {
228 // This is actually necessary! Removing it causes compile errors on
229 // GCC and clang. You could try declaring this:
230 //
231 // const uint32_t SourceCoords::MAX_PTR;
232 //
233 // which fixes the GCC/clang error, but causes bustage on Windows. Sigh.
234 //
235 uint32_t maxPtr = MAX_PTR;
236
237 // The first line begins at buffer offset |initialOffset|. MAX_PTR is the
238 // sentinel. The appends cannot fail because |lineStartOffsets_| has
239 // statically-allocated elements.
240 MOZ_ASSERT(lineStartOffsets_.capacity() >= 2);
241 MOZ_ALWAYS_TRUE(lineStartOffsets_.reserve(2));
242 lineStartOffsets_.infallibleAppend(initialOffset);
243 lineStartOffsets_.infallibleAppend(maxPtr);
244 }
245
246 MOZ_ALWAYS_INLINE bool SourceCoords::add(uint32_t lineNum,
247 uint32_t lineStartOffset) {
248 uint32_t index = indexFromLineNumber(lineNum);
249 uint32_t sentinelIndex = lineStartOffsets_.length() - 1;
250
251 MOZ_ASSERT(lineStartOffsets_[0] <= lineStartOffset);
252 MOZ_ASSERT(lineStartOffsets_[sentinelIndex] == MAX_PTR);
253
254 if (index == sentinelIndex) {
255 // We haven't seen this newline before. Update lineStartOffsets_
256 // only if lineStartOffsets_.append succeeds, to keep sentinel.
257 // Otherwise return false to tell TokenStream about OOM.
258 uint32_t maxPtr = MAX_PTR;
259 if (!lineStartOffsets_.append(maxPtr)) {
260 static_assert(std::is_same_v<decltype(lineStartOffsets_.allocPolicy()),
261 TempAllocPolicy&>,
262 "this function's caller depends on it reporting an "
263 "error on failure, as TempAllocPolicy ensures");
264 return false;
265 }
266
267 lineStartOffsets_[index] = lineStartOffset;
268 } else {
269 // We have seen this newline before (and ungot it). Do nothing (other
270 // than checking it hasn't mysteriously changed).
271 // This path can be executed after hitting OOM, so check index.
272 MOZ_ASSERT_IF(index < sentinelIndex,
273 lineStartOffsets_[index] == lineStartOffset);
274 }
275 return true;
276 }
277
278 MOZ_ALWAYS_INLINE bool SourceCoords::fill(const SourceCoords& other) {
279 MOZ_ASSERT(lineStartOffsets_[0] == other.lineStartOffsets_[0]);
280 MOZ_ASSERT(lineStartOffsets_.back() == MAX_PTR);
281 MOZ_ASSERT(other.lineStartOffsets_.back() == MAX_PTR);
282
283 if (lineStartOffsets_.length() >= other.lineStartOffsets_.length()) {
284 return true;
285 }
286
287 uint32_t sentinelIndex = lineStartOffsets_.length() - 1;
288 lineStartOffsets_[sentinelIndex] = other.lineStartOffsets_[sentinelIndex];
289
290 for (size_t i = sentinelIndex + 1; i < other.lineStartOffsets_.length();
291 i++) {
292 if (!lineStartOffsets_.append(other.lineStartOffsets_[i])) {
293 return false;
294 }
295 }
296 return true;
297 }
298
299 MOZ_ALWAYS_INLINE uint32_t
300 SourceCoords::indexFromOffset(uint32_t offset) const {
301 uint32_t iMin, iMax, iMid;
302
303 if (lineStartOffsets_[lastIndex_] <= offset) {
304 // If we reach here, offset is on a line the same as or higher than
305 // last time. Check first for the +0, +1, +2 cases, because they
306 // typically cover 85--98% of cases.
307 if (offset < lineStartOffsets_[lastIndex_ + 1]) {
308 return lastIndex_; // index is same as last time
309 }
310
311 // If we reach here, there must be at least one more entry (plus the
312 // sentinel). Try it.
313 lastIndex_++;
314 if (offset < lineStartOffsets_[lastIndex_ + 1]) {
315 return lastIndex_; // index is one higher than last time
316 }
317
318 // The same logic applies here.
319 lastIndex_++;
320 if (offset < lineStartOffsets_[lastIndex_ + 1]) {
321 return lastIndex_; // index is two higher than last time
322 }
323
324 // No luck. Oh well, we have a better-than-default starting point for
325 // the binary search.
326 iMin = lastIndex_ + 1;
327 MOZ_ASSERT(iMin <
328 lineStartOffsets_.length() - 1); // -1 due to the sentinel
329
330 } else {
331 iMin = 0;
332 }
333
334 // This is a binary search with deferred detection of equality, which was
335 // marginally faster in this case than a standard binary search.
336 // The -2 is because |lineStartOffsets_.length() - 1| is the sentinel, and we
337 // want one before that.
338 iMax = lineStartOffsets_.length() - 2;
339 while (iMax > iMin) {
340 iMid = iMin + (iMax - iMin) / 2;
341 if (offset >= lineStartOffsets_[iMid + 1]) {
342 iMin = iMid + 1; // offset is above lineStartOffsets_[iMid]
343 } else {
344 iMax = iMid; // offset is below or within lineStartOffsets_[iMid]
345 }
346 }
347
348 MOZ_ASSERT(iMax == iMin);
349 MOZ_ASSERT(lineStartOffsets_[iMin] <= offset);
350 MOZ_ASSERT(offset < lineStartOffsets_[iMin + 1]);
351
352 lastIndex_ = iMin;
353 return iMin;
354 }
355
356 SourceCoords::LineToken SourceCoords::lineToken(uint32_t offset) const {
357 return LineToken(indexFromOffset(offset), offset);
358 }
359
360 TokenStreamAnyChars::TokenStreamAnyChars(FrontendContext* fc,
361 const ReadOnlyCompileOptions& options,
362 StrictModeGetter* smg)
363 : fc(fc),
364 options_(options),
365 strictModeGetter_(smg),
366 filename_(options.filename()),
367 longLineColumnInfo_(fc),
368 srcCoords(fc, options.lineno, options.scriptSourceOffset),
369 lineno(options.lineno),
370 mutedErrors(options.mutedErrors()) {
371 // |isExprEnding| was initially zeroed: overwrite the true entries here.
372 isExprEnding[size_t(TokenKind::Comma)] = true;
373 isExprEnding[size_t(TokenKind::Semi)] = true;
374 isExprEnding[size_t(TokenKind::Colon)] = true;
375 isExprEnding[size_t(TokenKind::RightParen)] = true;
376 isExprEnding[size_t(TokenKind::RightBracket)] = true;
377 isExprEnding[size_t(TokenKind::RightCurly)] = true;
378 }
379
380 template <typename Unit>
381 TokenStreamCharsBase<Unit>::TokenStreamCharsBase(FrontendContext* fc,
382 ParserAtomsTable* parserAtoms,
383 const Unit* units,
384 size_t length,
385 size_t startOffset)
386 : TokenStreamCharsShared(fc, parserAtoms),
387 sourceUnits(units, length, startOffset) {}
388
389 bool FillCharBufferFromSourceNormalizingAsciiLineBreaks(CharBuffer& charBuffer,
390 const char16_t* cur,
391 const char16_t* end) {
392 MOZ_ASSERT(charBuffer.length() == 0);
393
394 while (cur < end) {
395 char16_t ch = *cur++;
396 if (ch == '\r') {
397 ch = '\n';
398 if (cur < end && *cur == '\n') {
399 cur++;
400 }
401 }
402
403 if (!charBuffer.append(ch)) {
404 return false;
405 }
406 }
407
408 MOZ_ASSERT(cur == end);
409 return true;
410 }
411
412 bool FillCharBufferFromSourceNormalizingAsciiLineBreaks(CharBuffer& charBuffer,
413 const Utf8Unit* cur,
414 const Utf8Unit* end) {
415 MOZ_ASSERT(charBuffer.length() == 0);
416
417 while (cur < end) {
418 Utf8Unit unit = *cur++;
419 if (MOZ_LIKELY(IsAscii(unit))) {
420 char16_t ch = unit.toUint8();
421 if (ch == '\r') {
422 ch = '\n';
423 if (cur < end && *cur == Utf8Unit('\n')) {
424 cur++;
425 }
426 }
427
428 if (!charBuffer.append(ch)) {
429 return false;
430 }
431
432 continue;
433 }
434
435 Maybe<char32_t> ch = DecodeOneUtf8CodePoint(unit, &cur, end);
436 MOZ_ASSERT(ch.isSome(),
437 "provided source text should already have been validated");
438
439 if (!AppendCodePointToCharBuffer(charBuffer, ch.value())) {
440 return false;
441 }
442 }
443
444 MOZ_ASSERT(cur == end);
445 return true;
446 }
447
448 template <typename Unit, class AnyCharsAccess>
449 TokenStreamSpecific<Unit, AnyCharsAccess>::TokenStreamSpecific(
450 FrontendContext* fc, ParserAtomsTable* parserAtoms,
451 const ReadOnlyCompileOptions& options, const Unit* units, size_t length)
452 : TokenStreamChars<Unit, AnyCharsAccess>(fc, parserAtoms, units, length,
453 options.scriptSourceOffset) {}
454
455 bool TokenStreamAnyChars::checkOptions() {
456 // Constrain starting columns to where they will saturate.
457 if (options().column.oneOriginValue() >
458 JS::LimitedColumnNumberOneOrigin::Limit) {
459 reportErrorNoOffset(JSMSG_BAD_COLUMN_NUMBER);
460 return false;
461 }
462
463 return true;
464 }
465
466 void TokenStreamAnyChars::reportErrorNoOffset(unsigned errorNumber, ...) const {
467 va_list args;
468 va_start(args, errorNumber);
469
470 reportErrorNoOffsetVA(errorNumber, &args);
471
472 va_end(args);
473 }
474
475 void TokenStreamAnyChars::reportErrorNoOffsetVA(unsigned errorNumber,
476 va_list* args) const {
477 ErrorMetadata metadata;
478 computeErrorMetadataNoOffset(&metadata);
479
480 ReportCompileErrorLatin1VA(fc, std::move(metadata), nullptr, errorNumber,
481 args);
482 }
483
484 [[nodiscard]] MOZ_ALWAYS_INLINE bool
485 TokenStreamAnyChars::internalUpdateLineInfoForEOL(uint32_t lineStartOffset) {
486 prevLinebase = linebase;
487 linebase = lineStartOffset;
488 lineno++;
489
490 // On overflow, report error.
491 if (MOZ_UNLIKELY(!lineno)) {
492 reportErrorNoOffset(JSMSG_BAD_LINE_NUMBER);
493 return false;
494 }
495
496 return srcCoords.add(lineno, linebase);
497 }
498
499 #ifdef DEBUG
500
501 template <>
502 inline void SourceUnits<char16_t>::assertNextCodePoint(
503 const PeekedCodePoint<char16_t>& peeked) {
504 char32_t c = peeked.codePoint();
505 if (c < unicode::NonBMPMin) {
506 MOZ_ASSERT(peeked.lengthInUnits() == 1);
507 MOZ_ASSERT(ptr[0] == c);
508 } else {
509 MOZ_ASSERT(peeked.lengthInUnits() == 2);
510 char16_t lead, trail;
511 unicode::UTF16Encode(c, &lead, &trail);
512 MOZ_ASSERT(ptr[0] == lead);
513 MOZ_ASSERT(ptr[1] == trail);
514 }
515 }
516
517 template <>
518 inline void SourceUnits<Utf8Unit>::assertNextCodePoint(
519 const PeekedCodePoint<Utf8Unit>& peeked) {
520 char32_t c = peeked.codePoint();
521
522 // This is all roughly indulgence of paranoia only for assertions, so the
523 // reimplementation of UTF-8 encoding a code point is (we think) a virtue.
524 uint8_t expectedUnits[4] = {};
525 if (c < 0x80) {
526 expectedUnits[0] = AssertedCast<uint8_t>(c);
527 } else if (c < 0x800) {
528 expectedUnits[0] = 0b1100'0000 | (c >> 6);
529 expectedUnits[1] = 0b1000'0000 | (c & 0b11'1111);
530 } else if (c < 0x10000) {
531 expectedUnits[0] = 0b1110'0000 | (c >> 12);
532 expectedUnits[1] = 0b1000'0000 | ((c >> 6) & 0b11'1111);
533 expectedUnits[2] = 0b1000'0000 | (c & 0b11'1111);
534 } else {
535 expectedUnits[0] = 0b1111'0000 | (c >> 18);
536 expectedUnits[1] = 0b1000'0000 | ((c >> 12) & 0b11'1111);
537 expectedUnits[2] = 0b1000'0000 | ((c >> 6) & 0b11'1111);
538 expectedUnits[3] = 0b1000'0000 | (c & 0b11'1111);
539 }
540
541 MOZ_ASSERT(peeked.lengthInUnits() <= 4);
542 for (uint8_t i = 0; i < peeked.lengthInUnits(); i++) {
543 MOZ_ASSERT(expectedUnits[i] == ptr[i].toUint8());
544 }
545 }
546
547 #endif // DEBUG
548
549 static MOZ_ALWAYS_INLINE void RetractPointerToCodePointBoundary(
550 const Utf8Unit** ptr, const Utf8Unit* limit) {
551 MOZ_ASSERT(*ptr <= limit);
552
553 // |limit| is a code point boundary.
554 if (MOZ_UNLIKELY(*ptr == limit)) {
555 return;
556 }
557
558 // Otherwise rewind past trailing units to the start of the code point.
559 #ifdef DEBUG
560 size_t retracted = 0;
561 #endif
562 while (MOZ_UNLIKELY(IsTrailingUnit((*ptr)[0]))) {
563 --*ptr;
564 #ifdef DEBUG
565 retracted++;
566 #endif
567 }
568
569 MOZ_ASSERT(retracted < 4,
570 "the longest UTF-8 code point is four units, so this should never "
571 "retract more than three units");
572 }
573
574 static MOZ_ALWAYS_INLINE void RetractPointerToCodePointBoundary(
575 const char16_t** ptr, const char16_t* limit) {
576 MOZ_ASSERT(*ptr <= limit);
577
578 // |limit| is a code point boundary.
579 if (MOZ_UNLIKELY(*ptr == limit)) {
580 return;
581 }
582
583 // Otherwise the pointer must be retracted by one iff it splits a two-unit
584 // code point.
585 if (MOZ_UNLIKELY(unicode::IsTrailSurrogate((*ptr)[0]))) {
586 // Outside test suites testing garbage WTF-16, it's basically guaranteed
587 // here that |(*ptr)[-1] (*ptr)[0]| is a surrogate pair.
588 if (MOZ_LIKELY(unicode::IsLeadSurrogate((*ptr)[-1]))) {
589 --*ptr;
590 }
591 }
592 }
593
594 template <typename Unit>
595 JS::ColumnNumberUnsignedOffset TokenStreamAnyChars::computeColumnOffset(
596 const LineToken lineToken, const uint32_t offset,
597 const SourceUnits<Unit>& sourceUnits) const {
598 lineToken.assertConsistentOffset(offset);
599
600 const uint32_t start = srcCoords.lineStart(lineToken);
601 const uint32_t offsetInLine = offset - start;
602
603 if constexpr (std::is_same_v<Unit, char16_t>) {
604 // Column offset is in UTF-16 code units.
605 return JS::ColumnNumberUnsignedOffset(offsetInLine);
606 }
607
608 return computeColumnOffsetForUTF8(lineToken, offset, start, offsetInLine,
609 sourceUnits);
610 }
611
612 template <typename Unit>
613 JS::ColumnNumberUnsignedOffset TokenStreamAnyChars::computeColumnOffsetForUTF8(
614 const LineToken lineToken, const uint32_t offset, const uint32_t start,
615 const uint32_t offsetInLine, const SourceUnits<Unit>& sourceUnits) const {
616 const uint32_t line = lineNumber(lineToken);
617
618 // Reset the previous offset/column number offset cache for this line, if the
619 // previous lookup wasn't on this line.
620 if (line != lineOfLastColumnComputation_) {
621 lineOfLastColumnComputation_ = line;
622 lastChunkVectorForLine_ = nullptr;
623 lastOffsetOfComputedColumn_ = start;
624 lastComputedColumnOffset_ = JS::ColumnNumberUnsignedOffset::zero();
625 }
626
627 // Compute and return the final column number offset from a partially
628 // calculated offset/column number offset, using the last-cached
629 // offset/column number offset if they're more optimal.
630 auto OffsetFromPartial =
631 [this, offset, &sourceUnits](
632 uint32_t partialOffset,
633 JS::ColumnNumberUnsignedOffset partialColumnOffset,
634 UnitsType unitsType) {
635 MOZ_ASSERT(partialOffset <= offset);
636
637 // If the last lookup on this line was closer to |offset|, use it.
638 if (partialOffset < this->lastOffsetOfComputedColumn_ &&
639 this->lastOffsetOfComputedColumn_ <= offset) {
640 partialOffset = this->lastOffsetOfComputedColumn_;
641 partialColumnOffset = this->lastComputedColumnOffset_;
642 }
643
644 const Unit* begin = sourceUnits.codeUnitPtrAt(partialOffset);
645 const Unit* end = sourceUnits.codeUnitPtrAt(offset);
646
647 size_t offsetDelta =
648 AssertedCast<uint32_t>(PointerRangeSize(begin, end));
649 partialOffset += offsetDelta;
650
651 if (unitsType == UnitsType::GuaranteedSingleUnit) {
652 MOZ_ASSERT(unicode::CountUTF16CodeUnits(begin, end) == offsetDelta,
653 "guaranteed-single-units also guarantee pointer distance "
654 "equals UTF-16 code unit count");
655 partialColumnOffset += JS::ColumnNumberUnsignedOffset(offsetDelta);
656 } else {
657 partialColumnOffset += JS::ColumnNumberUnsignedOffset(
658 AssertedCast<uint32_t>(unicode::CountUTF16CodeUnits(begin, end)));
659 }
660
661 this->lastOffsetOfComputedColumn_ = partialOffset;
662 this->lastComputedColumnOffset_ = partialColumnOffset;
663 return partialColumnOffset;
664 };
665
666 // We won't add an entry to |longLineColumnInfo_| for lines where the maximum
667 // column has offset less than this value. The most common (non-minified)
668 // long line length is likely 80ch, maybe 100ch, so we use that, rounded up to
669 // the next power of two for efficient division/multiplication below.
670 constexpr uint32_t ColumnChunkLength = mozilla::tl::RoundUpPow2<100>::value;
671
672 // The index within any associated |Vector<ChunkInfo>| of |offset|'s chunk.
673 const uint32_t chunkIndex = offsetInLine / ColumnChunkLength;
674 if (chunkIndex == 0) {
675 // We don't know from an |offset| in the zeroth chunk that this line is even
676 // long. First-chunk info is mostly useless, anyway -- we have |start|
677 // already. So if we have *easy* access to that zeroth chunk, use it --
678 // otherwise just count pessimally. (This will still benefit from caching
679 // the last column/offset for computations for successive offsets, so it's
680 // not *always* worst-case.)
681 UnitsType unitsType;
682 if (lastChunkVectorForLine_ && lastChunkVectorForLine_->length() > 0) {
683 MOZ_ASSERT((*lastChunkVectorForLine_)[0].columnOffset() ==
684 JS::ColumnNumberUnsignedOffset::zero());
685 unitsType = (*lastChunkVectorForLine_)[0].unitsType();
686 } else {
687 unitsType = UnitsType::PossiblyMultiUnit;
688 }
689
690 return OffsetFromPartial(start, JS::ColumnNumberUnsignedOffset::zero(),
691 unitsType);
692 }
693
694 // If this line has no chunk vector yet, insert one in the hash map. (The
695 // required index is allocated and filled further down.)
696 if (!lastChunkVectorForLine_) {
697 auto ptr = longLineColumnInfo_.lookupForAdd(line);
698 if (!ptr) {
699 // This could rehash and invalidate a cached vector pointer, but the outer
700 // condition means we don't have a cached pointer.
701 if (!longLineColumnInfo_.add(ptr, line, Vector<ChunkInfo>(fc))) {
702 // In case of OOM, just count columns from the start of the line.
703 fc->recoverFromOutOfMemory();
704 return OffsetFromPartial(start, JS::ColumnNumberUnsignedOffset::zero(),
705 UnitsType::PossiblyMultiUnit);
706 }
707 }
708
709 // Note that adding elements to this vector won't invalidate this pointer.
710 lastChunkVectorForLine_ = &ptr->value();
711 }
712
713 const Unit* const limit = sourceUnits.codeUnitPtrAt(offset);
714
715 auto RetractedOffsetOfChunk = [
716 #ifdef DEBUG
717 this,
718 #endif
719 start, limit,
720 &sourceUnits](uint32_t index) {
721 MOZ_ASSERT(index < this->lastChunkVectorForLine_->length());
722
723 uint32_t naiveOffset = start + index * ColumnChunkLength;
724 const Unit* naivePtr = sourceUnits.codeUnitPtrAt(naiveOffset);
725
726 const Unit* actualPtr = naivePtr;
727 RetractPointerToCodePointBoundary(&actualPtr, limit);
728
729 #ifdef DEBUG
730 if ((*this->lastChunkVectorForLine_)[index].unitsType() ==
731 UnitsType::GuaranteedSingleUnit) {
732 MOZ_ASSERT(naivePtr == actualPtr, "miscomputed unitsType value");
733 }
734 #endif
735
736 return naiveOffset - PointerRangeSize(actualPtr, naivePtr);
737 };
738
739 uint32_t partialOffset;
740 JS::ColumnNumberUnsignedOffset partialColumnOffset;
741 UnitsType unitsType;
742
743 auto entriesLen = AssertedCast<uint32_t>(lastChunkVectorForLine_->length());
744 if (chunkIndex < entriesLen) {
745 // We've computed the chunk |offset| resides in. Compute the column number
746 // from the chunk.
747 partialOffset = RetractedOffsetOfChunk(chunkIndex);
748 partialColumnOffset = (*lastChunkVectorForLine_)[chunkIndex].columnOffset();
749
750 // This is exact if |chunkIndex| isn't the last chunk.
751 unitsType = (*lastChunkVectorForLine_)[chunkIndex].unitsType();
752
753 // Otherwise the last chunk is pessimistically assumed to contain multi-unit
754 // code points because we haven't fully examined its contents yet -- they
755 // may not have been tokenized yet, they could contain encoding errors, or
756 // they might not even exist.
757 MOZ_ASSERT_IF(chunkIndex == entriesLen - 1,
758 (*lastChunkVectorForLine_)[chunkIndex].unitsType() ==
759 UnitsType::PossiblyMultiUnit);
760 } else {
761 // Extend the vector from its last entry or the start of the line. (This is
762 // also a suitable partial start point if we must recover from OOM.)
763 if (entriesLen > 0) {
764 partialOffset = RetractedOffsetOfChunk(entriesLen - 1);
765 partialColumnOffset =
766 (*lastChunkVectorForLine_)[entriesLen - 1].columnOffset();
767 } else {
768 partialOffset = start;
769 partialColumnOffset = JS::ColumnNumberUnsignedOffset::zero();
770 }
771
772 if (!lastChunkVectorForLine_->reserve(chunkIndex + 1)) {
773 // As earlier, just start from the greatest offset/column in case of OOM.
774 fc->recoverFromOutOfMemory();
775 return OffsetFromPartial(partialOffset, partialColumnOffset,
776 UnitsType::PossiblyMultiUnit);
777 }
778
779 // OOM is no longer possible now. \o/
780
781 // The vector always begins with the column of the line start, i.e. zero,
782 // with chunk units pessimally assumed not single-unit.
783 if (entriesLen == 0) {
784 lastChunkVectorForLine_->infallibleAppend(
785 ChunkInfo(JS::ColumnNumberUnsignedOffset::zero(),
786 UnitsType::PossiblyMultiUnit));
787 entriesLen++;
788 }
789
790 do {
791 const Unit* const begin = sourceUnits.codeUnitPtrAt(partialOffset);
792 const Unit* chunkLimit = sourceUnits.codeUnitPtrAt(
793 start + std::min(entriesLen++ * ColumnChunkLength, offsetInLine));
794
795 MOZ_ASSERT(begin < chunkLimit);
796 MOZ_ASSERT(chunkLimit <= limit);
797
798 static_assert(
799 ColumnChunkLength > SourceUnitTraits<Unit>::maxUnitsLength - 1,
800 "any retraction below is assumed to never underflow to the "
801 "preceding chunk, even for the longest code point");
802
803 // Prior tokenizing ensured that [begin, limit) is validly encoded, and
804 // |begin < chunkLimit|, so any retraction here can't underflow.
805 RetractPointerToCodePointBoundary(&chunkLimit, limit);
806
807 MOZ_ASSERT(begin < chunkLimit);
808 MOZ_ASSERT(chunkLimit <= limit);
809
810 size_t numUnits = PointerRangeSize(begin, chunkLimit);
811 size_t numUTF16CodeUnits =
812 unicode::CountUTF16CodeUnits(begin, chunkLimit);
813
814 // If this chunk (which will become non-final at the end of the loop) is
815 // all single-unit code points, annotate the chunk accordingly.
816 if (numUnits == numUTF16CodeUnits) {
817 lastChunkVectorForLine_->back().guaranteeSingleUnits();
818 }
819
820 partialOffset += numUnits;
821 partialColumnOffset += JS::ColumnNumberUnsignedOffset(numUTF16CodeUnits);
822
823 lastChunkVectorForLine_->infallibleEmplaceBack(
824 partialColumnOffset, UnitsType::PossiblyMultiUnit);
825 } while (entriesLen < chunkIndex + 1);
826
827 // We're at a spot in the current final chunk, and final chunks never have
828 // complete units information, so be pessimistic.
829 unitsType = UnitsType::PossiblyMultiUnit;
830 }
831
832 return OffsetFromPartial(partialOffset, partialColumnOffset, unitsType);
833 }
834
835 template <typename Unit, class AnyCharsAccess>
836 JS::LimitedColumnNumberOneOrigin
837 GeneralTokenStreamChars<Unit, AnyCharsAccess>::computeColumn(
838 LineToken lineToken, uint32_t offset) const {
839 lineToken.assertConsistentOffset(offset);
840
841 const TokenStreamAnyChars& anyChars = anyCharsAccess();
842
843 JS::ColumnNumberUnsignedOffset columnOffset =
844 anyChars.computeColumnOffset(lineToken, offset, this->sourceUnits);
845
846 if (!lineToken.isFirstLine()) {
847 return JS::LimitedColumnNumberOneOrigin::fromUnlimited(
848 JS::ColumnNumberOneOrigin() + columnOffset);
849 }
850
851 if (1 + columnOffset.value() > JS::LimitedColumnNumberOneOrigin::Limit) {
852 return JS::LimitedColumnNumberOneOrigin::limit();
853 }
854
855 return JS::LimitedColumnNumberOneOrigin::fromUnlimited(
856 (anyChars.options_.column + columnOffset).oneOriginValue());
857 }
858
859 template <typename Unit, class AnyCharsAccess>
860 void GeneralTokenStreamChars<Unit, AnyCharsAccess>::computeLineAndColumn(
861 uint32_t offset, uint32_t* line,
862 JS::LimitedColumnNumberOneOrigin* column) const {
863 const TokenStreamAnyChars& anyChars = anyCharsAccess();
864
865 auto lineToken = anyChars.lineToken(offset);
866 *line = anyChars.lineNumber(lineToken);
867 *column = computeColumn(lineToken, offset);
868 }
869
870 template <class AnyCharsAccess>
871 MOZ_COLD void TokenStreamChars<Utf8Unit, AnyCharsAccess>::internalEncodingError(
872 uint8_t relevantUnits, unsigned errorNumber, ...) {
873 va_list args;
874 va_start(args, errorNumber);
875
876 do {
877 size_t offset = this->sourceUnits.offset();
878
879 ErrorMetadata err;
880
881 TokenStreamAnyChars& anyChars = anyCharsAccess();
882
883 bool canAddLineOfContext = fillExceptingContext(&err, offset);
884 if (canAddLineOfContext) {
885 if (!internalComputeLineOfContext(&err, offset)) {
886 break;
887 }
888
889 // As this is an encoding error, the computed window-end must be
890 // identical to the location of the error -- any further on and the
891 // window would contain invalid Unicode.
892 MOZ_ASSERT_IF(err.lineOfContext != nullptr,
893 err.lineLength == err.tokenOffset);
894 }
895
896 auto notes = MakeUnique<JSErrorNotes>();
897 if (!notes) {
898 ReportOutOfMemory(anyChars.fc);
899 break;
900 }
901
902 // The largest encoding of a UTF-8 code point is 4 units. (Encoding an
903 // obsolete 5- or 6-byte code point will complain only about a bad lead
904 // code unit.)
905 constexpr size_t MaxWidth = sizeof("0xHH 0xHH 0xHH 0xHH");
906
907 MOZ_ASSERT(relevantUnits > 0);
908
909 char badUnitsStr[MaxWidth];
910 char* ptr = badUnitsStr;
911 while (relevantUnits > 0) {
912 byteToString(this->sourceUnits.getCodeUnit().toUint8(), ptr);
913 ptr[4] = ' ';
914
915 ptr += 5;
916 relevantUnits--;
917 }
918
919 ptr[-1] = '\0';
920
921 uint32_t line;
922 JS::LimitedColumnNumberOneOrigin column;
923 computeLineAndColumn(offset, &line, &column);
924
925 if (!notes->addNoteASCII(anyChars.fc, anyChars.getFilename().c_str(), 0,
926 line, JS::ColumnNumberOneOrigin(column),
927 GetErrorMessage, nullptr, JSMSG_BAD_CODE_UNITS,
928 badUnitsStr)) {
929 break;
930 }
931
932 ReportCompileErrorLatin1VA(anyChars.fc, std::move(err), std::move(notes),
933 errorNumber, &args);
934 } while (false);
935
936 va_end(args);
937 }
938
939 template <class AnyCharsAccess>
940 MOZ_COLD void TokenStreamChars<Utf8Unit, AnyCharsAccess>::badLeadUnit(
941 Utf8Unit lead) {
942 uint8_t leadValue = lead.toUint8();
943
944 char leadByteStr[5];
945 byteToTerminatedString(leadValue, leadByteStr);
946
947 internalEncodingError(1, JSMSG_BAD_LEADING_UTF8_UNIT, leadByteStr);
948 }
949
950 template <class AnyCharsAccess>
951 MOZ_COLD void TokenStreamChars<Utf8Unit, AnyCharsAccess>::notEnoughUnits(
952 Utf8Unit lead, uint8_t remaining, uint8_t required) {
953 uint8_t leadValue = lead.toUint8();
954
955 MOZ_ASSERT(required == 2 || required == 3 || required == 4);
956 MOZ_ASSERT(remaining < 4);
957 MOZ_ASSERT(remaining < required);
958
959 char leadByteStr[5];
960 byteToTerminatedString(leadValue, leadByteStr);
961
962 // |toHexChar| produces the desired decimal numbers for values < 4.
963 const char expectedStr[] = {toHexChar(required - 1), '\0'};
964 const char actualStr[] = {toHexChar(remaining - 1), '\0'};
965
966 internalEncodingError(remaining, JSMSG_NOT_ENOUGH_CODE_UNITS, leadByteStr,
967 expectedStr, required == 2 ? "" : "s", actualStr,
968 remaining == 2 ? " was" : "s were");
969 }
970
971 template <class AnyCharsAccess>
972 MOZ_COLD void TokenStreamChars<Utf8Unit, AnyCharsAccess>::badTrailingUnit(
973 uint8_t unitsObserved) {
974 Utf8Unit badUnit =
975 this->sourceUnits.addressOfNextCodeUnit()[unitsObserved - 1];
976
977 char badByteStr[5];
978 byteToTerminatedString(badUnit.toUint8(), badByteStr);
979
980 internalEncodingError(unitsObserved, JSMSG_BAD_TRAILING_UTF8_UNIT,
981 badByteStr);
982 }
983
984 template <class AnyCharsAccess>
985 MOZ_COLD void
986 TokenStreamChars<Utf8Unit, AnyCharsAccess>::badStructurallyValidCodePoint(
987 char32_t codePoint, uint8_t codePointLength, const char* reason) {
988 // Construct a string like "0x203D" (including null terminator) to include
989 // in the error message. Write the string end-to-start from end to start
990 // of an adequately sized |char| array, shifting least significant nibbles
991 // off the number and writing the corresponding hex digits until done, then
992 // prefixing with "0x". |codePointStr| points at the incrementally
993 // computed string, within |codePointCharsArray|'s bounds.
994
995 // 0x1F'FFFF is the maximum value that can fit in 3+6+6+6 unconstrained
996 // bits in a four-byte UTF-8 code unit sequence.
997 constexpr size_t MaxHexSize = sizeof(
998 "0x1F"
999 "FFFF"); // including '\0'
1000 char codePointCharsArray[MaxHexSize];
1001
1002 char* codePointStr = std::end(codePointCharsArray);
1003 *--codePointStr = '\0';
1004
1005 // Note that by do-while looping here rather than while-looping, this
1006 // writes a '0' when |codePoint == 0|.
1007 do {
1008 MOZ_ASSERT(codePointCharsArray < codePointStr);
1009 *--codePointStr = toHexChar(codePoint & 0xF);
1010 codePoint >>= 4;
1011 } while (codePoint);
1012
1013 MOZ_ASSERT(codePointCharsArray + 2 <= codePointStr);
1014 *--codePointStr = 'x';
1015 *--codePointStr = '0';
1016
1017 internalEncodingError(codePointLength, JSMSG_FORBIDDEN_UTF8_CODE_POINT,
1018 codePointStr, reason);
1019 }
1020
1021 template <class AnyCharsAccess>
1022 [[nodiscard]] bool
1023 TokenStreamChars<Utf8Unit, AnyCharsAccess>::getNonAsciiCodePointDontNormalize(
1024 Utf8Unit lead, char32_t* codePoint) {
1025 auto onBadLeadUnit = [this, &lead]() { this->badLeadUnit(lead); };
1026
1027 auto onNotEnoughUnits = [this, &lead](uint8_t remaining, uint8_t required) {
1028 this->notEnoughUnits(lead, remaining, required);
1029 };
1030
1031 auto onBadTrailingUnit = [this](uint8_t unitsObserved) {
1032 this->badTrailingUnit(unitsObserved);
1033 };
1034
1035 auto onBadCodePoint = [this](char32_t badCodePoint, uint8_t unitsObserved) {
1036 this->badCodePoint(badCodePoint, unitsObserved);
1037 };
1038
1039 auto onNotShortestForm = [this](char32_t badCodePoint,
1040 uint8_t unitsObserved) {
1041 this->notShortestForm(badCodePoint, unitsObserved);
1042 };
1043
1044 // If a valid code point is decoded, this function call consumes its code
1045 // units. If not, it ungets the lead code unit and invokes the right error
1046 // handler, so on failure we must immediately return false.
1047 SourceUnitsIterator iter(this->sourceUnits);
1048 Maybe<char32_t> maybeCodePoint = DecodeOneUtf8CodePointInline(
1049 lead, &iter, SourceUnitsEnd(), onBadLeadUnit, onNotEnoughUnits,
1050 onBadTrailingUnit, onBadCodePoint, onNotShortestForm);
1051 if (maybeCodePoint.isNothing()) {
1052 return false;
1053 }
1054
1055 *codePoint = maybeCodePoint.value();
1056 return true;
1057 }
1058
1059 template <class AnyCharsAccess>
1060 bool TokenStreamChars<char16_t, AnyCharsAccess>::getNonAsciiCodePoint(
1061 int32_t lead, char32_t* codePoint) {
1062 MOZ_ASSERT(lead != EOF);
1063 MOZ_ASSERT(!isAsciiCodePoint(lead),
1064 "ASCII code unit/point must be handled separately");
1065 MOZ_ASSERT(lead == this->sourceUnits.previousCodeUnit(),
1066 "getNonAsciiCodePoint called incorrectly");
1067
1068 // The code point is usually |lead|: overwrite later if needed.
1069 *codePoint = AssertedCast<char32_t>(lead);
1070
1071 // ECMAScript specifically requires that unpaired UTF-16 surrogates be
1072 // treated as the corresponding code point and not as an error. See
1073 // <https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type>.
1074 // Thus this function does not consider any sequence of 16-bit numbers to
1075 // be intrinsically in error.
1076
1077 // Dispense with single-unit code points and lone trailing surrogates.
1078 if (MOZ_LIKELY(!unicode::IsLeadSurrogate(lead))) {
1079 if (MOZ_UNLIKELY(lead == unicode::LINE_SEPARATOR ||
1080 lead == unicode::PARA_SEPARATOR)) {
1081 if (!updateLineInfoForEOL()) {
1082 #ifdef DEBUG
1083 // Assign to a sentinel value to hopefully cause errors.
1084 *codePoint = std::numeric_limits<char32_t>::max();
1085 #endif
1086 MOZ_MAKE_MEM_UNDEFINED(codePoint, sizeof(*codePoint));
1087 return false;
1088 }
1089
1090 *codePoint = '\n';
1091 } else {
1092 MOZ_ASSERT(!IsLineTerminator(*codePoint));
1093 }
1094
1095 return true;
1096 }
1097
1098 // Also handle a lead surrogate not paired with a trailing surrogate.
1099 if (MOZ_UNLIKELY(
1100 this->sourceUnits.atEnd() ||
1101 !unicode::IsTrailSurrogate(this->sourceUnits.peekCodeUnit()))) {
1102 MOZ_ASSERT(!IsLineTerminator(*codePoint));
1103 return true;
1104 }
1105
1106 // Otherwise we have a multi-unit code point.
1107 *codePoint = unicode::UTF16Decode(lead, this->sourceUnits.getCodeUnit());
1108 MOZ_ASSERT(!IsLineTerminator(*codePoint));
1109 return true;
1110 }
1111
1112 template <class AnyCharsAccess>
1113 bool TokenStreamChars<Utf8Unit, AnyCharsAccess>::getNonAsciiCodePoint(
1114 int32_t unit, char32_t* codePoint) {
1115 MOZ_ASSERT(unit != EOF);
1116 MOZ_ASSERT(!isAsciiCodePoint(unit),
1117 "ASCII code unit/point must be handled separately");
1118
1119 Utf8Unit lead = Utf8Unit(static_cast<unsigned char>(unit));
1120 MOZ_ASSERT(lead == this->sourceUnits.previousCodeUnit(),
1121 "getNonAsciiCodePoint called incorrectly");
1122
1123 auto onBadLeadUnit = [this, &lead]() { this->badLeadUnit(lead); };
1124
1125 auto onNotEnoughUnits = [this, &lead](uint_fast8_t remaining,
1126 uint_fast8_t required) {
1127 this->notEnoughUnits(lead, remaining, required);
1128 };
1129
1130 auto onBadTrailingUnit = [this](uint_fast8_t unitsObserved) {
1131 this->badTrailingUnit(unitsObserved);
1132 };
1133
1134 auto onBadCodePoint = [this](char32_t badCodePoint,
1135 uint_fast8_t unitsObserved) {
1136 this->badCodePoint(badCodePoint, unitsObserved);
1137 };
1138
1139 auto onNotShortestForm = [this](char32_t badCodePoint,
1140 uint_fast8_t unitsObserved) {
1141 this->notShortestForm(badCodePoint, unitsObserved);
1142 };
1143
1144 // This consumes the full, valid code point or ungets |lead| and calls the
1145 // appropriate error functor on failure.
1146 SourceUnitsIterator iter(this->sourceUnits);
1147 Maybe<char32_t> maybeCodePoint = DecodeOneUtf8CodePoint(
1148 lead, &iter, SourceUnitsEnd(), onBadLeadUnit, onNotEnoughUnits,
1149 onBadTrailingUnit, onBadCodePoint, onNotShortestForm);
1150 if (maybeCodePoint.isNothing()) {
1151 return false;
1152 }
1153
1154 char32_t cp = maybeCodePoint.value();
1155 if (MOZ_UNLIKELY(cp == unicode::LINE_SEPARATOR ||
1156 cp == unicode::PARA_SEPARATOR)) {
1157 if (!updateLineInfoForEOL()) {
1158 #ifdef DEBUG
1159 // Assign to a sentinel value to hopefully cause errors.
1160 *codePoint = std::numeric_limits<char32_t>::max();
1161 #endif
1162 MOZ_MAKE_MEM_UNDEFINED(codePoint, sizeof(*codePoint));
1163 return false;
1164 }
1165
1166 *codePoint = '\n';
1167 } else {
1168 MOZ_ASSERT(!IsLineTerminator(cp));
1169 *codePoint = cp;
1170 }
1171
1172 return true;
1173 }
1174
1175 template <>
1176 size_t SourceUnits<char16_t>::findWindowStart(size_t offset) const {
1177 // This is JS's understanding of UTF-16 that allows lone surrogates, so
1178 // we have to exclude lone surrogates from [windowStart, offset) ourselves.
1179
1180 const char16_t* const earliestPossibleStart = codeUnitPtrAt(startOffset_);
1181
1182 const char16_t* const initial = codeUnitPtrAt(offset);
1183 const char16_t* p = initial;
1184
1185 auto HalfWindowSize = [&p, &initial]() {
1186 return PointerRangeSize(p, initial);
1187 };
1188
1189 while (true) {
1190 MOZ_ASSERT(earliestPossibleStart <= p);
1191 MOZ_ASSERT(HalfWindowSize() <= WindowRadius);
1192 if (p <= earliestPossibleStart || HalfWindowSize() >= WindowRadius) {
1193 break;
1194 }
1195
1196 char16_t c = p[-1];
1197
1198 // This stops at U+2028 LINE SEPARATOR or U+2029 PARAGRAPH SEPARATOR in
1199 // string and template literals. These code points do affect line and
1200 // column coordinates, even as they encode their literal values.
1201 if (IsLineTerminator(c)) {
1202 break;
1203 }
1204
1205 // Don't allow invalid UTF-16 in pre-context. (Current users don't
1206 // require this, and this behavior isn't currently imposed on
1207 // pre-context, but these facts might change someday.)
1208
1209 if (MOZ_UNLIKELY(unicode::IsLeadSurrogate(c))) {
1210 break;
1211 }
1212
1213 // Optimistically include the code unit, reverting below if needed.
1214 p--;
1215
1216 // If it's not a surrogate at all, keep going.
1217 if (MOZ_LIKELY(!unicode::IsTrailSurrogate(c))) {
1218 continue;
1219 }
1220
1221 // Stop if we don't have a usable surrogate pair.
1222 if (HalfWindowSize() >= WindowRadius ||
1223 p <= earliestPossibleStart || // trail surrogate at low end
1224 !unicode::IsLeadSurrogate(p[-1])) // no paired lead surrogate
1225 {
1226 p++;
1227 break;
1228 }
1229
1230 p--;
1231 }
1232
1233 MOZ_ASSERT(HalfWindowSize() <= WindowRadius);
1234 return offset - HalfWindowSize();
1235 }
1236
1237 template <>
1238 size_t SourceUnits<Utf8Unit>::findWindowStart(size_t offset) const {
1239 // |offset| must be the location of the error or somewhere before it, so we
1240 // know preceding data is valid UTF-8.
1241
1242 const Utf8Unit* const earliestPossibleStart = codeUnitPtrAt(startOffset_);
1243
1244 const Utf8Unit* const initial = codeUnitPtrAt(offset);
1245 const Utf8Unit* p = initial;
1246
1247 auto HalfWindowSize = [&p, &initial]() {
1248 return PointerRangeSize(p, initial);
1249 };
1250
1251 while (true) {
1252 MOZ_ASSERT(earliestPossibleStart <= p);
1253 MOZ_ASSERT(HalfWindowSize() <= WindowRadius);
1254 if (p <= earliestPossibleStart || HalfWindowSize() >= WindowRadius) {
1255 break;
1256 }
1257
1258 // Peek backward for a line break, and only decrement if there is none.
1259 uint8_t prev = p[-1].toUint8();
1260
1261 // First check for the ASCII LineTerminators.
1262 if (prev == '\r' || prev == '\n') {
1263 break;
1264 }
1265
1266 // Now check for the non-ASCII LineTerminators U+2028 LINE SEPARATOR
1267 // (0xE2 0x80 0xA8) and U+2029 PARAGRAPH (0xE2 0x80 0xA9). If there
1268 // aren't three code units available, some comparison here will fail
1269 // before we'd underflow.
1270 if (MOZ_UNLIKELY((prev == 0xA8 || prev == 0xA9) &&
1271 p[-2].toUint8() == 0x80 && p[-3].toUint8() == 0xE2)) {
1272 break;
1273 }
1274
1275 // Rewind over the non-LineTerminator. This can't underflow
1276 // |earliestPossibleStart| because it begins a code point.
1277 while (IsTrailingUnit(*--p)) {
1278 continue;
1279 }
1280
1281 MOZ_ASSERT(earliestPossibleStart <= p);
1282
1283 // But if we underflowed |WindowRadius|, adjust forward and stop.
1284 if (HalfWindowSize() > WindowRadius) {
1285 static_assert(WindowRadius > 3,
1286 "skipping over non-lead code units below must not "
1287 "advance past |offset|");
1288
1289 while (IsTrailingUnit(*++p)) {
1290 continue;
1291 }
1292
1293 MOZ_ASSERT(HalfWindowSize() < WindowRadius);
1294 break;
1295 }
1296 }
1297
1298 MOZ_ASSERT(HalfWindowSize() <= WindowRadius);
1299 return offset - HalfWindowSize();
1300 }
1301
1302 template <>
1303 size_t SourceUnits<char16_t>::findWindowEnd(size_t offset) const {
1304 const char16_t* const initial = codeUnitPtrAt(offset);
1305 const char16_t* p = initial;
1306
1307 auto HalfWindowSize = [&initial, &p]() {
1308 return PointerRangeSize(initial, p);
1309 };
1310
1311 while (true) {
1312 MOZ_ASSERT(p <= limit_);
1313 MOZ_ASSERT(HalfWindowSize() <= WindowRadius);
1314 if (p >= limit_ || HalfWindowSize() >= WindowRadius) {
1315 break;
1316 }
1317
1318 char16_t c = *p;
1319
1320 // This stops at U+2028 LINE SEPARATOR or U+2029 PARAGRAPH SEPARATOR in
1321 // string and template literals. These code points do affect line and
1322 // column coordinates, even as they encode their literal values.
1323 if (IsLineTerminator(c)) {
1324 break;
1325 }
1326
1327 // Don't allow invalid UTF-16 in post-context. (Current users don't
1328 // require this, and this behavior isn't currently imposed on
1329 // pre-context, but these facts might change someday.)
1330
1331 if (MOZ_UNLIKELY(unicode::IsTrailSurrogate(c))) {
1332 break;
1333 }
1334
1335 // Optimistically consume the code unit, ungetting it below if needed.
1336 p++;
1337
1338 // If it's not a surrogate at all, keep going.
1339 if (MOZ_LIKELY(!unicode::IsLeadSurrogate(c))) {
1340 continue;
1341 }
1342
1343 // Retract if the lead surrogate would stand alone at the end of the
1344 // window.
1345 if (HalfWindowSize() >= WindowRadius || // split pair
1346 p >= limit_ || // half-pair at end of source
1347 !unicode::IsTrailSurrogate(*p)) // no paired trail surrogate
1348 {
1349 p--;
1350 break;
1351 }
1352
1353 p++;
1354 }
1355
1356 return offset + HalfWindowSize();
1357 }
1358
1359 template <>
1360 size_t SourceUnits<Utf8Unit>::findWindowEnd(size_t offset) const {
1361 const Utf8Unit* const initial = codeUnitPtrAt(offset);
1362 const Utf8Unit* p = initial;
1363
1364 auto HalfWindowSize = [&initial, &p]() {
1365 return PointerRangeSize(initial, p);
1366 };
1367
1368 while (true) {
1369 MOZ_ASSERT(p <= limit_);
1370 MOZ_ASSERT(HalfWindowSize() <= WindowRadius);
1371 if (p >= limit_ || HalfWindowSize() >= WindowRadius) {
1372 break;
1373 }
1374
1375 // A non-encoding error might be followed by an encoding error within
1376 // |maxEnd|, so we must validate as we go to not include invalid UTF-8
1377 // in the computed window. What joy!
1378
1379 Utf8Unit lead = *p;
1380 if (mozilla::IsAscii(lead)) {
1381 if (IsSingleUnitLineTerminator(lead)) {
1382 break;
1383 }
1384
1385 p++;
1386 continue;
1387 }
1388
1389 PeekedCodePoint<Utf8Unit> peeked = PeekCodePoint(p, limit_);
1390 if (peeked.isNone()) {
1391 break; // encoding error
1392 }
1393
1394 char32_t c = peeked.codePoint();
1395 if (MOZ_UNLIKELY(c == unicode::LINE_SEPARATOR ||
1396 c == unicode::PARA_SEPARATOR)) {
1397 break;
1398 }
1399
1400 MOZ_ASSERT(!IsLineTerminator(c));
1401
1402 uint8_t len = peeked.lengthInUnits();
1403 if (HalfWindowSize() + len > WindowRadius) {
1404 break;
1405 }
1406
1407 p += len;
1408 }
1409
1410 MOZ_ASSERT(HalfWindowSize() <= WindowRadius);
1411 return offset + HalfWindowSize();
1412 }
1413
1414 template <typename Unit, class AnyCharsAccess>
1415 bool TokenStreamSpecific<Unit, AnyCharsAccess>::advance(size_t position) {
1416 const Unit* end = this->sourceUnits.codeUnitPtrAt(position);
1417 while (this->sourceUnits.addressOfNextCodeUnit() < end) {
1418 if (!getCodePoint()) {
1419 return false;
1420 }
1421 }
1422
1423 TokenStreamAnyChars& anyChars = anyCharsAccess();
1424 Token* cur = const_cast<Token*>(&anyChars.currentToken());
1425 cur->pos.begin = this->sourceUnits.offset();
1426 cur->pos.end = cur->pos.begin;
1427 #ifdef DEBUG
1428 cur->type = TokenKind::Limit;
1429 #endif
1430 MOZ_MAKE_MEM_UNDEFINED(&cur->type, sizeof(cur->type));
1431 anyChars.lookahead = 0;
1432 return true;
1433 }
1434
1435 template <typename Unit, class AnyCharsAccess>
1436 void TokenStreamSpecific<Unit, AnyCharsAccess>::seekTo(const Position& pos) {
1437 TokenStreamAnyChars& anyChars = anyCharsAccess();
1438
1439 this->sourceUnits.setAddressOfNextCodeUnit(pos.buf,
1440 /* allowPoisoned = */ true);
1441 anyChars.flags = pos.flags;
1442 anyChars.lineno = pos.lineno;
1443 anyChars.linebase = pos.linebase;
1444 anyChars.prevLinebase = pos.prevLinebase;
1445 anyChars.lookahead = pos.lookahead;
1446
1447 anyChars.tokens[anyChars.cursor()] = pos.currentToken;
1448 for (unsigned i = 0; i < anyChars.lookahead; i++) {
1449 anyChars.tokens[anyChars.aheadCursor(1 + i)] = pos.lookaheadTokens[i];
1450 }
1451 }
1452
1453 template <typename Unit, class AnyCharsAccess>
1454 bool TokenStreamSpecific<Unit, AnyCharsAccess>::seekTo(
1455 const Position& pos, const TokenStreamAnyChars& other) {
1456 if (!anyCharsAccess().srcCoords.fill(other.srcCoords)) {
1457 return false;
1458 }
1459
1460 seekTo(pos);
1461 return true;
1462 }
1463
1464 void TokenStreamAnyChars::computeErrorMetadataNoOffset(
1465 ErrorMetadata* err) const {
1466 err->isMuted = mutedErrors;
1467 err->filename = filename_;
1468 err->lineNumber = 0;
1469 err->columnNumber = JS::ColumnNumberOneOrigin();
1470
1471 MOZ_ASSERT(err->lineOfContext == nullptr);
1472 }
1473
1474 bool TokenStreamAnyChars::fillExceptingContext(ErrorMetadata* err,
1475 uint32_t offset) const {
1476 err->isMuted = mutedErrors;
1477
1478 // If this TokenStreamAnyChars doesn't have location information, try to
1479 // get it from the caller.
1480 if (!filename_) {
1481 JSContext* maybeCx = context()->maybeCurrentJSContext();
1482 if (maybeCx) {
1483 NonBuiltinFrameIter iter(maybeCx,
1484 FrameIter::FOLLOW_DEBUGGER_EVAL_PREV_LINK,
1485 maybeCx->realm()->principals());
1486 if (!iter.done() && iter.filename()) {
1487 err->filename = JS::ConstUTF8CharsZ(iter.filename());
1488 JS::TaggedColumnNumberOneOrigin columnNumber;
1489 err->lineNumber = iter.computeLine(&columnNumber);
1490 err->columnNumber =
1491 JS::ColumnNumberOneOrigin(columnNumber.oneOriginValue());
1492 return false;
1493 }
1494 }
1495 }
1496
1497 // Otherwise use this TokenStreamAnyChars's location information.
1498 err->filename = filename_;
1499 return true;
1500 }
1501
1502 template <>
1503 inline void SourceUnits<char16_t>::computeWindowOffsetAndLength(
1504 const char16_t* encodedWindow, size_t encodedTokenOffset,
1505 size_t* utf16TokenOffset, size_t encodedWindowLength,
1506 size_t* utf16WindowLength) const {
1507 MOZ_ASSERT_UNREACHABLE("shouldn't need to recompute for UTF-16");
1508 }
1509
1510 template <>
1511 inline void SourceUnits<Utf8Unit>::computeWindowOffsetAndLength(
1512 const Utf8Unit* encodedWindow, size_t encodedTokenOffset,
1513 size_t* utf16TokenOffset, size_t encodedWindowLength,
1514 size_t* utf16WindowLength) const {
1515 MOZ_ASSERT(encodedTokenOffset <= encodedWindowLength,
1516 "token offset must be within the window, and the two lambda "
1517 "calls below presume this ordering of values");
1518
1519 const Utf8Unit* const encodedWindowEnd = encodedWindow + encodedWindowLength;
1520
1521 size_t i = 0;
1522 auto ComputeUtf16Count = [&i, &encodedWindow](const Utf8Unit* limit) {
1523 while (encodedWindow < limit) {
1524 Utf8Unit lead = *encodedWindow++;
1525 if (MOZ_LIKELY(IsAscii(lead))) {
1526 // ASCII contributes a single UTF-16 code unit.
1527 i++;
1528 continue;
1529 }
1530
1531 Maybe<char32_t> cp = DecodeOneUtf8CodePoint(lead, &encodedWindow, limit);
1532 MOZ_ASSERT(cp.isSome(),
1533 "computed window should only contain valid UTF-8");
1534
1535 i += unicode::IsSupplementary(cp.value()) ? 2 : 1;
1536 }
1537
1538 return i;
1539 };
1540
1541 // Compute the token offset from |i == 0| and the initial |encodedWindow|.
1542 const Utf8Unit* token = encodedWindow + encodedTokenOffset;
1543 MOZ_ASSERT(token <= encodedWindowEnd);
1544 *utf16TokenOffset = ComputeUtf16Count(token);
1545
1546 // Compute the window length, picking up from |i| and |encodedWindow| that,
1547 // in general, were modified just above.
1548 *utf16WindowLength = ComputeUtf16Count(encodedWindowEnd);
1549 }
1550
1551 template <typename Unit>
1552 bool TokenStreamCharsBase<Unit>::addLineOfContext(ErrorMetadata* err,
1553 uint32_t offset) const {
1554 // Rename the variable to make meaning clearer: an offset into source units
1555 // in Unit encoding.
1556 size_t encodedOffset = offset;
1557
1558 // These are also offsets into source units in Unit encoding.
1559 size_t encodedWindowStart = sourceUnits.findWindowStart(encodedOffset);
1560 size_t encodedWindowEnd = sourceUnits.findWindowEnd(encodedOffset);
1561
1562 size_t encodedWindowLength = encodedWindowEnd - encodedWindowStart;
1563 MOZ_ASSERT(encodedWindowLength <= SourceUnits::WindowRadius * 2);
1564
1565 // Don't add a useless "line" of context when the window ends up empty
1566 // because of an invalid encoding at the start of a line.
1567 if (encodedWindowLength == 0) {
1568 MOZ_ASSERT(err->lineOfContext == nullptr,
1569 "ErrorMetadata::lineOfContext must be null so we don't "
1570 "have to set the lineLength/tokenOffset fields");
1571 return true;
1572 }
1573
1574 CharBuffer lineOfContext(fc);
1575
1576 const Unit* encodedWindow = sourceUnits.codeUnitPtrAt(encodedWindowStart);
1577 if (!FillCharBufferFromSourceNormalizingAsciiLineBreaks(
1578 lineOfContext, encodedWindow, encodedWindow + encodedWindowLength)) {
1579 return false;
1580 }
1581
1582 size_t utf16WindowLength = lineOfContext.length();
1583
1584 // The windowed string is null-terminated.
1585 if (!lineOfContext.append('\0')) {
1586 return false;
1587 }
1588
1589 err->lineOfContext.reset(lineOfContext.extractOrCopyRawBuffer());
1590 if (!err->lineOfContext) {
1591 return false;
1592 }
1593
1594 size_t encodedTokenOffset = encodedOffset - encodedWindowStart;
1595
1596 MOZ_ASSERT(encodedTokenOffset <= encodedWindowLength,
1597 "token offset must be inside the window");
1598
1599 // The length in UTF-8 code units of a code point is always greater than or
1600 // equal to the same code point's length in UTF-16 code points. ASCII code
1601 // points are 1 unit in either encoding. Code points in [U+0080, U+10000)
1602 // are 2-3 UTF-8 code units to 1 UTF-16 code unit. And code points in
1603 // [U+10000, U+10FFFF] are 4 UTF-8 code units to 2 UTF-16 code units.
1604 //
1605 // Therefore, if encoded window length equals the length in UTF-16 (this is
1606 // always the case for Unit=char16_t), the UTF-16 offsets are exactly the
1607 // encoded offsets. Otherwise we must convert offset/length from UTF-8 to
1608 // UTF-16.
1609 if constexpr (std::is_same_v<Unit, char16_t>) {
1610 MOZ_ASSERT(utf16WindowLength == encodedWindowLength,
1611 "UTF-16 to UTF-16 shouldn't change window length");
1612 err->tokenOffset = encodedTokenOffset;
1613 err->lineLength = encodedWindowLength;
1614 } else {
1615 static_assert(std::is_same_v<Unit, Utf8Unit>, "should only see UTF-8 here");
1616
1617 bool simple = utf16WindowLength == encodedWindowLength;
1618 #ifdef DEBUG
1619 auto isAscii = [](Unit u) { return IsAscii(u); };
1620 MOZ_ASSERT(std::all_of(encodedWindow, encodedWindow + encodedWindowLength,
1621 isAscii) == simple,
1622 "equal window lengths in UTF-8 should correspond only to "
1623 "wholly-ASCII text");
1624 #endif
1625 if (simple) {
1626 err->tokenOffset = encodedTokenOffset;
1627 err->lineLength = encodedWindowLength;
1628 } else {
1629 sourceUnits.computeWindowOffsetAndLength(
1630 encodedWindow, encodedTokenOffset, &err->tokenOffset,
1631 encodedWindowLength, &err->lineLength);
1632 }
1633 }
1634
1635 return true;
1636 }
1637
1638 template <typename Unit, class AnyCharsAccess>
1639 bool TokenStreamSpecific<Unit, AnyCharsAccess>::computeErrorMetadata(
1640 ErrorMetadata* err, const ErrorOffset& errorOffset) const {
1641 if (errorOffset.is<NoOffset>()) {
1642 anyCharsAccess().computeErrorMetadataNoOffset(err);
1643 return true;
1644 }
1645
1646 uint32_t offset;
1647 if (errorOffset.is<uint32_t>()) {
1648 offset = errorOffset.as<uint32_t>();
1649 } else {
1650 offset = this->sourceUnits.offset();
1651 }
1652
1653 // This function's return value isn't a success/failure indication: it
1654 // returns true if this TokenStream can be used to provide a line of
1655 // context.
1656 if (fillExceptingContext(err, offset)) {
1657 // Add a line of context from this TokenStream to help with debugging.
1658 return internalComputeLineOfContext(err, offset);
1659 }
1660
1661 // We can't fill in any more here.
1662 return true;
1663 }
1664
1665 template <typename Unit, class AnyCharsAccess>
1666 void TokenStreamSpecific<Unit, AnyCharsAccess>::reportIllegalCharacter(
1667 int32_t cp) {
1668 UniqueChars display = JS_smprintf("U+%04X", cp);
1669 if (!display) {
1670 ReportOutOfMemory(anyCharsAccess().fc);
1671 return;
1672 }
1673 error(JSMSG_ILLEGAL_CHARACTER, display.get());
1674 }
1675
1676 // We have encountered a '\': check for a Unicode escape sequence after it.
1677 // Return the length of the escape sequence and the encoded code point (by
1678 // value) if we found a Unicode escape sequence, and skip all code units
1679 // involed. Otherwise, return 0 and don't advance along the buffer.
1680 template <typename Unit, class AnyCharsAccess>
1681 uint32_t GeneralTokenStreamChars<Unit, AnyCharsAccess>::matchUnicodeEscape(
1682 char32_t* codePoint) {
1683 MOZ_ASSERT(this->sourceUnits.previousCodeUnit() == Unit('\\'));
1684
1685 int32_t unit = getCodeUnit();
1686 if (unit != 'u') {
1687 // NOTE: |unit| may be EOF here.
1688 ungetCodeUnit(unit);
1689 MOZ_ASSERT(this->sourceUnits.previousCodeUnit() == Unit('\\'));
1690 return 0;
1691 }
1692
1693 char16_t v;
1694 unit = getCodeUnit();
1695 if (IsAsciiHexDigit(unit) && this->sourceUnits.matchHexDigits(3, &v)) {
1696 *codePoint = (AsciiAlphanumericToNumber(unit) << 12) | v;
1697 return 5;
1698 }
1699
1700 if (unit == '{') {
1701 return matchExtendedUnicodeEscape(codePoint);
1702 }
1703
1704 // NOTE: |unit| may be EOF here, so this ungets either one or two units.
1705 ungetCodeUnit(unit);
1706 ungetCodeUnit('u');
1707 MOZ_ASSERT(this->sourceUnits.previousCodeUnit() == Unit('\\'));
1708 return 0;
1709 }
1710
1711 template <typename Unit, class AnyCharsAccess>
1712 uint32_t
1713 GeneralTokenStreamChars<Unit, AnyCharsAccess>::matchExtendedUnicodeEscape(
1714 char32_t* codePoint) {
1715 MOZ_ASSERT(this->sourceUnits.previousCodeUnit() == Unit('{'));
1716
1717 int32_t unit = getCodeUnit();
1718
1719 // Skip leading zeroes.
1720 uint32_t leadingZeroes = 0;
1721 while (unit == '0') {
1722 leadingZeroes++;
1723 unit = getCodeUnit();
1724 }
1725
1726 size_t i = 0;
1727 uint32_t code = 0;
1728 while (IsAsciiHexDigit(unit) && i < 6) {
1729 code = (code << 4) | AsciiAlphanumericToNumber(unit);
1730 unit = getCodeUnit();
1731 i++;
1732 }
1733
1734 uint32_t gotten =
1735 2 + // 'u{'
1736 leadingZeroes + i + // significant hexdigits
1737 (unit != EOF); // subtract a get if it didn't contribute to length
1738
1739 if (unit == '}' && (leadingZeroes > 0 || i > 0) &&
1740 code <= unicode::NonBMPMax) {
1741 *codePoint = code;
1742 return gotten;
1743 }
1744
1745 this->sourceUnits.unskipCodeUnits(gotten);
1746 MOZ_ASSERT(this->sourceUnits.previousCodeUnit() == Unit('\\'));
1747 return 0;
1748 }
1749
1750 template <typename Unit, class AnyCharsAccess>
1751 uint32_t
1752 GeneralTokenStreamChars<Unit, AnyCharsAccess>::matchUnicodeEscapeIdStart(
1753 char32_t* codePoint) {
1754 uint32_t length = matchUnicodeEscape(codePoint);
1755 if (MOZ_LIKELY(length > 0)) {
1756 if (MOZ_LIKELY(unicode::IsIdentifierStart(*codePoint))) {
1757 return length;
1758 }
1759
1760 this->sourceUnits.unskipCodeUnits(length);
1761 }
1762
1763 MOZ_ASSERT(this->sourceUnits.previousCodeUnit() == Unit('\\'));
1764 return 0;
1765 }
1766
1767 template <typename Unit, class AnyCharsAccess>
1768 bool GeneralTokenStreamChars<Unit, AnyCharsAccess>::matchUnicodeEscapeIdent(
1769 char32_t* codePoint) {
1770 uint32_t length = matchUnicodeEscape(codePoint);
1771 if (MOZ_LIKELY(length > 0)) {
1772 if (MOZ_LIKELY(unicode::IsIdentifierPart(*codePoint))) {
1773 return true;
1774 }
1775
1776 this->sourceUnits.unskipCodeUnits(length);
1777 }
1778
1779 MOZ_ASSERT(this->sourceUnits.previousCodeUnit() == Unit('\\'));
1780 return false;
1781 }
1782
1783 template <typename Unit, class AnyCharsAccess>
1784 [[nodiscard]] bool
1785 TokenStreamSpecific<Unit, AnyCharsAccess>::matchIdentifierStart(
1786 IdentifierEscapes* sawEscape) {
1787 int32_t unit = getCodeUnit();
1788 if (unit == EOF) {
1789 error(JSMSG_MISSING_PRIVATE_NAME);
1790 return false;
1791 }
1792
1793 if (MOZ_LIKELY(isAsciiCodePoint(unit))) {
1794 if (unicode::IsIdentifierStart(char16_t(unit))) {
1795 *sawEscape = IdentifierEscapes::None;
1796 return true;
1797 }
1798
1799 if (unit == '\\') {
1800 char32_t codePoint;
1801 uint32_t escapeLength = matchUnicodeEscapeIdStart(&codePoint);
1802 if (escapeLength != 0) {
1803 *sawEscape = IdentifierEscapes::SawUnicodeEscape;
1804 return true;
1805 }
1806
1807 // We could point "into" a mistyped escape, e.g. for "\u{41H}" we
1808 // could point at the 'H'. But we don't do that now, so the code
1809 // unit after the '\' isn't necessarily bad, so just point at the
1810 // start of the actually-invalid escape.
1811 ungetCodeUnit('\\');
1812 error(JSMSG_BAD_ESCAPE);
1813 return false;
1814 }
1815 }
1816
1817 // Unget the lead code unit before peeking at the full code point.
1818 ungetCodeUnit(unit);
1819
1820 PeekedCodePoint<Unit> peeked = this->sourceUnits.peekCodePoint();
1821 if (!peeked.isNone() && unicode::IsIdentifierStart(peeked.codePoint())) {
1822 this->sourceUnits.consumeKnownCodePoint(peeked);
1823
1824 *sawEscape = IdentifierEscapes::None;
1825 return true;
1826 }
1827
1828 error(JSMSG_MISSING_PRIVATE_NAME);
1829 return false;
1830 }
1831
1832 template <typename Unit, class AnyCharsAccess>
1833 bool TokenStreamSpecific<Unit, AnyCharsAccess>::getDirectives(
1834 bool isMultiline, bool shouldWarnDeprecated) {
1835 // Match directive comments used in debugging, such as "//# sourceURL" and
1836 // "//# sourceMappingURL". Use of "//@" instead of "//#" is deprecated.
1837 //
1838 // To avoid a crashing bug in IE, several JavaScript transpilers wrap single
1839 // line comments containing a source mapping URL inside a multiline
1840 // comment. To avoid potentially expensive lookahead and backtracking, we
1841 // only check for this case if we encounter a '#' code unit.
1842
1843 bool res = getDisplayURL(isMultiline, shouldWarnDeprecated) &&
1844 getSourceMappingURL(isMultiline, shouldWarnDeprecated);
1845 if (!res) {
1846 badToken();
1847 }
1848
1849 return res;
1850 }
1851
1852 [[nodiscard]] bool TokenStreamCharsShared::copyCharBufferTo(
1853 UniquePtr<char16_t[], JS::FreePolicy>* destination) {
1854 size_t length = charBuffer.length();
1855
1856 *destination = fc->getAllocator()->make_pod_array<char16_t>(length + 1);
1857 if (!*destination) {
1858 return false;
1859 }
1860
1861 std::copy(charBuffer.begin(), charBuffer.end(), destination->get());
1862 (*destination)[length] = '\0';
1863 return true;
1864 }
1865
1866 template <typename Unit, class AnyCharsAccess>
1867 [[nodiscard]] bool TokenStreamSpecific<Unit, AnyCharsAccess>::getDirective(
1868 bool isMultiline, bool shouldWarnDeprecated, const char* directive,
1869 uint8_t directiveLength, const char* errorMsgPragma,
1870 UniquePtr<char16_t[], JS::FreePolicy>* destination) {
1871 // Stop if we don't find |directive|. (Note that |directive| must be
1872 // ASCII, so there are no tricky encoding issues to consider in matching
1873 // UTF-8/16-agnostically.)
1874 if (!this->sourceUnits.matchCodeUnits(directive, directiveLength)) {
1875 return true;
1876 }
1877
1878 if (shouldWarnDeprecated) {
1879 if (!warning(JSMSG_DEPRECATED_PRAGMA, errorMsgPragma)) {
1880 return false;
1881 }
1882 }
1883
1884 this->charBuffer.clear();
1885
1886 do {
1887 int32_t unit = peekCodeUnit();
1888 if (unit == EOF) {
1889 break;
1890 }
1891
1892 if (MOZ_LIKELY(isAsciiCodePoint(unit))) {
1893 if (unicode::IsSpace(AssertedCast<Latin1Char>(unit))) {
1894 break;
1895 }
1896
1897 consumeKnownCodeUnit(unit);
1898
1899 // Debugging directives can occur in both single- and multi-line
1900 // comments. If we're currently inside a multi-line comment, we
1901 // also must recognize multi-line comment terminators.
1902 if (isMultiline && unit == '*' && peekCodeUnit() == '/') {
1903 ungetCodeUnit('*');
1904 break;
1905 }
1906
1907 if (!this->charBuffer.append(unit)) {
1908 return false;
1909 }
1910
1911 continue;
1912 }
1913
1914 // This ignores encoding errors: subsequent caller-side code to
1915 // handle the remaining source text in the comment will do so.
1916 PeekedCodePoint<Unit> peeked = this->sourceUnits.peekCodePoint();
1917 if (peeked.isNone() || unicode::IsSpace(peeked.codePoint())) {
1918 break;
1919 }
1920
1921 MOZ_ASSERT(!IsLineTerminator(peeked.codePoint()),
1922 "!IsSpace must imply !IsLineTerminator or else we'll fail to "
1923 "maintain line-info/flags for EOL");
1924 this->sourceUnits.consumeKnownCodePoint(peeked);
1925
1926 if (!AppendCodePointToCharBuffer(this->charBuffer, peeked.codePoint())) {
1927 return false;
1928 }
1929 } while (true);
1930
1931 if (this->charBuffer.empty()) {
1932 // The directive's URL was missing, but comments can contain anything,
1933 // so it isn't an error.
1934 return true;
1935 }
1936
1937 return copyCharBufferTo(destination);
1938 }
1939
1940 template <typename Unit, class AnyCharsAccess>
1941 bool TokenStreamSpecific<Unit, AnyCharsAccess>::getDisplayURL(
1942 bool isMultiline, bool shouldWarnDeprecated) {
1943 // Match comments of the form "//# sourceURL=<url>" or
1944 // "/\* //# sourceURL=<url> *\/"
1945 //
1946 // Note that while these are labeled "sourceURL" in the source text,
1947 // internally we refer to it as a "displayURL" to distinguish what the
1948 // developer would like to refer to the source as from the source's actual
1949 // URL.
1950
1951 static constexpr char sourceURLDirective[] = " sourceURL=";
1952 constexpr uint8_t sourceURLDirectiveLength = js_strlen(sourceURLDirective);
1953 return getDirective(isMultiline, shouldWarnDeprecated, sourceURLDirective,
1954 sourceURLDirectiveLength, "sourceURL",
1955 &anyCharsAccess().displayURL_);
1956 }
1957
1958 template <typename Unit, class AnyCharsAccess>
1959 bool TokenStreamSpecific<Unit, AnyCharsAccess>::getSourceMappingURL(
1960 bool isMultiline, bool shouldWarnDeprecated) {
1961 // Match comments of the form "//# sourceMappingURL=<url>" or
1962 // "/\* //# sourceMappingURL=<url> *\/"
1963
1964 static constexpr char sourceMappingURLDirective[] = " sourceMappingURL=";
1965 constexpr uint8_t sourceMappingURLDirectiveLength =
1966 js_strlen(sourceMappingURLDirective);
1967 return getDirective(isMultiline, shouldWarnDeprecated,
1968 sourceMappingURLDirective,
1969 sourceMappingURLDirectiveLength, "sourceMappingURL",
1970 &anyCharsAccess().sourceMapURL_);
1971 }
1972
1973 template <typename Unit, class AnyCharsAccess>
1974 MOZ_ALWAYS_INLINE Token*
1975 GeneralTokenStreamChars<Unit, AnyCharsAccess>::newTokenInternal(
1976 TokenKind kind, TokenStart start, TokenKind* out) {
1977 MOZ_ASSERT(kind < TokenKind::Limit);
1978 MOZ_ASSERT(kind != TokenKind::Eol,
1979 "TokenKind::Eol should never be used in an actual Token, only "
1980 "returned by peekTokenSameLine()");
1981
1982 TokenStreamAnyChars& anyChars = anyCharsAccess();
1983 anyChars.flags.isDirtyLine = true;
1984
1985 Token* token = anyChars.allocateToken();
1986
1987 *out = token->type = kind;
1988 token->pos = TokenPos(start.offset(), this->sourceUnits.offset());
1989 MOZ_ASSERT(token->pos.begin <= token->pos.end);
1990
1991 // NOTE: |token->modifier| is set in |newToken()| so that optimized,
1992 // non-debug code won't do any work to pass a modifier-argument that will
1993 // never be used.
1994
1995 return token;
1996 }
1997
1998 template <typename Unit, class AnyCharsAccess>
1999 MOZ_COLD bool GeneralTokenStreamChars<Unit, AnyCharsAccess>::badToken() {
2000 // We didn't get a token, so don't set |flags.isDirtyLine|.
2001 anyCharsAccess().flags.hadError = true;
2002
2003 // Poisoning sourceUnits on error establishes an invariant: once an
2004 // erroneous token has been seen, sourceUnits will not be consulted again.
2005 // This is true because the parser will deal with the illegal token by
2006 // aborting parsing immediately.
2007 this->sourceUnits.poisonInDebug();
2008
2009 return false;
2010 };
2011
2012 bool AppendCodePointToCharBuffer(CharBuffer& charBuffer, char32_t codePoint) {
2013 MOZ_ASSERT(codePoint <= unicode::NonBMPMax,
2014 "should only be processing code points validly decoded from UTF-8 "
2015 "or WTF-16 source text (surrogate code points permitted)");
2016
2017 char16_t units[2];
2018 unsigned numUnits = 0;
2019 unicode::UTF16Encode(codePoint, units, &numUnits);
2020
2021 MOZ_ASSERT(numUnits == 1 || numUnits == 2,
2022 "UTF-16 code points are only encoded in one or two units");
2023
2024 if (!charBuffer.append(units[0])) {
2025 return false;
2026 }
2027
2028 if (numUnits == 1) {
2029 return true;
2030 }
2031
2032 return charBuffer.append(units[1]);
2033 }
2034
2035 template <typename Unit, class AnyCharsAccess>
2036 bool TokenStreamSpecific<Unit, AnyCharsAccess>::putIdentInCharBuffer(
2037 const Unit* identStart) {
2038 const Unit* const originalAddress = this->sourceUnits.addressOfNextCodeUnit();
2039 this->sourceUnits.setAddressOfNextCodeUnit(identStart);
2040
2041 auto restoreNextRawCharAddress = MakeScopeExit([this, originalAddress]() {
2042 this->sourceUnits.setAddressOfNextCodeUnit(originalAddress);
2043 });
2044
2045 this->charBuffer.clear();
2046 do {
2047 int32_t unit = getCodeUnit();
2048 if (unit == EOF) {
2049 break;
2050 }
2051
2052 char32_t codePoint;
2053 if (MOZ_LIKELY(isAsciiCodePoint(unit))) {
2054 if (unicode::IsIdentifierPart(char16_t(unit)) || unit == '#') {
2055 if (!this->charBuffer.append(unit)) {
2056 return false;
2057 }
2058
2059 continue;
2060 }
2061
2062 if (unit != '\\' || !matchUnicodeEscapeIdent(&codePoint)) {
2063 break;
2064 }
2065 } else {
2066 // |restoreNextRawCharAddress| undoes all gets, and this function
2067 // doesn't update line/column info.
2068 char32_t cp;
2069 if (!getNonAsciiCodePointDontNormalize(toUnit(unit), &cp)) {
2070 return false;
2071 }
2072
2073 codePoint = cp;
2074 if (!unicode::IsIdentifierPart(codePoint)) {
2075 break;
2076 }
2077 }
2078
2079 if (!AppendCodePointToCharBuffer(this->charBuffer, codePoint)) {
2080 return false;
2081 }
2082 } while (true);
2083
2084 return true;
2085 }
2086
2087 template <typename Unit, class AnyCharsAccess>
2088 [[nodiscard]] bool TokenStreamSpecific<Unit, AnyCharsAccess>::identifierName(
2089 TokenStart start, const Unit* identStart, IdentifierEscapes escaping,
2090 Modifier modifier, NameVisibility visibility, TokenKind* out) {
2091 // Run the bad-token code for every path out of this function except the
2092 // two success-cases.
2093 auto noteBadToken = MakeScopeExit([this]() { this->badToken(); });
2094
2095 // We've already consumed an initial code point in the identifer, to *know*
2096 // that this is an identifier. So no need to worry about not consuming any
2097 // code points in the loop below.
2098 int32_t unit;
2099 while (true) {
2100 unit = peekCodeUnit();
2101 if (unit == EOF) {
2102 break;
2103 }
2104
2105 if (MOZ_LIKELY(isAsciiCodePoint(unit))) {
2106 consumeKnownCodeUnit(unit);
2107
2108 if (MOZ_UNLIKELY(
2109 !unicode::IsIdentifierPart(static_cast<char16_t>(unit)))) {
2110 // Handle a Unicode escape -- otherwise it's not part of the
2111 // identifier.
2112 char32_t codePoint;
2113 if (unit != '\\' || !matchUnicodeEscapeIdent(&codePoint)) {
2114 ungetCodeUnit(unit);
2115 break;
2116 }
2117
2118 escaping = IdentifierEscapes::SawUnicodeEscape;
2119 }
2120 } else {
2121 // This ignores encoding errors: subsequent caller-side code to
2122 // handle source text after the IdentifierName will do so.
2123 PeekedCodePoint<Unit> peeked = this->sourceUnits.peekCodePoint();
2124 if (peeked.isNone() || !unicode::IsIdentifierPart(peeked.codePoint())) {
2125 break;
2126 }
2127
2128 MOZ_ASSERT(!IsLineTerminator(peeked.codePoint()),
2129 "IdentifierPart must guarantee !IsLineTerminator or "
2130 "else we'll fail to maintain line-info/flags for EOL");
2131
2132 this->sourceUnits.consumeKnownCodePoint(peeked);
2133 }
2134 }
2135
2136 TaggedParserAtomIndex atom;
2137 if (MOZ_UNLIKELY(escaping == IdentifierEscapes::SawUnicodeEscape)) {
2138 // Identifiers containing Unicode escapes have to be converted into
2139 // tokenbuf before atomizing.
2140 if (!putIdentInCharBuffer(identStart)) {
2141 return false;
2142 }
2143
2144 atom = drainCharBufferIntoAtom();
2145 } else {
2146 // Escape-free identifiers can be created directly from sourceUnits.
2147 const Unit* chars = identStart;
2148 size_t length = this->sourceUnits.addressOfNextCodeUnit() - identStart;
2149
2150 // Private identifiers start with a '#', and so cannot be reserved words.
2151 if (visibility == NameVisibility::Public) {
2152 // Represent reserved words lacking escapes as reserved word tokens.
2153 if (const ReservedWordInfo* rw = FindReservedWord(chars, length)) {
2154 noteBadToken.release();
2155 newSimpleToken(rw->tokentype, start, modifier, out);
2156 return true;
2157 }
2158 }
2159
2160 atom = atomizeSourceChars(Span(chars, length));
2161 }
2162 if (!atom) {
2163 return false;
2164 }
2165
2166 noteBadToken.release();
2167 if (visibility == NameVisibility::Private) {
2168 newPrivateNameToken(atom, start, modifier, out);
2169 return true;
2170 }
2171 newNameToken(atom, start, modifier, out);
2172 return true;
2173 }
2174
2175 enum FirstCharKind {
2176 // A char16_t has the 'OneChar' kind if it, by itself, constitutes a valid
2177 // token that cannot also be a prefix of a longer token. E.g. ';' has the
2178 // OneChar kind, but '+' does not, because '++' and '+=' are valid longer
2179 // tokens
2180 // that begin with '+'.
2181 //
2182 // The few token kinds satisfying these properties cover roughly 35--45%
2183 // of the tokens seen in practice.
2184 //
2185 // We represent the 'OneChar' kind with any positive value less than
2186 // TokenKind::Limit. This representation lets us associate
2187 // each one-char token char16_t with a TokenKind and thus avoid
2188 // a subsequent char16_t-to-TokenKind conversion.
2189 OneChar_Min = 0,
2190 OneChar_Max = size_t(TokenKind::Limit) - 1,
2191
2192 Space = size_t(TokenKind::Limit),
2193 Ident,
2194 Dec,
2195 String,
2196 EOL,
2197 ZeroDigit,
2198 Other,
2199
2200 LastCharKind = Other
2201 };
2202
2203 // OneChar: 40, 41, 44, 58, 59, 91, 93, 123, 125, 126:
2204 // '(', ')', ',', ':', ';', '[', ']', '{', '}', '~'
2205 // Ident: 36, 65..90, 95, 97..122: '$', 'A'..'Z', '_', 'a'..'z'
2206 // Dot: 46: '.'
2207 // Equals: 61: '='
2208 // String: 34, 39, 96: '"', '\'', '`'
2209 // Dec: 49..57: '1'..'9'
2210 // Plus: 43: '+'
2211 // ZeroDigit: 48: '0'
2212 // Space: 9, 11, 12, 32: '\t', '\v', '\f', ' '
2213 // EOL: 10, 13: '\n', '\r'
2214 //
2215 #define T_COMMA size_t(TokenKind::Comma)
2216 #define T_COLON size_t(TokenKind::Colon)
2217 #define T_BITNOT size_t(TokenKind::BitNot)
2218 #define T_LP size_t(TokenKind::LeftParen)
2219 #define T_RP size_t(TokenKind::RightParen)
2220 #define T_SEMI size_t(TokenKind::Semi)
2221 #define T_LB size_t(TokenKind::LeftBracket)
2222 #define T_RB size_t(TokenKind::RightBracket)
2223 #define T_LC size_t(TokenKind::LeftCurly)
2224 #define T_RC size_t(TokenKind::RightCurly)
2225 #define _______ Other
2226 static const uint8_t firstCharKinds[] = {
2227 // clang-format off
2228 /* 0 1 2 3 4 5 6 7 8 9 */
2229 /* 0+ */ _______, _______, _______, _______, _______, _______, _______, _______, _______, Space,
2230 /* 10+ */ EOL, Space, Space, EOL, _______, _______, _______, _______, _______, _______,
2231 /* 20+ */ _______, _______, _______, _______, _______, _______, _______, _______, _______, _______,
2232 /* 30+ */ _______, _______, Space, _______, String, _______, Ident, _______, _______, String,
2233 /* 40+ */ T_LP, T_RP, _______, _______, T_COMMA, _______, _______, _______,ZeroDigit, Dec,
2234 /* 50+ */ Dec, Dec, Dec, Dec, Dec, Dec, Dec, Dec, T_COLON, T_SEMI,
2235 /* 60+ */ _______, _______, _______, _______, _______, Ident, Ident, Ident, Ident, Ident,
2236 /* 70+ */ Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident,
2237 /* 80+ */ Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident,
2238 /* 90+ */ Ident, T_LB, _______, T_RB, _______, Ident, String, Ident, Ident, Ident,
2239 /* 100+ */ Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident,
2240 /* 110+ */ Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident, Ident,
2241 /* 120+ */ Ident, Ident, Ident, T_LC, _______, T_RC,T_BITNOT, _______
2242 // clang-format on
2243 };
2244 #undef T_COMMA
2245 #undef T_COLON
2246 #undef T_BITNOT
2247 #undef T_LP
2248 #undef T_RP
2249 #undef T_SEMI
2250 #undef T_LB
2251 #undef T_RB
2252 #undef T_LC
2253 #undef T_RC
2254 #undef _______
2255
2256 static_assert(LastCharKind < (1 << (sizeof(firstCharKinds[0]) * 8)),
2257 "Elements of firstCharKinds[] are too small");
2258
2259 template <>
2260 void SourceUnits<char16_t>::consumeRestOfSingleLineComment() {
2261 while (MOZ_LIKELY(!atEnd())) {
2262 char16_t unit = peekCodeUnit();
2263 if (IsLineTerminator(unit)) {
2264 return;
2265 }
2266
2267 consumeKnownCodeUnit(unit);
2268 }
2269 }
2270
2271 template <>
2272 void SourceUnits<Utf8Unit>::consumeRestOfSingleLineComment() {
2273 while (MOZ_LIKELY(!atEnd())) {
2274 const Utf8Unit unit = peekCodeUnit();
2275 if (IsSingleUnitLineTerminator(unit)) {
2276 return;
2277 }
2278
2279 if (MOZ_LIKELY(IsAscii(unit))) {
2280 consumeKnownCodeUnit(unit);
2281 continue;
2282 }
2283
2284 PeekedCodePoint<Utf8Unit> peeked = peekCodePoint();
2285 if (peeked.isNone()) {
2286 return;
2287 }
2288
2289 char32_t c = peeked.codePoint();
2290 if (MOZ_UNLIKELY(c == unicode::LINE_SEPARATOR ||
2291 c == unicode::PARA_SEPARATOR)) {
2292 return;
2293 }
2294
2295 consumeKnownCodePoint(peeked);
2296 }
2297 }
2298
2299 template <typename Unit, class AnyCharsAccess>
2300 [[nodiscard]] MOZ_ALWAYS_INLINE bool
2301 TokenStreamSpecific<Unit, AnyCharsAccess>::matchInteger(
2302 IsIntegerUnit isIntegerUnit, int32_t* nextUnit) {
2303 int32_t unit = getCodeUnit();
2304 if (!isIntegerUnit(unit)) {
2305 *nextUnit = unit;
2306 return true;
2307 }
2308 return matchIntegerAfterFirstDigit(isIntegerUnit, nextUnit);
2309 }
2310
2311 template <typename Unit, class AnyCharsAccess>
2312 [[nodiscard]] MOZ_ALWAYS_INLINE bool
2313 TokenStreamSpecific<Unit, AnyCharsAccess>::matchIntegerAfterFirstDigit(
2314 IsIntegerUnit isIntegerUnit, int32_t* nextUnit) {
2315 int32_t unit;
2316 while (true) {
2317 unit = getCodeUnit();
2318 if (isIntegerUnit(unit)) {
2319 continue;
2320 }
2321 if (unit != '_') {
2322 break;
2323 }
2324 unit = getCodeUnit();
2325 if (!isIntegerUnit(unit)) {
2326 if (unit == '_') {
2327 ungetCodeUnit(unit);
2328 error(JSMSG_NUMBER_MULTIPLE_ADJACENT_UNDERSCORES);
2329 } else {
2330 ungetCodeUnit(unit);
2331 ungetCodeUnit('_');
2332 error(JSMSG_NUMBER_END_WITH_UNDERSCORE);
2333 }
2334 return false;
2335 }
2336 }
2337
2338 *nextUnit = unit;
2339 return true;
2340 }
2341
2342 template <typename Unit, class AnyCharsAccess>
2343 [[nodiscard]] bool TokenStreamSpecific<Unit, AnyCharsAccess>::decimalNumber(
2344 int32_t unit, TokenStart start, const Unit* numStart, Modifier modifier,
2345 TokenKind* out) {
2346 // Run the bad-token code for every path out of this function except the
2347 // one success-case.
2348 auto noteBadToken = MakeScopeExit([this]() { this->badToken(); });
2349
2350 // Consume integral component digits.
2351 if (IsAsciiDigit(unit)) {
2352 if (!matchIntegerAfterFirstDigit(IsAsciiDigit, &unit)) {
2353 return false;
2354 }
2355 }
2356
2357 // Numbers contain no escapes, so we can read directly from |sourceUnits|.
2358 double dval;
2359 bool isBigInt = false;
2360 DecimalPoint decimalPoint = NoDecimal;
2361 if (unit != '.' && unit != 'e' && unit != 'E' && unit != 'n') {
2362 // NOTE: |unit| may be EOF here.
2363 ungetCodeUnit(unit);
2364
2365 // Most numbers are pure decimal integers without fractional component
2366 // or exponential notation. Handle that with optimized code.
2367 if (!GetDecimalInteger(numStart, this->sourceUnits.addressOfNextCodeUnit(),
2368 &dval)) {
2369 ReportOutOfMemory(this->fc);
2370 return false;
2371 }
2372 } else if (unit == 'n') {
2373 isBigInt = true;
2374 unit = peekCodeUnit();
2375 } else {
2376 // Consume any decimal dot and fractional component.
2377 if (unit == '.') {
2378 decimalPoint = HasDecimal;
2379 if (!matchInteger(IsAsciiDigit, &unit)) {
2380 return false;
2381 }
2382 }
2383
2384 // Consume any exponential notation.
2385 if (unit == 'e' || unit == 'E') {
2386 unit = getCodeUnit();
2387 if (unit == '+' || unit == '-') {
2388 unit = getCodeUnit();
2389 }
2390
2391 // Exponential notation must contain at least one digit.
2392 if (!IsAsciiDigit(unit)) {
2393 ungetCodeUnit(unit);
2394 error(JSMSG_MISSING_EXPONENT);
2395 return false;
2396 }
2397
2398 // Consume exponential digits.
2399 if (!matchIntegerAfterFirstDigit(IsAsciiDigit, &unit)) {
2400 return false;
2401 }
2402 }
2403
2404 ungetCodeUnit(unit);
2405
2406 if (!GetDecimal(numStart, this->sourceUnits.addressOfNextCodeUnit(),
2407 &dval)) {
2408 ReportOutOfMemory(this->fc);
2409 return false;
2410 }
2411 }
2412
2413 // Number followed by IdentifierStart is an error. (This is the only place
2414 // in ECMAScript where token boundary is inadequate to properly separate
2415 // two tokens, necessitating this unaesthetic lookahead.)
2416 if (unit != EOF) {
2417 if (MOZ_LIKELY(isAsciiCodePoint(unit))) {
2418 if (unicode::IsIdentifierStart(char16_t(unit))) {
2419 error(JSMSG_IDSTART_AFTER_NUMBER);
2420 return false;
2421 }
2422 } else {
2423 // This ignores encoding errors: subsequent caller-side code to
2424 // handle source text after the number will do so.
2425 PeekedCodePoint<Unit> peeked = this->sourceUnits.peekCodePoint();
2426 if (!peeked.isNone() && unicode::IsIdentifierStart(peeked.codePoint())) {
2427 error(JSMSG_IDSTART_AFTER_NUMBER);
2428 return false;
2429 }
2430 }
2431 }
2432
2433 noteBadToken.release();
2434
2435 if (isBigInt) {
2436 return bigIntLiteral(start, modifier, out);
2437 }
2438
2439 newNumberToken(dval, decimalPoint, start, modifier, out);
2440 return true;
2441 }
2442
2443 template <typename Unit, class AnyCharsAccess>
2444 [[nodiscard]] bool TokenStreamSpecific<Unit, AnyCharsAccess>::regexpLiteral(
2445 TokenStart start, TokenKind* out) {
2446 MOZ_ASSERT(this->sourceUnits.previousCodeUnit() == Unit('/'));
2447 this->charBuffer.clear();
2448
2449 auto ProcessNonAsciiCodePoint = [this](int32_t lead) {
2450 MOZ_ASSERT(lead != EOF);
2451 MOZ_ASSERT(!this->isAsciiCodePoint(lead));
2452
2453 char32_t codePoint;
2454 if (!this->getNonAsciiCodePointDontNormalize(this->toUnit(lead),
2455 &codePoint)) {
2456 return false;
2457 }
2458
2459 if (MOZ_UNLIKELY(codePoint == unicode::LINE_SEPARATOR ||
2460 codePoint == unicode::PARA_SEPARATOR)) {
2461 this->sourceUnits.ungetLineOrParagraphSeparator();
2462 this->error(JSMSG_UNTERMINATED_REGEXP);
2463 return false;
2464 }
2465
2466 return AppendCodePointToCharBuffer(this->charBuffer, codePoint);
2467 };
2468
2469 auto ReportUnterminatedRegExp = [this](int32_t unit) {
2470 this->ungetCodeUnit(unit);
2471 this->error(JSMSG_UNTERMINATED_REGEXP);
2472 };
2473
2474 bool inCharClass = false;
2475 do {
2476 int32_t unit = getCodeUnit();
2477 if (unit == EOF) {
2478 ReportUnterminatedRegExp(unit);
2479 return badToken();
2480 }
2481
2482 if (MOZ_UNLIKELY(!isAsciiCodePoint(unit))) {
2483 if (!ProcessNonAsciiCodePoint(unit)) {
2484 return badToken();
2485 }
2486
2487 continue;
2488 }
2489
2490 if (unit == '\\') {
2491 if (!this->charBuffer.append(unit)) {
2492 return badToken();
2493 }
2494
2495 unit = getCodeUnit();
2496 if (unit == EOF) {
2497 ReportUnterminatedRegExp(unit);
2498 return badToken();
2499 }
2500
2501 // Fallthrough only handles ASCII code points, so
2502 // deal with non-ASCII and skip everything else.
2503 if (MOZ_UNLIKELY(!isAsciiCodePoint(unit))) {
2504 if (!ProcessNonAsciiCodePoint(unit)) {
2505 return badToken();
2506 }
2507
2508 continue;
2509 }
2510 } else if (unit == '[') {
2511 inCharClass = true;
2512 } else if (unit == ']') {
2513 inCharClass = false;
2514 } else if (unit == '/' && !inCharClass) {
2515 // For IE compat, allow unescaped / in char classes.
2516 break;
2517 }
2518
2519 // NOTE: Non-ASCII LineTerminators were handled by
2520 // ProcessNonAsciiCodePoint calls above.
2521 if (unit == '\r' || unit == '\n') {
2522 ReportUnterminatedRegExp(unit);
2523 return badToken();
2524 }
2525
2526 MOZ_ASSERT(!IsLineTerminator(AssertedCast<char32_t>(unit)));
2527 if (!this->charBuffer.append(unit)) {
2528 return badToken();
2529 }
2530 } while (true);
2531
2532 int32_t unit;
2533 RegExpFlags reflags = RegExpFlag::NoFlags;
2534 while (true) {
2535 uint8_t flag;
2536 unit = getCodeUnit();
2537 if (unit == 'd') {
2538 flag = RegExpFlag::HasIndices;
2539 } else if (unit == 'g') {
2540 flag = RegExpFlag::Global;
2541 } else if (unit == 'i') {
2542 flag = RegExpFlag::IgnoreCase;
2543 } else if (unit == 'm') {
2544 flag = RegExpFlag::Multiline;
2545 } else if (unit == 's') {
2546 flag = RegExpFlag::DotAll;
2547 } else if (unit == 'u') {
2548 flag = RegExpFlag::Unicode;
2549 } else if (unit == 'v') {
2550 flag = RegExpFlag::UnicodeSets;
2551 } else if (unit == 'y') {
2552 flag = RegExpFlag::Sticky;
2553 } else if (IsAsciiAlpha(unit)) {
2554 flag = RegExpFlag::NoFlags;
2555 } else {
2556 break;
2557 }
2558
2559 if ((reflags & flag) || flag == RegExpFlag::NoFlags) {
2560 ungetCodeUnit(unit);
2561 char buf[2] = {char(unit), '\0'};
2562 error(JSMSG_BAD_REGEXP_FLAG, buf);
2563 return badToken();
2564 }
2565
2566 // /u and /v flags are mutually exclusive.
2567 if (((reflags & RegExpFlag::Unicode) && (flag & RegExpFlag::UnicodeSets)) ||
2568 ((reflags & RegExpFlag::UnicodeSets) && (flag & RegExpFlag::Unicode))) {
2569 ungetCodeUnit(unit);
2570 char buf[2] = {char(unit), '\0'};
2571 error(JSMSG_BAD_REGEXP_FLAG, buf);
2572 return badToken();
2573 }
2574
2575 reflags |= flag;
2576 }
2577 ungetCodeUnit(unit);
2578
2579 newRegExpToken(reflags, start, out);
2580 return true;
2581 }
2582
2583 template <typename Unit, class AnyCharsAccess>
2584 [[nodiscard]] bool TokenStreamSpecific<Unit, AnyCharsAccess>::bigIntLiteral(
2585 TokenStart start, Modifier modifier, TokenKind* out) {
2586 MOZ_ASSERT(this->sourceUnits.previousCodeUnit() == toUnit('n'));
2587 MOZ_ASSERT(this->sourceUnits.offset() > start.offset());
2588 uint32_t length = this->sourceUnits.offset() - start.offset();
2589 MOZ_ASSERT(length >= 2);
2590 this->charBuffer.clear();
2591 mozilla::Range<const Unit> chars(
2592 this->sourceUnits.codeUnitPtrAt(start.offset()), length);
2593 for (uint32_t idx = 0; idx < length - 1; idx++) {
2594 int32_t unit = CodeUnitValue(chars[idx]);
2595 // Char buffer may start with a 0[bBoOxX] prefix, then follows with
2596 // binary, octal, decimal, or hex digits. Already checked by caller, as
2597 // the "n" indicating bigint comes at the end.
2598 MOZ_ASSERT(isAsciiCodePoint(unit));
2599 // Skip over any separators.
2600 if (unit == '_') {
2601 continue;
2602 }
2603 if (!AppendCodePointToCharBuffer(this->charBuffer, unit)) {
2604 return false;
2605 }
2606 }
2607 newBigIntToken(start, modifier, out);
2608 return true;
2609 }
2610
2611 template <typename Unit, class AnyCharsAccess>
2612 void GeneralTokenStreamChars<Unit,
2613 AnyCharsAccess>::consumeOptionalHashbangComment() {
2614 MOZ_ASSERT(this->sourceUnits.atStart(),
2615 "HashBangComment can only appear immediately at the start of a "
2616 "Script or Module");
2617
2618 // HashbangComment ::
2619 // #! SingleLineCommentChars_opt
2620
2621 if (!matchCodeUnit('#')) {
2622 // HashbangComment is optional at start of Script or Module.
2623 return;
2624 }
2625
2626 if (!matchCodeUnit('!')) {
2627 // # not followed by ! at start of Script or Module is an error, but normal
2628 // parsing code will handle that error just fine if we let it.
2629 ungetCodeUnit('#');
2630 return;
2631 }
2632
2633 // This doesn't consume a concluding LineTerminator, and it stops consuming
2634 // just before any encoding error. The subsequent |getToken| call will call
2635 // |getTokenInternal| below which will handle these possibilities.
2636 this->sourceUnits.consumeRestOfSingleLineComment();
2637 }
2638
2639 template <typename Unit, class AnyCharsAccess>
2640 [[nodiscard]] bool TokenStreamSpecific<Unit, AnyCharsAccess>::getTokenInternal(
2641 TokenKind* const ttp, const Modifier modifier) {
2642 // Assume we'll fail: success cases will overwrite this.
2643 #ifdef DEBUG
2644 *ttp = TokenKind::Limit;
2645 #endif
2646 MOZ_MAKE_MEM_UNDEFINED(ttp, sizeof(*ttp));
2647
2648 // This loop runs more than once only when whitespace or comments are
2649 // encountered.
2650 do {
2651 int32_t unit = peekCodeUnit();
2652 if (MOZ_UNLIKELY(unit == EOF)) {
2653 MOZ_ASSERT(this->sourceUnits.atEnd());
2654 anyCharsAccess().flags.isEOF = true;
2655 TokenStart start(this->sourceUnits, 0);
2656 newSimpleToken(TokenKind::Eof, start, modifier, ttp);
2657 return true;
2658 }
2659
2660 if (MOZ_UNLIKELY(!isAsciiCodePoint(unit))) {
2661 // Non-ASCII code points can only be identifiers or whitespace. It would
2662 // be nice to compute these *after* discarding whitespace, but IN A WORLD
2663 // where |unicode::IsSpace| requires consuming a variable number of code
2664 // units, it's easier to assume it's an identifier and maybe do a little
2665 // wasted work, than to unget and compute and reget if whitespace.
2666 TokenStart start(this->sourceUnits, 0);
2667 const Unit* identStart = this->sourceUnits.addressOfNextCodeUnit();
2668
2669 PeekedCodePoint<Unit> peeked = this->sourceUnits.peekCodePoint();
2670 if (peeked.isNone()) {
2671 MOZ_ALWAYS_FALSE(getCodePoint());
2672 return badToken();
2673 }
2674
2675 char32_t cp = peeked.codePoint();
2676 if (unicode::IsSpace(cp)) {
2677 this->sourceUnits.consumeKnownCodePoint(peeked);
2678 if (IsLineTerminator(cp)) {
2679 if (!updateLineInfoForEOL()) {
2680 return badToken();
2681 }
2682
2683 anyCharsAccess().updateFlagsForEOL();
2684 }
2685
2686 continue;
2687 }
2688
2689 static_assert(isAsciiCodePoint('$'),
2690 "IdentifierStart contains '$', but as "
2691 "!IsUnicodeIDStart('$'), ensure that '$' is never "
2692 "handled here");
2693 static_assert(isAsciiCodePoint('_'),
2694 "IdentifierStart contains '_', but as "
2695 "!IsUnicodeIDStart('_'), ensure that '_' is never "
2696 "handled here");
2697
2698 if (MOZ_LIKELY(unicode::IsUnicodeIDStart(cp))) {
2699 this->sourceUnits.consumeKnownCodePoint(peeked);
2700 MOZ_ASSERT(!IsLineTerminator(cp),
2701 "IdentifierStart must guarantee !IsLineTerminator "
2702 "or else we'll fail to maintain line-info/flags "
2703 "for EOL here");
2704
2705 return identifierName(start, identStart, IdentifierEscapes::None,
2706 modifier, NameVisibility::Public, ttp);
2707 }
2708
2709 reportIllegalCharacter(cp);
2710 return badToken();
2711 } // !isAsciiCodePoint(unit)
2712
2713 consumeKnownCodeUnit(unit);
2714
2715 // Get the token kind, based on the first char. The ordering of c1kind
2716 // comparison is based on the frequency of tokens in real code:
2717 // Parsemark (which represents typical JS code on the web) and the
2718 // Unreal demo (which represents asm.js code).
2719 //
2720 // Parsemark Unreal
2721 // OneChar 32.9% 39.7%
2722 // Space 25.0% 0.6%
2723 // Ident 19.2% 36.4%
2724 // Dec 7.2% 5.1%
2725 // String 7.9% 0.0%
2726 // EOL 1.7% 0.0%
2727 // ZeroDigit 0.4% 4.9%
2728 // Other 5.7% 13.3%
2729 //
2730 // The ordering is based mostly only Parsemark frequencies, with Unreal
2731 // frequencies used to break close categories (e.g. |Dec| and
2732 // |String|). |Other| is biggish, but no other token kind is common
2733 // enough for it to be worth adding extra values to FirstCharKind.
2734 FirstCharKind c1kind = FirstCharKind(firstCharKinds[unit]);
2735
2736 // Look for an unambiguous single-char token.
2737 //
2738 if (c1kind <= OneChar_Max) {
2739 TokenStart start(this->sourceUnits, -1);
2740 newSimpleToken(TokenKind(c1kind), start, modifier, ttp);
2741 return true;
2742 }
2743
2744 // Skip over non-EOL whitespace chars.
2745 //
2746 if (c1kind == Space) {
2747 continue;
2748 }
2749
2750 // Look for an identifier.
2751 //
2752 if (c1kind == Ident) {
2753 TokenStart start(this->sourceUnits, -1);
2754 return identifierName(
2755 start, this->sourceUnits.addressOfNextCodeUnit() - 1,
2756 IdentifierEscapes::None, modifier, NameVisibility::Public, ttp);
2757 }
2758
2759 // Look for a decimal number.
2760 //
2761 if (c1kind == Dec) {
2762 TokenStart start(this->sourceUnits, -1);
2763 const Unit* numStart = this->sourceUnits.addressOfNextCodeUnit() - 1;
2764 return decimalNumber(unit, start, numStart, modifier, ttp);
2765 }
2766
2767 // Look for a string or a template string.
2768 //
2769 if (c1kind == String) {
2770 return getStringOrTemplateToken(static_cast<char>(unit), modifier, ttp);
2771 }
2772
2773 // Skip over EOL chars, updating line state along the way.
2774 //
2775 if (c1kind == EOL) {
2776 if (unit == '\r') {
2777 matchLineTerminator('\n');
2778 }
2779
2780 if (!updateLineInfoForEOL()) {
2781 return badToken();
2782 }
2783
2784 anyCharsAccess().updateFlagsForEOL();
2785 continue;
2786 }
2787
2788 // From a '0', look for a hexadecimal, binary, octal, or "noctal" (a
2789 // number starting with '0' that contains '8' or '9' and is treated as
2790 // decimal) number.
2791 //
2792 if (c1kind == ZeroDigit) {
2793 TokenStart start(this->sourceUnits, -1);
2794 int radix;
2795 bool isBigInt = false;
2796 const Unit* numStart;
2797 unit = getCodeUnit();
2798 if (unit == 'x' || unit == 'X') {
2799 radix = 16;
2800 unit = getCodeUnit();
2801 if (!IsAsciiHexDigit(unit)) {
2802 // NOTE: |unit| may be EOF here.
2803 ungetCodeUnit(unit);
2804 error(JSMSG_MISSING_HEXDIGITS);
2805 return badToken();
2806 }
2807
2808 // one past the '0x'
2809 numStart = this->sourceUnits.addressOfNextCodeUnit() - 1;
2810
2811 if (!matchIntegerAfterFirstDigit(IsAsciiHexDigit, &unit)) {
2812 return badToken();
2813 }
2814 } else if (unit == 'b' || unit == 'B') {
2815 radix = 2;
2816 unit = getCodeUnit();
2817 if (!IsAsciiBinary(unit)) {
2818 // NOTE: |unit| may be EOF here.
2819 ungetCodeUnit(unit);
2820 error(JSMSG_MISSING_BINARY_DIGITS);
2821 return badToken();
2822 }
2823
2824 // one past the '0b'
2825 numStart = this->sourceUnits.addressOfNextCodeUnit() - 1;
2826
2827 if (!matchIntegerAfterFirstDigit(IsAsciiBinary, &unit)) {
2828 return badToken();
2829 }
2830 } else if (unit == 'o' || unit == 'O') {
2831 radix = 8;
2832 unit = getCodeUnit();
2833 if (!IsAsciiOctal(unit)) {
2834 // NOTE: |unit| may be EOF here.
2835 ungetCodeUnit(unit);
2836 error(JSMSG_MISSING_OCTAL_DIGITS);
2837 return badToken();
2838 }
2839
2840 // one past the '0o'
2841 numStart = this->sourceUnits.addressOfNextCodeUnit() - 1;
2842
2843 if (!matchIntegerAfterFirstDigit(IsAsciiOctal, &unit)) {
2844 return badToken();
2845 }
2846 } else if (IsAsciiDigit(unit)) {
2847 // Reject octal literals that appear in strict mode code.
2848 if (!strictModeError(JSMSG_DEPRECATED_OCTAL_LITERAL)) {
2849 return badToken();
2850 }
2851
2852 // The above test doesn't catch a few edge cases; see
2853 // |GeneralParser::maybeParseDirective|. Record the violation so that
2854 // that function can handle them.
2855 anyCharsAccess().setSawDeprecatedOctalLiteral();
2856
2857 radix = 8;
2858 // one past the '0'
2859 numStart = this->sourceUnits.addressOfNextCodeUnit() - 1;
2860
2861 bool nonOctalDecimalIntegerLiteral = false;
2862 do {
2863 if (unit >= '8') {
2864 nonOctalDecimalIntegerLiteral = true;
2865 }
2866 unit = getCodeUnit();
2867 } while (IsAsciiDigit(unit));
2868
2869 if (unit == '_') {
2870 ungetCodeUnit(unit);
2871 error(JSMSG_SEPARATOR_IN_ZERO_PREFIXED_NUMBER);
2872 return badToken();
2873 }
2874
2875 if (unit == 'n') {
2876 ungetCodeUnit(unit);
2877 error(JSMSG_BIGINT_INVALID_SYNTAX);
2878 return badToken();
2879 }
2880
2881 if (nonOctalDecimalIntegerLiteral) {
2882 // Use the decimal scanner for the rest of the number.
2883 return decimalNumber(unit, start, numStart, modifier, ttp);
2884 }
2885 } else if (unit == '_') {
2886 // Give a more explicit error message when '_' is used after '0'.
2887 ungetCodeUnit(unit);
2888 error(JSMSG_SEPARATOR_IN_ZERO_PREFIXED_NUMBER);
2889 return badToken();
2890 } else {
2891 // '0' not followed by [XxBbOo0-9_]; scan as a decimal number.
2892 ungetCodeUnit(unit);
2893 numStart = this->sourceUnits.addressOfNextCodeUnit() - 1; // The '0'.
2894 return decimalNumber('0', start, numStart, modifier, ttp);
2895 }
2896
2897 if (unit == 'n') {
2898 isBigInt = true;
2899 unit = peekCodeUnit();
2900 } else {
2901 ungetCodeUnit(unit);
2902 }
2903
2904 // Error if an identifier-start code point appears immediately
2905 // after the number. Somewhat surprisingly, if we don't check
2906 // here, we'll never check at all.
2907 if (MOZ_LIKELY(isAsciiCodePoint(unit))) {
2908 if (unicode::IsIdentifierStart(char16_t(unit))) {
2909 error(JSMSG_IDSTART_AFTER_NUMBER);
2910 return badToken();
2911 }
2912 } else if (MOZ_LIKELY(unit != EOF)) {
2913 // This ignores encoding errors: subsequent caller-side code to
2914 // handle source text after the number will do so.
2915 PeekedCodePoint<Unit> peeked = this->sourceUnits.peekCodePoint();
2916 if (!peeked.isNone() &&
2917 unicode::IsIdentifierStart(peeked.codePoint())) {
2918 error(JSMSG_IDSTART_AFTER_NUMBER);
2919 return badToken();
2920 }
2921 }
2922
2923 if (isBigInt) {
2924 return bigIntLiteral(start, modifier, ttp);
2925 }
2926
2927 double dval;
2928 if (!GetFullInteger(numStart, this->sourceUnits.addressOfNextCodeUnit(),
2929 radix, IntegerSeparatorHandling::SkipUnderscore,
2930 &dval)) {
2931 ReportOutOfMemory(this->fc);
2932 return badToken();
2933 }
2934 newNumberToken(dval, NoDecimal, start, modifier, ttp);
2935 return true;
2936 }
2937
2938 MOZ_ASSERT(c1kind == Other);
2939
2940 // This handles everything else. Simple tokens distinguished solely by
2941 // TokenKind should set |simpleKind| and break, to share simple-token
2942 // creation code for all such tokens. All other tokens must be handled
2943 // by returning (or by continuing from the loop enclosing this).
2944 //
2945 TokenStart start(this->sourceUnits, -1);
2946 TokenKind simpleKind;
2947 #ifdef DEBUG
2948 simpleKind = TokenKind::Limit; // sentinel value for code after switch
2949 #endif
2950
2951 // The block a ways above eliminated all non-ASCII, so cast to the
2952 // smallest type possible to assist the C++ compiler.
2953 switch (AssertedCast<uint8_t>(CodeUnitValue(toUnit(unit)))) {
2954 case '.':
2955 if (IsAsciiDigit(peekCodeUnit())) {
2956 return decimalNumber('.', start,
2957 this->sourceUnits.addressOfNextCodeUnit() - 1,
2958 modifier, ttp);
2959 }
2960
2961 unit = getCodeUnit();
2962 if (unit == '.') {
2963 if (matchCodeUnit('.')) {
2964 simpleKind = TokenKind::TripleDot;
2965 break;
2966 }
2967 }
2968
2969 // NOTE: |unit| may be EOF here. A stray '.' at EOF would be an
2970 // error, but subsequent code will handle it.
2971 ungetCodeUnit(unit);
2972
2973 simpleKind = TokenKind::Dot;
2974 break;
2975
2976 case '#': {
2977 TokenStart start(this->sourceUnits, -1);
2978 const Unit* identStart = this->sourceUnits.addressOfNextCodeUnit() - 1;
2979 IdentifierEscapes sawEscape;
2980 if (!matchIdentifierStart(&sawEscape)) {
2981 return badToken();
2982 }
2983 return identifierName(start, identStart, sawEscape, modifier,
2984 NameVisibility::Private, ttp);
2985 }
2986
2987 case '=':
2988 if (matchCodeUnit('=')) {
2989 simpleKind = matchCodeUnit('=') ? TokenKind::StrictEq : TokenKind::Eq;
2990 } else if (matchCodeUnit('>')) {
2991 simpleKind = TokenKind::Arrow;
2992 } else {
2993 simpleKind = TokenKind::Assign;
2994 }
2995 break;
2996
2997 case '+':
2998 if (matchCodeUnit('+')) {
2999 simpleKind = TokenKind::Inc;
3000 } else {
3001 simpleKind =
3002 matchCodeUnit('=') ? TokenKind::AddAssign : TokenKind::Add;
3003 }
3004 break;
3005
3006 case '\\': {
3007 char32_t codePoint;
3008 if (uint32_t escapeLength = matchUnicodeEscapeIdStart(&codePoint)) {
3009 return identifierName(
3010 start,
3011 this->sourceUnits.addressOfNextCodeUnit() - escapeLength - 1,
3012 IdentifierEscapes::SawUnicodeEscape, modifier,
3013 NameVisibility::Public, ttp);
3014 }
3015
3016 // We could point "into" a mistyped escape, e.g. for "\u{41H}" we
3017 // could point at the 'H'. But we don't do that now, so the code
3018 // unit after the '\' isn't necessarily bad, so just point at the
3019 // start of the actually-invalid escape.
3020 ungetCodeUnit('\\');
3021 error(JSMSG_BAD_ESCAPE);
3022 return badToken();
3023 }
3024
3025 case '|':
3026 if (matchCodeUnit('|')) {
3027 simpleKind = matchCodeUnit('=') ? TokenKind::OrAssign : TokenKind::Or;
3028 } else {
3029 simpleKind =
3030 matchCodeUnit('=') ? TokenKind::BitOrAssign : TokenKind::BitOr;
3031 }
3032 break;
3033
3034 case '^':
3035 simpleKind =
3036 matchCodeUnit('=') ? TokenKind::BitXorAssign : TokenKind::BitXor;
3037 break;
3038
3039 case '&':
3040 if (matchCodeUnit('&')) {
3041 simpleKind =
3042 matchCodeUnit('=') ? TokenKind::AndAssign : TokenKind::And;
3043 } else {
3044 simpleKind =
3045 matchCodeUnit('=') ? TokenKind::BitAndAssign : TokenKind::BitAnd;
3046 }
3047 break;
3048
3049 case '?':
3050 if (matchCodeUnit('.')) {
3051 unit = getCodeUnit();
3052 if (IsAsciiDigit(unit)) {
3053 // if the code unit is followed by a number, for example it has the
3054 // following form `<...> ?.5 <..> then it should be treated as a
3055 // ternary rather than as an optional chain
3056 simpleKind = TokenKind::Hook;
3057 ungetCodeUnit(unit);
3058 ungetCodeUnit('.');
3059 } else {
3060 ungetCodeUnit(unit);
3061 simpleKind = TokenKind::OptionalChain;
3062 }
3063 } else if (matchCodeUnit('?')) {
3064 simpleKind = matchCodeUnit('=') ? TokenKind::CoalesceAssign
3065 : TokenKind::Coalesce;
3066 } else {
3067 simpleKind = TokenKind::Hook;
3068 }
3069 break;
3070
3071 case '!':
3072 if (matchCodeUnit('=')) {
3073 simpleKind = matchCodeUnit('=') ? TokenKind::StrictNe : TokenKind::Ne;
3074 } else {
3075 simpleKind = TokenKind::Not;
3076 }
3077 break;
3078
3079 case '<':
3080 if (anyCharsAccess().options().allowHTMLComments) {
3081 // Treat HTML begin-comment as comment-till-end-of-line.
3082 if (matchCodeUnit('!')) {
3083 if (matchCodeUnit('-')) {
3084 if (matchCodeUnit('-')) {
3085 this->sourceUnits.consumeRestOfSingleLineComment();
3086 continue;
3087 }
3088 ungetCodeUnit('-');
3089 }
3090 ungetCodeUnit('!');
3091 }
3092 }
3093 if (matchCodeUnit('<')) {
3094 simpleKind =
3095 matchCodeUnit('=') ? TokenKind::LshAssign : TokenKind::Lsh;
3096 } else {
3097 simpleKind = matchCodeUnit('=') ? TokenKind::Le : TokenKind::Lt;
3098 }
3099 break;
3100
3101 case '>':
3102 if (matchCodeUnit('>')) {
3103 if (matchCodeUnit('>')) {
3104 simpleKind =
3105 matchCodeUnit('=') ? TokenKind::UrshAssign : TokenKind::Ursh;
3106 } else {
3107 simpleKind =
3108 matchCodeUnit('=') ? TokenKind::RshAssign : TokenKind::Rsh;
3109 }
3110 } else {
3111 simpleKind = matchCodeUnit('=') ? TokenKind::Ge : TokenKind::Gt;
3112 }
3113 break;
3114
3115 case '*':
3116 if (matchCodeUnit('*')) {
3117 simpleKind =
3118 matchCodeUnit('=') ? TokenKind::PowAssign : TokenKind::Pow;
3119 } else {
3120 simpleKind =
3121 matchCodeUnit('=') ? TokenKind::MulAssign : TokenKind::Mul;
3122 }
3123 break;
3124
3125 case '/':
3126 // Look for a single-line comment.
3127 if (matchCodeUnit('/')) {
3128 unit = getCodeUnit();
3129 if (unit == '@' || unit == '#') {
3130 bool shouldWarn = unit == '@';
3131 if (!getDirectives(false, shouldWarn)) {
3132 return false;
3133 }
3134 } else {
3135 // NOTE: |unit| may be EOF here.
3136 ungetCodeUnit(unit);
3137 }
3138
3139 this->sourceUnits.consumeRestOfSingleLineComment();
3140 continue;
3141 }
3142
3143 // Look for a multi-line comment.
3144 if (matchCodeUnit('*')) {
3145 TokenStreamAnyChars& anyChars = anyCharsAccess();
3146 unsigned linenoBefore = anyChars.lineno;
3147
3148 do {
3149 int32_t unit = getCodeUnit();
3150 if (unit == EOF) {
3151 error(JSMSG_UNTERMINATED_COMMENT);
3152 return badToken();
3153 }
3154
3155 if (unit == '*' && matchCodeUnit('/')) {
3156 break;
3157 }
3158
3159 if (unit == '@' || unit == '#') {
3160 bool shouldWarn = unit == '@';
3161 if (!getDirectives(true, shouldWarn)) {
3162 return badToken();
3163 }
3164 } else if (MOZ_LIKELY(isAsciiCodePoint(unit))) {
3165 if (!getFullAsciiCodePoint(unit)) {
3166 return badToken();
3167 }
3168 } else {
3169 char32_t codePoint;
3170 if (!getNonAsciiCodePoint(unit, &codePoint)) {
3171 return badToken();
3172 }
3173 }
3174 } while (true);
3175
3176 if (linenoBefore != anyChars.lineno) {
3177 anyChars.updateFlagsForEOL();
3178 }
3179
3180 continue;
3181 }
3182
3183 // Look for a regexp.
3184 if (modifier == SlashIsRegExp) {
3185 return regexpLiteral(start, ttp);
3186 }
3187
3188 simpleKind = matchCodeUnit('=') ? TokenKind::DivAssign : TokenKind::Div;
3189 break;
3190
3191 case '%':
3192 simpleKind = matchCodeUnit('=') ? TokenKind::ModAssign : TokenKind::Mod;
3193 break;
3194
3195 case '-':
3196 if (matchCodeUnit('-')) {
3197 if (anyCharsAccess().options().allowHTMLComments &&
3198 !anyCharsAccess().flags.isDirtyLine) {
3199 if (matchCodeUnit('>')) {
3200 this->sourceUnits.consumeRestOfSingleLineComment();
3201 continue;
3202 }
3203 }
3204
3205 simpleKind = TokenKind::Dec;
3206 } else {
3207 simpleKind =
3208 matchCodeUnit('=') ? TokenKind::SubAssign : TokenKind::Sub;
3209 }
3210 break;
3211
3212 #ifdef ENABLE_DECORATORS
3213 case '@':
3214 simpleKind = TokenKind::At;
3215 break;
3216 #endif
3217
3218 default:
3219 // We consumed a bad ASCII code point/unit. Put it back so the
3220 // error location is the bad code point.
3221 ungetCodeUnit(unit);
3222 reportIllegalCharacter(unit);
3223 return badToken();
3224 } // switch (AssertedCast<uint8_t>(CodeUnitValue(toUnit(unit))))
3225
3226 MOZ_ASSERT(simpleKind != TokenKind::Limit,
3227 "switch-statement should have set |simpleKind| before "
3228 "breaking");
3229
3230 newSimpleToken(simpleKind, start, modifier, ttp);
3231 return true;
3232 } while (true);
3233 }
3234
3235 template <typename Unit, class AnyCharsAccess>
3236 bool TokenStreamSpecific<Unit, AnyCharsAccess>::getStringOrTemplateToken(
3237 char untilChar, Modifier modifier, TokenKind* out) {
3238 MOZ_ASSERT(untilChar == '\'' || untilChar == '"' || untilChar == '`',
3239 "unexpected string/template literal delimiter");
3240
3241 bool parsingTemplate = (untilChar == '`');
3242 bool templateHead = false;
3243
3244 TokenStart start(this->sourceUnits, -1);
3245 this->charBuffer.clear();
3246
3247 // Run the bad-token code for every path out of this function except the
3248 // one success-case.
3249 auto noteBadToken = MakeScopeExit([this]() { this->badToken(); });
3250
3251 auto ReportPrematureEndOfLiteral = [this, untilChar](unsigned errnum) {
3252 // Unicode separators aren't end-of-line in template or (as of
3253 // recently) string literals, so this assertion doesn't allow them.
3254 MOZ_ASSERT(this->sourceUnits.atEnd() ||
3255 this->sourceUnits.peekCodeUnit() == Unit('\r') ||
3256 this->sourceUnits.peekCodeUnit() == Unit('\n'),
3257 "must be parked at EOF or EOL to call this function");
3258
3259 // The various errors reported here include language like "in a ''
3260 // literal" or similar, with '' being '', "", or `` as appropriate.
3261 const char delimiters[] = {untilChar, untilChar, '\0'};
3262
3263 this->error(errnum, delimiters);
3264 return;
3265 };
3266
3267 // We need to detect any of these chars: " or ', \n (or its
3268 // equivalents), \\, EOF. Because we detect EOL sequences here and
3269 // put them back immediately, we can use getCodeUnit().
3270 int32_t unit;
3271 while ((unit = getCodeUnit()) != untilChar) {
3272 if (unit == EOF) {
3273 ReportPrematureEndOfLiteral(JSMSG_EOF_BEFORE_END_OF_LITERAL);
3274 return false;
3275 }
3276
3277 // Non-ASCII code points are always directly appended -- even
3278 // U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR that are
3279 // ordinarily LineTerminatorSequences. (They contribute their literal
3280 // values to template and [as of recently] string literals, but they're
3281 // line terminators when computing line/column coordinates.) Handle
3282 // the non-ASCII case early for readability.
3283 if (MOZ_UNLIKELY(!isAsciiCodePoint(unit))) {
3284 char32_t cp;
3285 if (!getNonAsciiCodePointDontNormalize(toUnit(unit), &cp)) {
3286 return false;
3287 }
3288
3289 if (MOZ_UNLIKELY(cp == unicode::LINE_SEPARATOR ||
3290 cp == unicode::PARA_SEPARATOR)) {
3291 if (!updateLineInfoForEOL()) {
3292 return false;
3293 }
3294
3295 anyCharsAccess().updateFlagsForEOL();
3296 } else {
3297 MOZ_ASSERT(!IsLineTerminator(cp));
3298 }
3299
3300 if (!AppendCodePointToCharBuffer(this->charBuffer, cp)) {
3301 return false;
3302 }
3303
3304 continue;
3305 }
3306
3307 if (unit == '\\') {
3308 // When parsing templates, we don't immediately report errors for
3309 // invalid escapes; these are handled by the parser. We don't
3310 // append to charBuffer in those cases because it won't be read.
3311 unit = getCodeUnit();
3312 if (unit == EOF) {
3313 ReportPrematureEndOfLiteral(JSMSG_EOF_IN_ESCAPE_IN_LITERAL);
3314 return false;
3315 }
3316
3317 // Non-ASCII |unit| isn't handled by code after this, so dedicate
3318 // an unlikely special-case to it and then continue.
3319 if (MOZ_UNLIKELY(!isAsciiCodePoint(unit))) {
3320 char32_t codePoint;
3321 if (!getNonAsciiCodePoint(unit, &codePoint)) {
3322 return false;
3323 }
3324
3325 // If we consumed U+2028 LINE SEPARATOR or U+2029 PARAGRAPH
3326 // SEPARATOR, they'll be normalized to '\n'. '\' followed by
3327 // LineContinuation represents no code points, so don't append
3328 // in this case.
3329 if (codePoint != '\n') {
3330 if (!AppendCodePointToCharBuffer(this->charBuffer, codePoint)) {
3331 return false;
3332 }
3333 }
3334
3335 continue;
3336 }
3337
3338 // The block above eliminated all non-ASCII, so cast to the
3339 // smallest type possible to assist the C++ compiler.
3340 switch (AssertedCast<uint8_t>(CodeUnitValue(toUnit(unit)))) {
3341 case 'b':
3342 unit = '\b';
3343 break;
3344 case 'f':
3345 unit = '\f';
3346 break;
3347 case 'n':
3348 unit = '\n';
3349 break;
3350 case 'r':
3351 unit = '\r';
3352 break;
3353 case 't':
3354 unit = '\t';
3355 break;
3356 case 'v':
3357 unit = '\v';
3358 break;
3359
3360 case '\r':
3361 matchLineTerminator('\n');
3362 [[fallthrough]];
3363 case '\n': {
3364 // LineContinuation represents no code points. We're manually
3365 // consuming a LineTerminatorSequence, so we must manually
3366 // update line/column info.
3367 if (!updateLineInfoForEOL()) {
3368 return false;
3369 }
3370
3371 continue;
3372 }
3373
3374 // Unicode character specification.
3375 case 'u': {
3376 int32_t c2 = getCodeUnit();
3377 if (c2 == EOF) {
3378 ReportPrematureEndOfLiteral(JSMSG_EOF_IN_ESCAPE_IN_LITERAL);
3379 return false;
3380 }
3381
3382 // First handle a delimited Unicode escape, e.g. \u{1F4A9}.
3383 if (c2 == '{') {
3384 uint32_t start = this->sourceUnits.offset() - 3;
3385 uint32_t code = 0;
3386 bool first = true;
3387 bool valid = true;
3388 do {
3389 int32_t u3 = getCodeUnit();
3390 if (u3 == EOF) {
3391 if (parsingTemplate) {
3392 TokenStreamAnyChars& anyChars = anyCharsAccess();
3393 anyChars.setInvalidTemplateEscape(start,
3394 InvalidEscapeType::Unicode);
3395 valid = false;
3396 break;
3397 }
3398 reportInvalidEscapeError(start, InvalidEscapeType::Unicode);
3399 return false;
3400 }
3401 if (u3 == '}') {
3402 if (first) {
3403 if (parsingTemplate) {
3404 TokenStreamAnyChars& anyChars = anyCharsAccess();
3405 anyChars.setInvalidTemplateEscape(
3406 start, InvalidEscapeType::Unicode);
3407 valid = false;
3408 break;
3409 }
3410 reportInvalidEscapeError(start, InvalidEscapeType::Unicode);
3411 return false;
3412 }
3413 break;
3414 }
3415
3416 // Beware: |u3| may be a non-ASCII code point here; if
3417 // so it'll pass into this |if|-block.
3418 if (!IsAsciiHexDigit(u3)) {
3419 if (parsingTemplate) {
3420 // We put the code unit back so that we read it
3421 // on the next pass, which matters if it was
3422 // '`' or '\'.
3423 ungetCodeUnit(u3);
3424
3425 TokenStreamAnyChars& anyChars = anyCharsAccess();
3426 anyChars.setInvalidTemplateEscape(start,
3427 InvalidEscapeType::Unicode);
3428 valid = false;
3429 break;
3430 }
3431 reportInvalidEscapeError(start, InvalidEscapeType::Unicode);
3432 return false;
3433 }
3434
3435 code = (code << 4) | AsciiAlphanumericToNumber(u3);
3436 if (code > unicode::NonBMPMax) {
3437 if (parsingTemplate) {
3438 TokenStreamAnyChars& anyChars = anyCharsAccess();
3439 anyChars.setInvalidTemplateEscape(
3440 start + 3, InvalidEscapeType::UnicodeOverflow);
3441 valid = false;
3442 break;
3443 }
3444 reportInvalidEscapeError(start + 3,
3445 InvalidEscapeType::UnicodeOverflow);
3446 return false;
3447 }
3448
3449 first = false;
3450 } while (true);
3451
3452 if (!valid) {
3453 continue;
3454 }
3455
3456 MOZ_ASSERT(code <= unicode::NonBMPMax);
3457 if (!AppendCodePointToCharBuffer(this->charBuffer, code)) {
3458 return false;
3459 }
3460
3461 continue;
3462 } // end of delimited Unicode escape handling
3463
3464 // Otherwise it must be a fixed-length \uXXXX Unicode escape.
3465 // If it isn't, this is usually an error -- but if this is a
3466 // template literal, we must defer error reporting because
3467 // malformed escapes are okay in *tagged* template literals.
3468 char16_t v;
3469 if (IsAsciiHexDigit(c2) && this->sourceUnits.matchHexDigits(3, &v)) {
3470 unit = (AsciiAlphanumericToNumber(c2) << 12) | v;
3471 } else {
3472 // Beware: |c2| may not be an ASCII code point here!
3473 ungetCodeUnit(c2);
3474 uint32_t start = this->sourceUnits.offset() - 2;
3475 if (parsingTemplate) {
3476 TokenStreamAnyChars& anyChars = anyCharsAccess();
3477 anyChars.setInvalidTemplateEscape(start,
3478 InvalidEscapeType::Unicode);
3479 continue;
3480 }
3481 reportInvalidEscapeError(start, InvalidEscapeType::Unicode);
3482 return false;
3483 }
3484 break;
3485 } // case 'u'
3486
3487 // Hexadecimal character specification.
3488 case 'x': {
3489 char16_t v;
3490 if (this->sourceUnits.matchHexDigits(2, &v)) {
3491 unit = v;
3492 } else {
3493 uint32_t start = this->sourceUnits.offset() - 2;
3494 if (parsingTemplate) {
3495 TokenStreamAnyChars& anyChars = anyCharsAccess();
3496 anyChars.setInvalidTemplateEscape(start,
3497 InvalidEscapeType::Hexadecimal);
3498 continue;
3499 }
3500 reportInvalidEscapeError(start, InvalidEscapeType::Hexadecimal);
3501 return false;
3502 }
3503 break;
3504 }
3505
3506 default: {
3507 if (!IsAsciiOctal(unit)) {
3508 // \8 or \9 in an untagged template literal is a syntax error,
3509 // reported in GeneralParser::noSubstitutionUntaggedTemplate.
3510 //
3511 // Tagged template literals, however, may contain \8 and \9. The
3512 // "cooked" representation of such a part will be |undefined|, and
3513 // the "raw" representation will contain the literal characters.
3514 //
3515 // function f(parts) {
3516 // assertEq(parts[0], undefined);
3517 // assertEq(parts.raw[0], "\\8");
3518 // return "composed";
3519 // }
3520 // assertEq(f`\8`, "composed");
3521 if (unit == '8' || unit == '9') {
3522 TokenStreamAnyChars& anyChars = anyCharsAccess();
3523 if (parsingTemplate) {
3524 anyChars.setInvalidTemplateEscape(
3525 this->sourceUnits.offset() - 2,
3526 InvalidEscapeType::EightOrNine);
3527 continue;
3528 }
3529
3530 // \8 and \9 are forbidden in string literals in strict mode code.
3531 if (!strictModeError(JSMSG_DEPRECATED_EIGHT_OR_NINE_ESCAPE)) {
3532 return false;
3533 }
3534
3535 // The above test doesn't catch a few edge cases; see
3536 // |GeneralParser::maybeParseDirective|. Record the violation so
3537 // that that function can handle them.
3538 anyChars.setSawDeprecatedEightOrNineEscape();
3539 }
3540 break;
3541 }
3542
3543 // Octal character specification.
3544 int32_t val = AsciiOctalToNumber(unit);
3545
3546 unit = peekCodeUnit();
3547 if (MOZ_UNLIKELY(unit == EOF)) {
3548 ReportPrematureEndOfLiteral(JSMSG_EOF_IN_ESCAPE_IN_LITERAL);
3549 return false;
3550 }
3551
3552 // Strict mode code allows only \0 followed by a non-digit.
3553 if (val != 0 || IsAsciiDigit(unit)) {
3554 TokenStreamAnyChars& anyChars = anyCharsAccess();
3555 if (parsingTemplate) {
3556 anyChars.setInvalidTemplateEscape(this->sourceUnits.offset() - 2,
3557 InvalidEscapeType::Octal);
3558 continue;
3559 }
3560
3561 if (!strictModeError(JSMSG_DEPRECATED_OCTAL_ESCAPE)) {
3562 return false;
3563 }
3564
3565 // The above test doesn't catch a few edge cases; see
3566 // |GeneralParser::maybeParseDirective|. Record the violation so
3567 // that that function can handle them.
3568 anyChars.setSawDeprecatedOctalEscape();
3569 }
3570
3571 if (IsAsciiOctal(unit)) {
3572 val = 8 * val + AsciiOctalToNumber(unit);
3573 consumeKnownCodeUnit(unit);
3574
3575 unit = peekCodeUnit();
3576 if (MOZ_UNLIKELY(unit == EOF)) {
3577 ReportPrematureEndOfLiteral(JSMSG_EOF_IN_ESCAPE_IN_LITERAL);
3578 return false;
3579 }
3580
3581 if (IsAsciiOctal(unit)) {
3582 int32_t save = val;
3583 val = 8 * val + AsciiOctalToNumber(unit);
3584 if (val <= 0xFF) {
3585 consumeKnownCodeUnit(unit);
3586 } else {
3587 val = save;
3588 }
3589 }
3590 }
3591
3592 unit = char16_t(val);
3593 break;
3594 } // default
3595 } // switch (AssertedCast<uint8_t>(CodeUnitValue(toUnit(unit))))
3596
3597 if (!this->charBuffer.append(unit)) {
3598 return false;
3599 }
3600
3601 continue;
3602 } // (unit == '\\')
3603
3604 if (unit == '\r' || unit == '\n') {
3605 if (!parsingTemplate) {
3606 // String literals don't allow ASCII line breaks.
3607 ungetCodeUnit(unit);
3608 ReportPrematureEndOfLiteral(JSMSG_EOL_BEFORE_END_OF_STRING);
3609 return false;
3610 }
3611
3612 if (unit == '\r') {
3613 unit = '\n';
3614 matchLineTerminator('\n');
3615 }
3616
3617 if (!updateLineInfoForEOL()) {
3618 return false;
3619 }
3620
3621 anyCharsAccess().updateFlagsForEOL();
3622 } else if (parsingTemplate && unit == '$' && matchCodeUnit('{')) {
3623 templateHead = true;
3624 break;
3625 }
3626
3627 if (!this->charBuffer.append(unit)) {
3628 return false;
3629 }
3630 }
3631
3632 TaggedParserAtomIndex atom = drainCharBufferIntoAtom();
3633 if (!atom) {
3634 return false;
3635 }
3636
3637 noteBadToken.release();
3638
3639 MOZ_ASSERT_IF(!parsingTemplate, !templateHead);
3640
3641 TokenKind kind = !parsingTemplate ? TokenKind::String
3642 : templateHead ? TokenKind::TemplateHead
3643 : TokenKind::NoSubsTemplate;
3644 newAtomToken(kind, atom, start, modifier, out);
3645 return true;
3646 }
3647
3648 const char* TokenKindToDesc(TokenKind tt) {
3649 switch (tt) {
3650 #define EMIT_CASE(name, desc) \
3651 case TokenKind::name: \
3652 return desc;
3653 FOR_EACH_TOKEN_KIND(EMIT_CASE)
3654 #undef EMIT_CASE
3655 case TokenKind::Limit:
3656 MOZ_ASSERT_UNREACHABLE("TokenKind::Limit should not be passed.");
3657 break;
3658 }
3659
3660 return "<bad TokenKind>";
3661 }
3662
3663 #ifdef DEBUG
3664 const char* TokenKindToString(TokenKind tt) {
3665 switch (tt) {
3666 # define EMIT_CASE(name, desc) \
3667 case TokenKind::name: \
3668 return "TokenKind::" #name;
3669 FOR_EACH_TOKEN_KIND(EMIT_CASE)
3670 # undef EMIT_CASE
3671 case TokenKind::Limit:
3672 break;
3673 }
3674
3675 return "<bad TokenKind>";
3676 }
3677 #endif
3678
3679 template class TokenStreamCharsBase<Utf8Unit>;
3680 template class TokenStreamCharsBase<char16_t>;
3681
3682 template class GeneralTokenStreamChars<char16_t, TokenStreamAnyCharsAccess>;
3683 template class TokenStreamChars<char16_t, TokenStreamAnyCharsAccess>;
3684 template class TokenStreamSpecific<char16_t, TokenStreamAnyCharsAccess>;
3685
3686 template class GeneralTokenStreamChars<
3687 Utf8Unit, ParserAnyCharsAccess<GeneralParser<FullParseHandler, Utf8Unit>>>;
3688 template class GeneralTokenStreamChars<
3689 Utf8Unit,
3690 ParserAnyCharsAccess<GeneralParser<SyntaxParseHandler, Utf8Unit>>>;
3691 template class GeneralTokenStreamChars<
3692 char16_t, ParserAnyCharsAccess<GeneralParser<FullParseHandler, char16_t>>>;
3693 template class GeneralTokenStreamChars<
3694 char16_t,
3695 ParserAnyCharsAccess<GeneralParser<SyntaxParseHandler, char16_t>>>;
3696
3697 template class TokenStreamChars<
3698 Utf8Unit, ParserAnyCharsAccess<GeneralParser<FullParseHandler, Utf8Unit>>>;
3699 template class TokenStreamChars<
3700 Utf8Unit,
3701 ParserAnyCharsAccess<GeneralParser<SyntaxParseHandler, Utf8Unit>>>;
3702 template class TokenStreamChars<
3703 char16_t, ParserAnyCharsAccess<GeneralParser<FullParseHandler, char16_t>>>;
3704 template class TokenStreamChars<
3705 char16_t,
3706 ParserAnyCharsAccess<GeneralParser<SyntaxParseHandler, char16_t>>>;
3707
3708 template class TokenStreamSpecific<
3709 Utf8Unit, ParserAnyCharsAccess<GeneralParser<FullParseHandler, Utf8Unit>>>;
3710 template class TokenStreamSpecific<
3711 Utf8Unit,
3712 ParserAnyCharsAccess<GeneralParser<SyntaxParseHandler, Utf8Unit>>>;
3713 template class TokenStreamSpecific<
3714 char16_t, ParserAnyCharsAccess<GeneralParser<FullParseHandler, char16_t>>>;
3715 template class TokenStreamSpecific<
3716 char16_t,
3717 ParserAnyCharsAccess<GeneralParser<SyntaxParseHandler, char16_t>>>;
3718
3719 } // namespace frontend
3720
3721 } // namespace js