-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathScan.cpp
2397 lines (2095 loc) · 74 KB
/
Scan.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "ParserPch.h"
/*****************************************************************************
*
* The following table speeds various tests of characters, such as whether
* a given character can be part of an identifier, and so on.
*/
int CountNewlines(LPCOLESTR psz)
{
int cln = 0;
while (0 != *psz)
{
switch (*psz++)
{
case _u('\xD'):
if (*psz == _u('\xA'))
{
++psz;
}
// fall-through
case _u('\xA'):
cln++;
break;
}
}
return cln;
}
BOOL Token::IsKeyword() const
{
// keywords (but not future reserved words)
return (tk <= tkYIELD);
}
tokens Token::SetRegex(UnifiedRegex::RegexPattern *const pattern, Parser *const parser)
{
Assert(parser);
if(pattern)
parser->RegisterRegexPattern(pattern);
this->u.pattern = pattern;
return tk = tkRegExp;
}
IdentPtr Token::CreateIdentifier(HashTbl * hashTbl)
{
Assert(this->u.pid == nullptr);
if (this->u.pchMin)
{
Assert(IsIdentifier());
IdentPtr pid = hashTbl->PidHashNameLen(this->u.pchMin, this->u.pchMin + this->u.length, this->u.length);
this->u.pid = pid;
return pid;
}
Assert(IsReservedWord());
IdentPtr pid = hashTbl->PidFromTk(tk);
this->u.pid = pid;
return pid;
}
template <typename EncodingPolicy>
Scanner<EncodingPolicy>::Scanner(Parser* parser, Token *ptoken, Js::ScriptContext* scriptContext)
{
Assert(ptoken);
m_parser = parser;
m_ptoken = ptoken;
m_scriptContext = scriptContext;
m_tempChBuf.m_pscanner = this;
m_tempChBufSecondary.m_pscanner = this;
this->charClassifier = scriptContext->GetCharClassifier();
this->es6UnicodeMode = scriptContext->GetConfig()->IsES6UnicodeExtensionsEnabled();
ClearStates();
}
template <typename EncodingPolicy>
Scanner<EncodingPolicy>::~Scanner(void)
{
}
template <typename EncodingPolicy>
void Scanner<EncodingPolicy>::ClearStates()
{
m_pchBase = nullptr;
m_pchLast = nullptr;
m_pchMinLine = nullptr;
m_pchMinTok = nullptr;
m_currentCharacter = nullptr;
m_pchPrevLine = nullptr;
m_cMinTokMultiUnits = 0;
m_cMinLineMultiUnits = 0;
m_fStringTemplateDepth = 0;
m_fHadEol = FALSE;
m_fIsModuleCode = FALSE;
m_doubleQuoteOnLastTkStrCon = FALSE;
m_OctOrLeadingZeroOnLastTKNumber = false;
m_EscapeOnLastTkStrCon = false;
m_fNextStringTemplateIsTagged = false;
m_DeferredParseFlags = ScanFlagNone;
m_fYieldIsKeywordRegion = false;
m_fAwaitIsKeywordRegion = false;
m_line = 0;
m_scanState = ScanStateNormal;
m_ichMinError = 0;
m_ichLimError = 0;
m_startLine = 0;
m_pchStartLine = NULL;
m_iecpLimTokPrevious = (size_t)-1;
m_ichLimTokPrevious = (charcount_t)-1;
}
template <typename EncodingPolicy>
void Scanner<EncodingPolicy>::Clear()
{
EncodingPolicy::Clear();
ClearStates();
this->m_tempChBuf.Clear();
this->m_tempChBufSecondary.Clear();
}
/*****************************************************************************
*
* Initializes the scanner to prepare to scan the given source text.
*/
template <typename EncodingPolicy>
void Scanner<EncodingPolicy>::SetText(EncodedCharPtr pszSrc, size_t offset, size_t length, charcount_t charOffset, bool isUtf8, ULONG grfscr, ULONG lineNumber)
{
// Save the start of the script and add the offset to get the point where we should start scanning.
m_pchBase = pszSrc;
m_pchLast = m_pchBase + offset + length;
m_pchPrevLine = m_currentCharacter = m_pchMinLine = m_pchMinTok = pszSrc + offset;
this->RestoreMultiUnits(offset - charOffset);
// Absorb any byte order mark at the start
if(offset == 0)
{
switch( this->PeekFull(m_currentCharacter, m_pchLast) )
{
case 0xFFEE: // "Opposite" endian BOM
// We do not support big-endian encodings
// fall-through
case 0xFEFF: // "Correct" BOM
this->template ReadFull<true>(m_currentCharacter, m_pchLast);
break;
}
}
m_line = lineNumber;
m_startLine = lineNumber;
m_pchStartLine = m_currentCharacter;
m_ptoken->tk = tkNone;
m_fIsModuleCode = (grfscr & fscrIsModuleCode) != 0;
m_fHadEol = FALSE;
m_DeferredParseFlags = ScanFlagNone;
this->SetIsUtf8(isUtf8);
}
#if ENABLE_BACKGROUND_PARSING
template <typename EncodingPolicy>
void Scanner<EncodingPolicy>::PrepareForBackgroundParse(Js::ScriptContext *scriptContext)
{
scriptContext->GetThreadContext()->GetStandardChars((EncodedChar*)0);
scriptContext->GetThreadContext()->GetStandardChars((char16*)0);
}
#endif
//-----------------------------------------------------------------------------
// Number of code points from 'first' up to, but not including the next
// newline character, embedded NUL, or 'last', depending on which comes first.
//
// This is used to determine a length of BSTR, which can't contain a NUL character.
//-----------------------------------------------------------------------------
template <typename EncodingPolicy>
charcount_t Scanner<EncodingPolicy>::LineLength(EncodedCharPtr first, EncodedCharPtr last, size_t* cb)
{
Assert(cb != nullptr);
charcount_t result = 0;
EncodedCharPtr p = first;
for (;;)
{
EncodedCharPtr prev = p;
switch( this->template ReadFull<false>(p, last) )
{
case kchNWL: // _C_NWL
case kchRET:
case kchLS:
case kchPS:
case kchNUL: // _C_NUL
// p is now advanced past the line terminator character.
// We need to know the number of bytes making up the line, not including the line terminator character.
// To avoid subtracting a variable number of bytes because the line terminator characters are different
// number of bytes long (plus there may be multiple valid encodings for these characters) just keep
// track of the first byte of the line terminator character in prev.
Assert(prev >= first);
*cb = prev - first;
return result;
}
result++;
}
}
template <typename EncodingPolicy>
charcount_t Scanner<EncodingPolicy>::UpdateLine(int32 &line, EncodedCharPtr start, EncodedCharPtr last, charcount_t ichStart, charcount_t ichEnd)
{
EncodedCharPtr p = start;
charcount_t ich = ichStart;
int32 current = line;
charcount_t lastStart = ichStart;
while (ich < ichEnd)
{
ich++;
switch (this->template ReadFull<false>(p, last))
{
case kchRET:
if (this->PeekFull(p, last) == kchNWL)
{
ich++;
this->template ReadFull<false>(p, last);
}
// fall-through
case kchNWL:
case kchLS:
case kchPS:
current++;
lastStart = ich;
break;
case kchNUL:
goto done;
}
}
done:
line = current;
return lastStart;
}
template <typename EncodingPolicy>
bool Scanner<EncodingPolicy>::TryReadEscape(EncodedCharPtr& startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar)
{
Assert(outChar != nullptr);
Assert(startingLocation <= endOfSource);
EncodedCharPtr currentLocation = startingLocation;
codepoint_t charToOutput = 0x0;
// '\' is Assumed as there is only one caller
// Read 'u' characters
if (currentLocation >= endOfSource || this->ReadFirst(currentLocation, endOfSource) != 'u')
{
return false;
}
bool expectCurly = false;
if (currentLocation < endOfSource && this->PeekFirst(currentLocation, endOfSource) == '{' && es6UnicodeMode)
{
expectCurly = true;
// Move past the character
this->ReadFirst(currentLocation, endOfSource);
}
uint i = 0;
OLECHAR ch = 0;
int hexValue = 0;
uint maxHexDigits = (expectCurly ? MAXUINT32 : 4u);
for(; i < maxHexDigits && currentLocation < endOfSource; i++)
{
if (!Js::NumberUtilities::FHexDigit(ch = this->ReadFirst(currentLocation, endOfSource), &hexValue))
{
break;
}
charToOutput = charToOutput * 0x10 + hexValue;
if (charToOutput > 0x10FFFF)
{
return false;
}
}
//At least 4 characters have to be read
if (i == 0 || (i != 4 && !expectCurly))
{
return false;
}
Assert(expectCurly ? es6UnicodeMode : true);
if (expectCurly && ch != '}')
{
return false;
}
*outChar = charToOutput;
startingLocation = currentLocation;
return true;
}
template <typename EncodingPolicy>
template <bool bScan>
bool Scanner<EncodingPolicy>::TryReadCodePointRest(codepoint_t lower, EncodedCharPtr& startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *outContainsMultiUnitChar)
{
Assert(outChar != nullptr);
Assert(outContainsMultiUnitChar != nullptr);
Assert(es6UnicodeMode);
Assert(Js::NumberUtilities::IsSurrogateLowerPart(lower));
EncodedCharPtr currentLocation = startingLocation;
*outChar = lower;
if (currentLocation < endOfSource)
{
size_t restorePoint = this->m_cMultiUnits;
codepoint_t upper = this->template ReadFull<bScan>(currentLocation, endOfSource);
if (Js::NumberUtilities::IsSurrogateUpperPart(upper))
{
*outChar = Js::NumberUtilities::SurrogatePairAsCodePoint(lower, upper);
if (this->IsMultiUnitChar(static_cast<OLECHAR>(upper)))
{
*outContainsMultiUnitChar = true;
}
startingLocation = currentLocation;
}
else
{
this->RestoreMultiUnits(restorePoint);
}
}
return true;
}
template <typename EncodingPolicy>
template <bool bScan>
inline bool Scanner<EncodingPolicy>::TryReadCodePoint(EncodedCharPtr &startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *hasEscape, bool *outContainsMultiUnitChar)
{
Assert(outChar != nullptr);
Assert(outContainsMultiUnitChar != nullptr);
if (startingLocation >= endOfSource)
{
return false;
}
codepoint_t ch = this->template ReadFull<bScan>(startingLocation, endOfSource);
if (FBigChar(ch))
{
if (this->IsMultiUnitChar(static_cast<OLECHAR>(ch)))
{
*outContainsMultiUnitChar = true;
}
if (es6UnicodeMode && Js::NumberUtilities::IsSurrogateLowerPart(ch))
{
return TryReadCodePointRest<bScan>(ch, startingLocation, endOfSource, outChar, outContainsMultiUnitChar);
}
}
else if (ch == '\\' && TryReadEscape(startingLocation, endOfSource, &ch))
{
*hasEscape = true;
}
*outChar = ch;
return true;
}
template <typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::ScanIdentifier(bool identifyKwds, EncodedCharPtr *pp)
{
EncodedCharPtr p = *pp;
EncodedCharPtr pchMin = p;
// JS6 allows unicode characters in the form of \uxxxx escape sequences
// to be part of the identifier.
bool fHasEscape = false;
bool fHasMultiChar = false;
codepoint_t codePoint = INVALID_CODEPOINT;
size_t multiUnitsBeforeLast = this->m_cMultiUnits;
// Check if we started the id
if (!TryReadCodePoint<true>(p, m_pchLast, &codePoint, &fHasEscape, &fHasMultiChar))
{
// If no chars. could be scanned as part of the identifier, return error.
return tkScanError;
}
Assert(codePoint < 0x110000u);
if (!charClassifier->IsIdStart(codePoint))
{
// Put back the last character
this->RestoreMultiUnits(multiUnitsBeforeLast);
// If no chars. could be scanned as part of the identifier, return error.
return tkScanError;
}
return ScanIdentifierContinue(identifyKwds, fHasEscape, fHasMultiChar, pchMin, p, pp);
}
template <typename EncodingPolicy>
BOOL Scanner<EncodingPolicy>::FastIdentifierContinue(EncodedCharPtr&p, EncodedCharPtr last)
{
if (EncodingPolicy::MultiUnitEncoding)
{
while (p < last)
{
EncodedChar currentChar = *p;
if (this->IsMultiUnitChar(currentChar))
{
// multi unit character, we may not have reach the end yet
return FALSE;
}
Assert(currentChar != '\\' || !charClassifier->IsIdContinueFast<false>(currentChar));
if (!charClassifier->IsIdContinueFast<false>(currentChar))
{
// only reach the end of the identifier if it is not the start of an escape sequence
return currentChar != '\\';
}
p++;
}
// We have reach the end of the identifier.
return TRUE;
}
// Not fast path for non multi unit encoding
return false;
}
template <typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::ScanIdentifierContinue(bool identifyKwds, bool fHasEscape, bool fHasMultiChar,
EncodedCharPtr pchMin, EncodedCharPtr p, EncodedCharPtr *pp)
{
EncodedCharPtr last = m_pchLast;
while (true)
{
// Fast path for utf8, non-multi unit char and not escape
if (FastIdentifierContinue(p, last))
{
break;
}
// Slow path that has to deal with multi unit encoding
codepoint_t codePoint = INVALID_CODEPOINT;
EncodedCharPtr pchBeforeLast = p;
size_t multiUnitsBeforeLast = this->m_cMultiUnits;
if (TryReadCodePoint<true>(p, last, &codePoint, &fHasEscape, &fHasMultiChar))
{
Assert(codePoint < 0x110000u);
if (charClassifier->IsIdContinue(codePoint))
{
continue;
}
}
// Put back the last character
p = pchBeforeLast;
this->RestoreMultiUnits(multiUnitsBeforeLast);
break;
}
m_lastIdentifierHasEscape = fHasEscape;
Assert(p - pchMin > 0 && p - pchMin <= LONG_MAX);
*pp = p;
if (!identifyKwds)
{
return tkID;
}
// UTF16 Scanner are only for syntax coloring, so it shouldn't come here.
if (EncodingPolicy::MultiUnitEncoding && !fHasMultiChar && !fHasEscape)
{
Assert(sizeof(EncodedChar) == 1);
// If there are no escape, that the main scan loop would have found the keyword already
// So we can just assume it is an ID
DebugOnly(int32 cch = UnescapeToTempBuf(pchMin, p));
DebugOnly(tokens tk = Ident::TkFromNameLen(m_tempChBuf.m_prgch, cch, IsStrictMode()));
Assert(tk == tkID || (tk == tkYIELD && !this->YieldIsKeyword()) || (tk == tkAWAIT && !this->AwaitIsKeyword()));
m_ptoken->SetIdentifier(reinterpret_cast<const char *>(pchMin), (int32)(p - pchMin));
return tkID;
}
IdentPtr pid = PidOfIdentiferAt(pchMin, p, fHasEscape, fHasMultiChar);
m_ptoken->SetIdentifier(pid);
if (!fHasEscape)
{
// If it doesn't have escape, then Scan() should have taken care of keywords (except
// yield if m_fYieldIsKeyword is false, in which case yield is treated as an identifier, and except
// await if m_fAwaitIsKeyword is false, in which case await is treated as an identifier).
// We don't have to check if the name is reserved word and return it as an Identifier
Assert(pid->Tk(IsStrictMode()) == tkID
|| (pid->Tk(IsStrictMode()) == tkYIELD && !this->YieldIsKeyword())
|| (pid->Tk(IsStrictMode()) == tkAWAIT && !this->AwaitIsKeyword()));
return tkID;
}
tokens tk = pid->Tk(IsStrictMode());
return tk == tkID || (tk == tkYIELD && !this->YieldIsKeyword()) || (tk == tkAWAIT && !this->AwaitIsKeyword()) ? tkID : tkNone;
}
template <typename EncodingPolicy>
IdentPtr Scanner<EncodingPolicy>::PidAt(size_t iecpMin, size_t iecpLim)
{
Assert(iecpMin < AdjustedLength() && iecpLim <= AdjustedLength() && iecpLim > iecpMin);
return PidOfIdentiferAt(m_pchBase + iecpMin, m_pchBase + iecpLim);
}
template <typename EncodingPolicy>
uint32 Scanner<EncodingPolicy>::UnescapeToTempBuf(EncodedCharPtr p, EncodedCharPtr last)
{
m_tempChBuf.Reset();
while( p < last )
{
codepoint_t codePoint;
bool hasEscape, isMultiChar;
bool gotCodePoint = TryReadCodePoint<false>(p, last, &codePoint, &hasEscape, &isMultiChar);
Assert(gotCodePoint);
Assert(codePoint < 0x110000);
if (codePoint < 0x10000)
{
m_tempChBuf.AppendCh((OLECHAR)codePoint);
}
else
{
char16 lower, upper;
Js::NumberUtilities::CodePointAsSurrogatePair(codePoint, &lower, &upper);
m_tempChBuf.AppendCh(lower);
m_tempChBuf.AppendCh(upper);
}
}
return m_tempChBuf.m_ichCur;
}
template <typename EncodingPolicy>
IdentPtr Scanner<EncodingPolicy>::PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last)
{
int32 cch = UnescapeToTempBuf(p, last);
return this->GetHashTbl()->PidHashNameLen(m_tempChBuf.m_prgch, cch);
}
template <typename EncodingPolicy>
IdentPtr Scanner<EncodingPolicy>::PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last, bool fHadEscape, bool fHasMultiChar)
{
// If there is an escape sequence in the JS6 identifier or it is a UTF8
// source then we have to convert it to the equivalent char so we use a
// buffer for translation.
if ((EncodingPolicy::MultiUnitEncoding && fHasMultiChar) || fHadEscape)
{
return PidOfIdentiferAt(p, last);
}
else if (EncodingPolicy::MultiUnitEncoding)
{
Assert(sizeof(EncodedChar) == 1);
return this->GetHashTbl()->PidHashNameLen(reinterpret_cast<const char *>(p), reinterpret_cast<const char *>(last), (int32)(last - p));
}
else
{
Assert(sizeof(EncodedChar) == 2);
return this->GetHashTbl()->PidHashNameLen(reinterpret_cast< const char16 * >(p), (int32)(last - p));
}
}
template <typename EncodingPolicy>
typename Scanner<EncodingPolicy>::EncodedCharPtr Scanner<EncodingPolicy>::FScanNumber(EncodedCharPtr p, double *pdbl, LikelyNumberType& likelyType, size_t savedMultiUnits)
{
EncodedCharPtr last = m_pchLast;
EncodedCharPtr pchT = nullptr;
bool baseSpecified = false;
likelyType = LikelyNumberType::Int;
// Reset
m_OctOrLeadingZeroOnLastTKNumber = false;
auto baseSpecifierCheck = [&pchT, &pdbl, p, &baseSpecified]()
{
if (pchT == p + 2)
{
// An octal token '0' was followed by a base specifier: /0[xXoObB]/
// This literal can no longer be a double
*pdbl = 0;
// Advance the character pointer to the base specifier
pchT = p + 1;
// Set the flag so we know to offset the potential identifier search after the literal
baseSpecified = true;
}
};
if ('0' == this->PeekFirst(p, last))
{
switch(this->PeekFirst(p + 1, last))
{
case '.':
case 'e':
case 'E':
case 'n':
likelyType = LikelyNumberType::Double;
// Floating point
goto LFloat;
case 'x':
case 'X':
// Hex
*pdbl = Js::NumberUtilities::DblFromHex(p + 2, &pchT, m_scriptContext->GetConfig()->IsESNumericSeparatorEnabled());
baseSpecifierCheck();
goto LIdCheck;
case 'o':
case 'O':
// Octal
*pdbl = Js::NumberUtilities::DblFromOctal(p + 2, &pchT, m_scriptContext->GetConfig()->IsESNumericSeparatorEnabled());
baseSpecifierCheck();
goto LIdCheck;
case 'b':
case 'B':
// Binary
*pdbl = Js::NumberUtilities::DblFromBinary(p + 2, &pchT, m_scriptContext->GetConfig()->IsESNumericSeparatorEnabled());
baseSpecifierCheck();
goto LIdCheck;
default:
// Octal
*pdbl = Js::NumberUtilities::DblFromOctal(p, &pchT);
Assert(pchT > p);
#if !SOURCERELEASE
// If an octal literal is malformed then it is in fact a decimal literal.
#endif // !SOURCERELEASE
if(*pdbl != 0 || pchT > p + 1)
m_OctOrLeadingZeroOnLastTKNumber = true; //report as an octal or hex for JSON when leading 0. Just '0' is ok
switch (*pchT)
{
case '8':
case '9':
// case 'e':
// case 'E':
// case '.':
m_OctOrLeadingZeroOnLastTKNumber = false; //08... or 09....
goto LFloat;
}
goto LIdCheck;
}
}
else
{
LFloat:
*pdbl = Js::NumberUtilities::StrToDbl(p, &pchT, likelyType, m_scriptContext->GetConfig()->IsESBigIntEnabled(), m_scriptContext->GetConfig()->IsESNumericSeparatorEnabled());
Assert(pchT == p || !Js::NumberUtilities::IsNan(*pdbl));
if (likelyType == LikelyNumberType::BigInt)
{
Assert(*pdbl == 0);
}
// fall through to LIdCheck
}
LIdCheck:
// https://tc39.github.io/ecma262/#sec-literals-numeric-literals
// The SourceCharacter immediately following a NumericLiteral must not be an IdentifierStart or DecimalDigit.
// For example : 3in is an error and not the two input elements 3 and in
// If a base was speficied, use the first character denoting the constant. In this case, pchT is pointing to the base specifier.
EncodedCharPtr startingLocation = baseSpecified ? pchT + 1 : pchT;
codepoint_t outChar = *startingLocation;
if (this->IsMultiUnitChar((OLECHAR)outChar))
{
outChar = this->template ReadRest<true>((OLECHAR)outChar, startingLocation, last);
}
if (this->charClassifier->IsIdStart(outChar))
{
this->RestoreMultiUnits(savedMultiUnits);
Error(ERRIdAfterLit);
}
// IsIdStart does not cover the unicode escape case. Try to read a unicode escape from the 'u' char.
if (*pchT == '\\')
{
startingLocation++; // TryReadEscape expects us to point to the 'u', and since it is by reference we need to do it beforehand.
if (TryReadEscape(startingLocation, m_pchLast, &outChar))
{
this->RestoreMultiUnits(savedMultiUnits);
Error(ERRIdAfterLit);
}
}
if (Js::NumberUtilities::IsDigit(*startingLocation))
{
this->RestoreMultiUnits(savedMultiUnits);
Error(ERRbadNumber);
}
return pchT;
}
template <typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::TryRescanRegExp()
{
EncodedCharPtr current = m_currentCharacter;
tokens result = RescanRegExp();
if (result == tkScanError)
m_currentCharacter = current;
return result;
}
template <typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::RescanRegExp()
{
#if DEBUG
switch (m_ptoken->tk)
{
case tkDiv:
Assert(m_currentCharacter == m_pchMinTok + 1);
break;
case tkAsgDiv:
Assert(m_currentCharacter == m_pchMinTok + 2);
break;
default:
AssertMsg(FALSE, "Who is calling RescanRegExp?");
break;
}
#endif //DEBUG
m_currentCharacter = m_pchMinTok;
if (*m_currentCharacter != '/')
Error(ERRnoSlash);
m_currentCharacter++;
tokens tk = tkNone;
{
ArenaAllocator alloc(_u("RescanRegExp"), m_parser->GetAllocator()->GetPageAllocator(), m_parser->GetAllocator()->outOfMemoryFunc);
tk = ScanRegExpConstant(&alloc);
}
return tk;
}
template <typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::RescanRegExpNoAST()
{
#if DEBUG
switch (m_ptoken->tk)
{
case tkDiv:
Assert(m_currentCharacter == m_pchMinTok + 1);
break;
case tkAsgDiv:
Assert(m_currentCharacter == m_pchMinTok + 2);
break;
default:
AssertMsg(FALSE, "Who is calling RescanRegExpNoParseTree?");
break;
}
#endif //DEBUG
m_currentCharacter = m_pchMinTok;
if (*m_currentCharacter != '/')
Error(ERRnoSlash);
m_currentCharacter++;
tokens tk = tkNone;
{
ArenaAllocator alloc(_u("RescanRegExp"), m_parser->GetAllocator()->GetPageAllocator(), m_parser->GetAllocator()->outOfMemoryFunc);
{
tk = ScanRegExpConstantNoAST(&alloc);
}
}
return tk;
}
template <typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::RescanRegExpTokenizer()
{
#if DEBUG
switch (m_ptoken->tk)
{
case tkDiv:
Assert(m_currentCharacter == m_pchMinTok + 1);
break;
case tkAsgDiv:
Assert(m_currentCharacter == m_pchMinTok + 2);
break;
default:
AssertMsg(FALSE, "Who is calling RescanRegExpNoParseTree?");
break;
}
#endif //DEBUG
m_currentCharacter = m_pchMinTok;
if (*m_currentCharacter != '/')
Error(ERRnoSlash);
m_currentCharacter++;
tokens tk = tkNone;
ThreadContext *threadContext = ThreadContext::GetContextForCurrentThread();
threadContext->EnsureRecycler();
Js::TempArenaAllocatorObject *alloc = threadContext->GetTemporaryAllocator(_u("RescanRegExp"));
TryFinally(
[&]() /* try block */
{
tk = this->ScanRegExpConstantNoAST(alloc->GetAllocator());
},
[&](bool /* hasException */) /* finally block */
{
threadContext->ReleaseTemporaryAllocator(alloc);
});
return tk;
}
template <typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::ScanRegExpConstant(ArenaAllocator* alloc)
{
PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackRegex);
// SEE ALSO: RegexHelper::PrimCompileDynamic()
#ifdef PROFILE_EXEC
m_scriptContext->ProfileBegin(Js::RegexCompilePhase);
#endif
ArenaAllocator* ctAllocator = alloc;
UnifiedRegex::StandardChars<EncodedChar>* standardEncodedChars = m_scriptContext->GetThreadContext()->GetStandardChars((EncodedChar*)0);
UnifiedRegex::StandardChars<char16>* standardChars = m_scriptContext->GetThreadContext()->GetStandardChars((char16*)0);
#if ENABLE_REGEX_CONFIG_OPTIONS
UnifiedRegex::DebugWriter *w = 0;
if (REGEX_CONFIG_FLAG(RegexDebug))
w = m_scriptContext->GetRegexDebugWriter();
if (REGEX_CONFIG_FLAG(RegexProfile))
m_scriptContext->GetRegexStatsDatabase()->BeginProfile();
#endif
UnifiedRegex::Node* root = 0;
charcount_t totalLen = 0, bodyChars = 0, totalChars = 0, bodyLen = 0;
UnifiedRegex::RegexFlags flags = UnifiedRegex::NoRegexFlags;
UnifiedRegex::Parser<EncodingPolicy, true> parser
( m_scriptContext
, ctAllocator
, standardEncodedChars
, standardChars
, this->IsUtf8()
#if ENABLE_REGEX_CONFIG_OPTIONS
, w
#endif
);
try
{
root = parser.ParseLiteral(m_currentCharacter, m_pchLast, bodyLen, totalLen, bodyChars, totalChars, flags);
}
catch (UnifiedRegex::ParseError e)
{
#ifdef PROFILE_EXEC
m_scriptContext->ProfileEnd(Js::RegexCompilePhase);
#endif
m_currentCharacter += e.encodedPos;
Error(e.error);
}
UnifiedRegex::RegexPattern* pattern;
if (m_parser->IsBackgroundParser())
{
// Avoid allocating pattern from recycler on background thread. The main thread will create the pattern
// and hook it to this parse node.
pattern = parser.template CompileProgram<false>(root, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, flags);
}
else
{
pattern = parser.template CompileProgram<true>(root, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, flags);
}
this->RestoreMultiUnits(this->m_cMultiUnits + parser.GetMultiUnits()); // m_currentCharacter changed, sync MultiUnits
return m_ptoken->SetRegex(pattern, m_parser);
}
template<typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::ScanRegExpConstantNoAST(ArenaAllocator* alloc)
{
PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackRegex);
ThreadContext *threadContext = m_scriptContext->GetThreadContext();
UnifiedRegex::StandardChars<EncodedChar>* standardEncodedChars = threadContext->GetStandardChars((EncodedChar*)0);
UnifiedRegex::StandardChars<char16>* standardChars = threadContext->GetStandardChars((char16*)0);
charcount_t totalLen = 0, bodyChars = 0, totalChars = 0, bodyLen = 0;
UnifiedRegex::Parser<EncodingPolicy, true> parser
( m_scriptContext
, alloc
, standardEncodedChars
, standardChars
, this->IsUtf8()
#if ENABLE_REGEX_CONFIG_OPTIONS
, 0
#endif
);
try
{
parser.ParseLiteralNoAST(m_currentCharacter, m_pchLast, bodyLen, totalLen, bodyChars, totalChars);
}
catch (UnifiedRegex::ParseError e)
{
m_currentCharacter += e.encodedPos;
Error(e.error);
// never reached
}
UnifiedRegex::RegexPattern* pattern = parser.template CompileProgram<false>(nullptr, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, UnifiedRegex::NoRegexFlags);
Assert(pattern == nullptr); // BuildAST == false, CompileProgram should return nullptr
this->RestoreMultiUnits(this->m_cMultiUnits + parser.GetMultiUnits()); // m_currentCharacter changed, sync MultiUnits
return (m_ptoken->tk = tkRegExp);
}
template<typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::ScanStringTemplateBegin(EncodedCharPtr *pp)
{
// String template must begin with a string constant followed by '`' or '${'
ScanStringConstant<true, true>('`', pp);
OLECHAR ch;
EncodedCharPtr last = m_pchLast;
ch = this->ReadFirst(*pp, last);
if (ch == '`')
{
// Simple string template - no substitutions
return tkStrTmplBasic;
}
else if (ch == '$')
{
ch = this->ReadFirst(*pp, last);
if (ch == '{')
{
// Next token after expr should be tkStrTmplMid or tkStrTmplEnd.
// In string template scanning mode, we expect the next char to be '}'
// and will treat it as the beginning of tkStrTmplEnd or tkStrTmplMid
m_fStringTemplateDepth++;
// Regular string template begin - next is first substitution
return tkStrTmplBegin;
}
}
// Error - make sure pointer stays at the last character of the error token instead of after it in the error case
(*pp)--;
return ScanError(m_currentCharacter, tkStrTmplBegin);
}
template<typename EncodingPolicy>
tokens Scanner<EncodingPolicy>::ScanStringTemplateMiddleOrEnd(EncodedCharPtr *pp)
{
// String template middle and end tokens must begin with a string constant
ScanStringConstant<true, true>('`', pp);
OLECHAR ch;
EncodedCharPtr last = m_pchLast;
ch = this->ReadFirst(*pp, last);
if (ch == '`')
{
// No longer in string template scanning mode
m_fStringTemplateDepth--;