Scan.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "ParserPch.h"
  6. /*****************************************************************************
  7. *
  8. * The following table speeds various tests of characters, such as whether
  9. * a given character can be part of an identifier, and so on.
  10. */
  11. int CountNewlines(LPCOLESTR psz)
  12. {
  13. int cln = 0;
  14. while (0 != *psz)
  15. {
  16. switch (*psz++)
  17. {
  18. case _u('\xD'):
  19. if (*psz == _u('\xA'))
  20. {
  21. ++psz;
  22. }
  23. // fall-through
  24. case _u('\xA'):
  25. cln++;
  26. break;
  27. }
  28. }
  29. return cln;
  30. }
  31. BOOL Token::IsKeyword() const
  32. {
  33. // keywords (but not future reserved words)
  34. return (tk <= tkYIELD);
  35. }
  36. tokens Token::SetRegex(UnifiedRegex::RegexPattern *const pattern, Parser *const parser)
  37. {
  38. Assert(parser);
  39. if(pattern)
  40. parser->RegisterRegexPattern(pattern);
  41. this->u.pattern = pattern;
  42. return tk = tkRegExp;
  43. }
  44. IdentPtr Token::CreateIdentifier(HashTbl * hashTbl)
  45. {
  46. Assert(this->u.pid == nullptr);
  47. if (this->u.pchMin)
  48. {
  49. Assert(IsIdentifier());
  50. IdentPtr pid = hashTbl->PidHashNameLen(this->u.pchMin, this->u.pchMin + this->u.length, this->u.length);
  51. this->u.pid = pid;
  52. return pid;
  53. }
  54. Assert(IsReservedWord());
  55. IdentPtr pid = hashTbl->PidFromTk(tk);
  56. this->u.pid = pid;
  57. return pid;
  58. }
  59. template <typename EncodingPolicy>
  60. Scanner<EncodingPolicy>::Scanner(Parser* parser, Token *ptoken, Js::ScriptContext* scriptContext)
  61. {
  62. Assert(ptoken);
  63. m_parser = parser;
  64. m_ptoken = ptoken;
  65. m_scriptContext = scriptContext;
  66. m_tempChBuf.m_pscanner = this;
  67. m_tempChBufSecondary.m_pscanner = this;
  68. this->charClassifier = scriptContext->GetCharClassifier();
  69. this->es6UnicodeMode = scriptContext->GetConfig()->IsES6UnicodeExtensionsEnabled();
  70. ClearStates();
  71. }
  72. template <typename EncodingPolicy>
  73. Scanner<EncodingPolicy>::~Scanner(void)
  74. {
  75. }
  76. template <typename EncodingPolicy>
  77. void Scanner<EncodingPolicy>::ClearStates()
  78. {
  79. m_pchBase = nullptr;
  80. m_pchLast = nullptr;
  81. m_pchMinLine = nullptr;
  82. m_pchMinTok = nullptr;
  83. m_currentCharacter = nullptr;
  84. m_pchPrevLine = nullptr;
  85. m_cMinTokMultiUnits = 0;
  86. m_cMinLineMultiUnits = 0;
  87. m_fStringTemplateDepth = 0;
  88. m_fHadEol = FALSE;
  89. m_fIsModuleCode = FALSE;
  90. m_doubleQuoteOnLastTkStrCon = FALSE;
  91. m_OctOrLeadingZeroOnLastTKNumber = false;
  92. m_EscapeOnLastTkStrCon = false;
  93. m_fNextStringTemplateIsTagged = false;
  94. m_DeferredParseFlags = ScanFlagNone;
  95. m_fYieldIsKeywordRegion = false;
  96. m_fAwaitIsKeywordRegion = false;
  97. m_line = 0;
  98. m_scanState = ScanStateNormal;
  99. m_ichMinError = 0;
  100. m_ichLimError = 0;
  101. m_startLine = 0;
  102. m_pchStartLine = NULL;
  103. m_iecpLimTokPrevious = (size_t)-1;
  104. m_ichLimTokPrevious = (charcount_t)-1;
  105. }
  106. template <typename EncodingPolicy>
  107. void Scanner<EncodingPolicy>::Clear()
  108. {
  109. EncodingPolicy::Clear();
  110. ClearStates();
  111. this->m_tempChBuf.Clear();
  112. this->m_tempChBufSecondary.Clear();
  113. }
  114. /*****************************************************************************
  115. *
  116. * Initializes the scanner to prepare to scan the given source text.
  117. */
  118. template <typename EncodingPolicy>
  119. void Scanner<EncodingPolicy>::SetText(EncodedCharPtr pszSrc, size_t offset, size_t length, charcount_t charOffset, bool isUtf8, ULONG grfscr, ULONG lineNumber)
  120. {
  121. // Save the start of the script and add the offset to get the point where we should start scanning.
  122. m_pchBase = pszSrc;
  123. m_pchLast = m_pchBase + offset + length;
  124. m_pchPrevLine = m_currentCharacter = m_pchMinLine = m_pchMinTok = pszSrc + offset;
  125. this->RestoreMultiUnits(offset - charOffset);
  126. // Absorb any byte order mark at the start
  127. if(offset == 0)
  128. {
  129. switch( this->PeekFull(m_currentCharacter, m_pchLast) )
  130. {
  131. case 0xFFEE: // "Opposite" endian BOM
  132. // We do not support big-endian encodings
  133. // fall-through
  134. case 0xFEFF: // "Correct" BOM
  135. this->template ReadFull<true>(m_currentCharacter, m_pchLast);
  136. break;
  137. }
  138. }
  139. m_line = lineNumber;
  140. m_startLine = lineNumber;
  141. m_pchStartLine = m_currentCharacter;
  142. m_ptoken->tk = tkNone;
  143. m_fIsModuleCode = (grfscr & fscrIsModuleCode) != 0;
  144. m_fHadEol = FALSE;
  145. m_DeferredParseFlags = ScanFlagNone;
  146. this->SetIsUtf8(isUtf8);
  147. }
  148. #if ENABLE_BACKGROUND_PARSING
  149. template <typename EncodingPolicy>
  150. void Scanner<EncodingPolicy>::PrepareForBackgroundParse(Js::ScriptContext *scriptContext)
  151. {
  152. scriptContext->GetThreadContext()->GetStandardChars((EncodedChar*)0);
  153. scriptContext->GetThreadContext()->GetStandardChars((char16*)0);
  154. }
  155. #endif
  156. //-----------------------------------------------------------------------------
  157. // Number of code points from 'first' up to, but not including the next
  158. // newline character, embedded NUL, or 'last', depending on which comes first.
  159. //
  160. // This is used to determine a length of BSTR, which can't contain a NUL character.
  161. //-----------------------------------------------------------------------------
  162. template <typename EncodingPolicy>
  163. charcount_t Scanner<EncodingPolicy>::LineLength(EncodedCharPtr first, EncodedCharPtr last, size_t* cb)
  164. {
  165. Assert(cb != nullptr);
  166. charcount_t result = 0;
  167. EncodedCharPtr p = first;
  168. for (;;)
  169. {
  170. EncodedCharPtr prev = p;
  171. switch( this->template ReadFull<false>(p, last) )
  172. {
  173. case kchNWL: // _C_NWL
  174. case kchRET:
  175. case kchLS:
  176. case kchPS:
  177. case kchNUL: // _C_NUL
  178. // p is now advanced past the line terminator character.
  179. // We need to know the number of bytes making up the line, not including the line terminator character.
  180. // To avoid subtracting a variable number of bytes because the line terminator characters are different
  181. // number of bytes long (plus there may be multiple valid encodings for these characters) just keep
  182. // track of the first byte of the line terminator character in prev.
  183. Assert(prev >= first);
  184. *cb = prev - first;
  185. return result;
  186. }
  187. result++;
  188. }
  189. }
  190. template <typename EncodingPolicy>
  191. charcount_t Scanner<EncodingPolicy>::UpdateLine(int32 &line, EncodedCharPtr start, EncodedCharPtr last, charcount_t ichStart, charcount_t ichEnd)
  192. {
  193. EncodedCharPtr p = start;
  194. charcount_t ich = ichStart;
  195. int32 current = line;
  196. charcount_t lastStart = ichStart;
  197. while (ich < ichEnd)
  198. {
  199. ich++;
  200. switch (this->template ReadFull<false>(p, last))
  201. {
  202. case kchRET:
  203. if (this->PeekFull(p, last) == kchNWL)
  204. {
  205. ich++;
  206. this->template ReadFull<false>(p, last);
  207. }
  208. // fall-through
  209. case kchNWL:
  210. case kchLS:
  211. case kchPS:
  212. current++;
  213. lastStart = ich;
  214. break;
  215. case kchNUL:
  216. goto done;
  217. }
  218. }
  219. done:
  220. line = current;
  221. return lastStart;
  222. }
  223. template <typename EncodingPolicy>
  224. bool Scanner<EncodingPolicy>::TryReadEscape(EncodedCharPtr& startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar)
  225. {
  226. Assert(outChar != nullptr);
  227. Assert(startingLocation <= endOfSource);
  228. EncodedCharPtr currentLocation = startingLocation;
  229. codepoint_t charToOutput = 0x0;
  230. // '\' is Assumed as there is only one caller
  231. // Read 'u' characters
  232. if (currentLocation >= endOfSource || this->ReadFirst(currentLocation, endOfSource) != 'u')
  233. {
  234. return false;
  235. }
  236. bool expectCurly = false;
  237. if (currentLocation < endOfSource && this->PeekFirst(currentLocation, endOfSource) == '{' && es6UnicodeMode)
  238. {
  239. expectCurly = true;
  240. // Move past the character
  241. this->ReadFirst(currentLocation, endOfSource);
  242. }
  243. uint i = 0;
  244. OLECHAR ch = 0;
  245. int hexValue = 0;
  246. uint maxHexDigits = (expectCurly ? MAXUINT32 : 4u);
  247. for(; i < maxHexDigits && currentLocation < endOfSource; i++)
  248. {
  249. if (!Js::NumberUtilities::FHexDigit(ch = this->ReadFirst(currentLocation, endOfSource), &hexValue))
  250. {
  251. break;
  252. }
  253. charToOutput = charToOutput * 0x10 + hexValue;
  254. if (charToOutput > 0x10FFFF)
  255. {
  256. return false;
  257. }
  258. }
  259. //At least 4 characters have to be read
  260. if (i == 0 || (i != 4 && !expectCurly))
  261. {
  262. return false;
  263. }
  264. Assert(expectCurly ? es6UnicodeMode : true);
  265. if (expectCurly && ch != '}')
  266. {
  267. return false;
  268. }
  269. *outChar = charToOutput;
  270. startingLocation = currentLocation;
  271. return true;
  272. }
  273. template <typename EncodingPolicy>
  274. template <bool bScan>
  275. bool Scanner<EncodingPolicy>::TryReadCodePointRest(codepoint_t lower, EncodedCharPtr& startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *outContainsMultiUnitChar)
  276. {
  277. Assert(outChar != nullptr);
  278. Assert(outContainsMultiUnitChar != nullptr);
  279. Assert(es6UnicodeMode);
  280. Assert(Js::NumberUtilities::IsSurrogateLowerPart(lower));
  281. EncodedCharPtr currentLocation = startingLocation;
  282. *outChar = lower;
  283. if (currentLocation < endOfSource)
  284. {
  285. size_t restorePoint = this->m_cMultiUnits;
  286. codepoint_t upper = this->template ReadFull<bScan>(currentLocation, endOfSource);
  287. if (Js::NumberUtilities::IsSurrogateUpperPart(upper))
  288. {
  289. *outChar = Js::NumberUtilities::SurrogatePairAsCodePoint(lower, upper);
  290. if (this->IsMultiUnitChar(static_cast<OLECHAR>(upper)))
  291. {
  292. *outContainsMultiUnitChar = true;
  293. }
  294. startingLocation = currentLocation;
  295. }
  296. else
  297. {
  298. this->RestoreMultiUnits(restorePoint);
  299. }
  300. }
  301. return true;
  302. }
  303. template <typename EncodingPolicy>
  304. template <bool bScan>
  305. inline bool Scanner<EncodingPolicy>::TryReadCodePoint(EncodedCharPtr &startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *hasEscape, bool *outContainsMultiUnitChar)
  306. {
  307. Assert(outChar != nullptr);
  308. Assert(outContainsMultiUnitChar != nullptr);
  309. if (startingLocation >= endOfSource)
  310. {
  311. return false;
  312. }
  313. codepoint_t ch = this->template ReadFull<bScan>(startingLocation, endOfSource);
  314. if (FBigChar(ch))
  315. {
  316. if (this->IsMultiUnitChar(static_cast<OLECHAR>(ch)))
  317. {
  318. *outContainsMultiUnitChar = true;
  319. }
  320. if (es6UnicodeMode && Js::NumberUtilities::IsSurrogateLowerPart(ch))
  321. {
  322. return TryReadCodePointRest<bScan>(ch, startingLocation, endOfSource, outChar, outContainsMultiUnitChar);
  323. }
  324. }
  325. else if (ch == '\\' && TryReadEscape(startingLocation, endOfSource, &ch))
  326. {
  327. *hasEscape = true;
  328. }
  329. *outChar = ch;
  330. return true;
  331. }
  332. template <typename EncodingPolicy>
  333. tokens Scanner<EncodingPolicy>::ScanIdentifier(bool identifyKwds, EncodedCharPtr *pp)
  334. {
  335. EncodedCharPtr p = *pp;
  336. EncodedCharPtr pchMin = p;
  337. // JS6 allows unicode characters in the form of \uxxxx escape sequences
  338. // to be part of the identifier.
  339. bool fHasEscape = false;
  340. bool fHasMultiChar = false;
  341. codepoint_t codePoint = INVALID_CODEPOINT;
  342. size_t multiUnitsBeforeLast = this->m_cMultiUnits;
  343. // Check if we started the id
  344. if (!TryReadCodePoint<true>(p, m_pchLast, &codePoint, &fHasEscape, &fHasMultiChar))
  345. {
  346. // If no chars. could be scanned as part of the identifier, return error.
  347. return tkScanError;
  348. }
  349. Assert(codePoint < 0x110000u);
  350. if (!charClassifier->IsIdStart(codePoint))
  351. {
  352. // Put back the last character
  353. this->RestoreMultiUnits(multiUnitsBeforeLast);
  354. // If no chars. could be scanned as part of the identifier, return error.
  355. return tkScanError;
  356. }
  357. return ScanIdentifierContinue(identifyKwds, fHasEscape, fHasMultiChar, pchMin, p, pp);
  358. }
  359. template <typename EncodingPolicy>
  360. BOOL Scanner<EncodingPolicy>::FastIdentifierContinue(EncodedCharPtr&p, EncodedCharPtr last)
  361. {
  362. if (EncodingPolicy::MultiUnitEncoding)
  363. {
  364. while (p < last)
  365. {
  366. EncodedChar currentChar = *p;
  367. if (this->IsMultiUnitChar(currentChar))
  368. {
  369. // multi unit character, we may not have reach the end yet
  370. return FALSE;
  371. }
  372. Assert(currentChar != '\\' || !charClassifier->IsIdContinueFast<false>(currentChar));
  373. if (!charClassifier->IsIdContinueFast<false>(currentChar))
  374. {
  375. // only reach the end of the identifier if it is not the start of an escape sequence
  376. return currentChar != '\\';
  377. }
  378. p++;
  379. }
  380. // We have reach the end of the identifier.
  381. return TRUE;
  382. }
  383. // Not fast path for non multi unit encoding
  384. return false;
  385. }
  386. template <typename EncodingPolicy>
  387. tokens Scanner<EncodingPolicy>::ScanIdentifierContinue(bool identifyKwds, bool fHasEscape, bool fHasMultiChar,
  388. EncodedCharPtr pchMin, EncodedCharPtr p, EncodedCharPtr *pp)
  389. {
  390. EncodedCharPtr last = m_pchLast;
  391. while (true)
  392. {
  393. // Fast path for utf8, non-multi unit char and not escape
  394. if (FastIdentifierContinue(p, last))
  395. {
  396. break;
  397. }
  398. // Slow path that has to deal with multi unit encoding
  399. codepoint_t codePoint = INVALID_CODEPOINT;
  400. EncodedCharPtr pchBeforeLast = p;
  401. size_t multiUnitsBeforeLast = this->m_cMultiUnits;
  402. if (TryReadCodePoint<true>(p, last, &codePoint, &fHasEscape, &fHasMultiChar))
  403. {
  404. Assert(codePoint < 0x110000u);
  405. if (charClassifier->IsIdContinue(codePoint))
  406. {
  407. continue;
  408. }
  409. }
  410. // Put back the last character
  411. p = pchBeforeLast;
  412. this->RestoreMultiUnits(multiUnitsBeforeLast);
  413. break;
  414. }
  415. m_lastIdentifierHasEscape = fHasEscape;
  416. Assert(p - pchMin > 0 && p - pchMin <= LONG_MAX);
  417. *pp = p;
  418. if (!identifyKwds)
  419. {
  420. return tkID;
  421. }
  422. // UTF16 Scanner are only for syntax coloring, so it shouldn't come here.
  423. if (EncodingPolicy::MultiUnitEncoding && !fHasMultiChar && !fHasEscape)
  424. {
  425. Assert(sizeof(EncodedChar) == 1);
  426. // If there are no escape, that the main scan loop would have found the keyword already
  427. // So we can just assume it is an ID
  428. DebugOnly(int32 cch = UnescapeToTempBuf(pchMin, p));
  429. DebugOnly(tokens tk = Ident::TkFromNameLen(m_tempChBuf.m_prgch, cch, IsStrictMode()));
  430. Assert(tk == tkID || (tk == tkYIELD && !this->YieldIsKeyword()) || (tk == tkAWAIT && !this->AwaitIsKeyword()));
  431. m_ptoken->SetIdentifier(reinterpret_cast<const char *>(pchMin), (int32)(p - pchMin));
  432. return tkID;
  433. }
  434. IdentPtr pid = PidOfIdentiferAt(pchMin, p, fHasEscape, fHasMultiChar);
  435. m_ptoken->SetIdentifier(pid);
  436. if (!fHasEscape)
  437. {
  438. // If it doesn't have escape, then Scan() should have taken care of keywords (except
  439. // yield if m_fYieldIsKeyword is false, in which case yield is treated as an identifier, and except
  440. // await if m_fAwaitIsKeyword is false, in which case await is treated as an identifier).
  441. // We don't have to check if the name is reserved word and return it as an Identifier
  442. Assert(pid->Tk(IsStrictMode()) == tkID
  443. || (pid->Tk(IsStrictMode()) == tkYIELD && !this->YieldIsKeyword())
  444. || (pid->Tk(IsStrictMode()) == tkAWAIT && !this->AwaitIsKeyword()));
  445. return tkID;
  446. }
  447. tokens tk = pid->Tk(IsStrictMode());
  448. return tk == tkID || (tk == tkYIELD && !this->YieldIsKeyword()) || (tk == tkAWAIT && !this->AwaitIsKeyword()) ? tkID : tkNone;
  449. }
  450. template <typename EncodingPolicy>
  451. IdentPtr Scanner<EncodingPolicy>::PidAt(size_t iecpMin, size_t iecpLim)
  452. {
  453. Assert(iecpMin < AdjustedLength() && iecpLim <= AdjustedLength() && iecpLim > iecpMin);
  454. return PidOfIdentiferAt(m_pchBase + iecpMin, m_pchBase + iecpLim);
  455. }
  456. template <typename EncodingPolicy>
  457. uint32 Scanner<EncodingPolicy>::UnescapeToTempBuf(EncodedCharPtr p, EncodedCharPtr last)
  458. {
  459. m_tempChBuf.Reset();
  460. while( p < last )
  461. {
  462. codepoint_t codePoint;
  463. bool hasEscape, isMultiChar;
  464. bool gotCodePoint = TryReadCodePoint<false>(p, last, &codePoint, &hasEscape, &isMultiChar);
  465. Assert(gotCodePoint);
  466. Assert(codePoint < 0x110000);
  467. if (codePoint < 0x10000)
  468. {
  469. m_tempChBuf.AppendCh((OLECHAR)codePoint);
  470. }
  471. else
  472. {
  473. char16 lower, upper;
  474. Js::NumberUtilities::CodePointAsSurrogatePair(codePoint, &lower, &upper);
  475. m_tempChBuf.AppendCh(lower);
  476. m_tempChBuf.AppendCh(upper);
  477. }
  478. }
  479. return m_tempChBuf.m_ichCur;
  480. }
  481. template <typename EncodingPolicy>
  482. IdentPtr Scanner<EncodingPolicy>::PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last)
  483. {
  484. int32 cch = UnescapeToTempBuf(p, last);
  485. return this->GetHashTbl()->PidHashNameLen(m_tempChBuf.m_prgch, cch);
  486. }
  487. template <typename EncodingPolicy>
  488. IdentPtr Scanner<EncodingPolicy>::PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last, bool fHadEscape, bool fHasMultiChar)
  489. {
  490. // If there is an escape sequence in the JS6 identifier or it is a UTF8
  491. // source then we have to convert it to the equivalent char so we use a
  492. // buffer for translation.
  493. if ((EncodingPolicy::MultiUnitEncoding && fHasMultiChar) || fHadEscape)
  494. {
  495. return PidOfIdentiferAt(p, last);
  496. }
  497. else if (EncodingPolicy::MultiUnitEncoding)
  498. {
  499. Assert(sizeof(EncodedChar) == 1);
  500. return this->GetHashTbl()->PidHashNameLen(reinterpret_cast<const char *>(p), reinterpret_cast<const char *>(last), (int32)(last - p));
  501. }
  502. else
  503. {
  504. Assert(sizeof(EncodedChar) == 2);
  505. return this->GetHashTbl()->PidHashNameLen(reinterpret_cast< const char16 * >(p), (int32)(last - p));
  506. }
  507. }
  508. template <typename EncodingPolicy>
  509. typename Scanner<EncodingPolicy>::EncodedCharPtr Scanner<EncodingPolicy>::FScanNumber(EncodedCharPtr p, double *pdbl, LikelyNumberType& likelyType, size_t savedMultiUnits)
  510. {
  511. EncodedCharPtr last = m_pchLast;
  512. EncodedCharPtr pchT = nullptr;
  513. bool baseSpecified = false;
  514. likelyType = LikelyNumberType::Int;
  515. // Reset
  516. m_OctOrLeadingZeroOnLastTKNumber = false;
  517. auto baseSpecifierCheck = [&pchT, &pdbl, p, &baseSpecified]()
  518. {
  519. if (pchT == p + 2)
  520. {
  521. // An octal token '0' was followed by a base specifier: /0[xXoObB]/
  522. // This literal can no longer be a double
  523. *pdbl = 0;
  524. // Advance the character pointer to the base specifier
  525. pchT = p + 1;
  526. // Set the flag so we know to offset the potential identifier search after the literal
  527. baseSpecified = true;
  528. }
  529. };
  530. if ('0' == this->PeekFirst(p, last))
  531. {
  532. switch(this->PeekFirst(p + 1, last))
  533. {
  534. case '.':
  535. case 'e':
  536. case 'E':
  537. case 'n':
  538. likelyType = LikelyNumberType::Double;
  539. // Floating point
  540. goto LFloat;
  541. case 'x':
  542. case 'X':
  543. // Hex
  544. *pdbl = Js::NumberUtilities::DblFromHex(p + 2, &pchT, m_scriptContext->GetConfig()->IsESNumericSeparatorEnabled());
  545. baseSpecifierCheck();
  546. goto LIdCheck;
  547. case 'o':
  548. case 'O':
  549. // Octal
  550. *pdbl = Js::NumberUtilities::DblFromOctal(p + 2, &pchT, m_scriptContext->GetConfig()->IsESNumericSeparatorEnabled());
  551. baseSpecifierCheck();
  552. goto LIdCheck;
  553. case 'b':
  554. case 'B':
  555. // Binary
  556. *pdbl = Js::NumberUtilities::DblFromBinary(p + 2, &pchT, m_scriptContext->GetConfig()->IsESNumericSeparatorEnabled());
  557. baseSpecifierCheck();
  558. goto LIdCheck;
  559. default:
  560. // Octal
  561. *pdbl = Js::NumberUtilities::DblFromOctal(p, &pchT);
  562. Assert(pchT > p);
  563. #if !SOURCERELEASE
  564. // If an octal literal is malformed then it is in fact a decimal literal.
  565. #endif // !SOURCERELEASE
  566. if(*pdbl != 0 || pchT > p + 1)
  567. m_OctOrLeadingZeroOnLastTKNumber = true; //report as an octal or hex for JSON when leading 0. Just '0' is ok
  568. switch (*pchT)
  569. {
  570. case '8':
  571. case '9':
  572. // case 'e':
  573. // case 'E':
  574. // case '.':
  575. m_OctOrLeadingZeroOnLastTKNumber = false; //08... or 09....
  576. goto LFloat;
  577. }
  578. goto LIdCheck;
  579. }
  580. }
  581. else
  582. {
  583. LFloat:
  584. *pdbl = Js::NumberUtilities::StrToDbl(p, &pchT, likelyType, m_scriptContext->GetConfig()->IsESBigIntEnabled(), m_scriptContext->GetConfig()->IsESNumericSeparatorEnabled());
  585. Assert(pchT == p || !Js::NumberUtilities::IsNan(*pdbl));
  586. if (likelyType == LikelyNumberType::BigInt)
  587. {
  588. Assert(*pdbl == 0);
  589. }
  590. // fall through to LIdCheck
  591. }
  592. LIdCheck:
  593. // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
  594. // The SourceCharacter immediately following a NumericLiteral must not be an IdentifierStart or DecimalDigit.
  595. // For example : 3in is an error and not the two input elements 3 and in
  596. // If a base was speficied, use the first character denoting the constant. In this case, pchT is pointing to the base specifier.
  597. EncodedCharPtr startingLocation = baseSpecified ? pchT + 1 : pchT;
  598. codepoint_t outChar = *startingLocation;
  599. if (this->IsMultiUnitChar((OLECHAR)outChar))
  600. {
  601. outChar = this->template ReadRest<true>((OLECHAR)outChar, startingLocation, last);
  602. }
  603. if (this->charClassifier->IsIdStart(outChar))
  604. {
  605. this->RestoreMultiUnits(savedMultiUnits);
  606. Error(ERRIdAfterLit);
  607. }
  608. // IsIdStart does not cover the unicode escape case. Try to read a unicode escape from the 'u' char.
  609. if (*pchT == '\\')
  610. {
  611. startingLocation++; // TryReadEscape expects us to point to the 'u', and since it is by reference we need to do it beforehand.
  612. if (TryReadEscape(startingLocation, m_pchLast, &outChar))
  613. {
  614. this->RestoreMultiUnits(savedMultiUnits);
  615. Error(ERRIdAfterLit);
  616. }
  617. }
  618. if (Js::NumberUtilities::IsDigit(*startingLocation))
  619. {
  620. this->RestoreMultiUnits(savedMultiUnits);
  621. Error(ERRbadNumber);
  622. }
  623. return pchT;
  624. }
  625. template <typename EncodingPolicy>
  626. tokens Scanner<EncodingPolicy>::TryRescanRegExp()
  627. {
  628. EncodedCharPtr current = m_currentCharacter;
  629. tokens result = RescanRegExp();
  630. if (result == tkScanError)
  631. m_currentCharacter = current;
  632. return result;
  633. }
  634. template <typename EncodingPolicy>
  635. tokens Scanner<EncodingPolicy>::RescanRegExp()
  636. {
  637. #if DEBUG
  638. switch (m_ptoken->tk)
  639. {
  640. case tkDiv:
  641. Assert(m_currentCharacter == m_pchMinTok + 1);
  642. break;
  643. case tkAsgDiv:
  644. Assert(m_currentCharacter == m_pchMinTok + 2);
  645. break;
  646. default:
  647. AssertMsg(FALSE, "Who is calling RescanRegExp?");
  648. break;
  649. }
  650. #endif //DEBUG
  651. m_currentCharacter = m_pchMinTok;
  652. if (*m_currentCharacter != '/')
  653. Error(ERRnoSlash);
  654. m_currentCharacter++;
  655. tokens tk = tkNone;
  656. {
  657. ArenaAllocator alloc(_u("RescanRegExp"), m_parser->GetAllocator()->GetPageAllocator(), m_parser->GetAllocator()->outOfMemoryFunc);
  658. tk = ScanRegExpConstant(&alloc);
  659. }
  660. return tk;
  661. }
  662. template <typename EncodingPolicy>
  663. tokens Scanner<EncodingPolicy>::RescanRegExpNoAST()
  664. {
  665. #if DEBUG
  666. switch (m_ptoken->tk)
  667. {
  668. case tkDiv:
  669. Assert(m_currentCharacter == m_pchMinTok + 1);
  670. break;
  671. case tkAsgDiv:
  672. Assert(m_currentCharacter == m_pchMinTok + 2);
  673. break;
  674. default:
  675. AssertMsg(FALSE, "Who is calling RescanRegExpNoParseTree?");
  676. break;
  677. }
  678. #endif //DEBUG
  679. m_currentCharacter = m_pchMinTok;
  680. if (*m_currentCharacter != '/')
  681. Error(ERRnoSlash);
  682. m_currentCharacter++;
  683. tokens tk = tkNone;
  684. {
  685. ArenaAllocator alloc(_u("RescanRegExp"), m_parser->GetAllocator()->GetPageAllocator(), m_parser->GetAllocator()->outOfMemoryFunc);
  686. {
  687. tk = ScanRegExpConstantNoAST(&alloc);
  688. }
  689. }
  690. return tk;
  691. }
  692. template <typename EncodingPolicy>
  693. tokens Scanner<EncodingPolicy>::RescanRegExpTokenizer()
  694. {
  695. #if DEBUG
  696. switch (m_ptoken->tk)
  697. {
  698. case tkDiv:
  699. Assert(m_currentCharacter == m_pchMinTok + 1);
  700. break;
  701. case tkAsgDiv:
  702. Assert(m_currentCharacter == m_pchMinTok + 2);
  703. break;
  704. default:
  705. AssertMsg(FALSE, "Who is calling RescanRegExpNoParseTree?");
  706. break;
  707. }
  708. #endif //DEBUG
  709. m_currentCharacter = m_pchMinTok;
  710. if (*m_currentCharacter != '/')
  711. Error(ERRnoSlash);
  712. m_currentCharacter++;
  713. tokens tk = tkNone;
  714. ThreadContext *threadContext = ThreadContext::GetContextForCurrentThread();
  715. threadContext->EnsureRecycler();
  716. Js::TempArenaAllocatorObject *alloc = threadContext->GetTemporaryAllocator(_u("RescanRegExp"));
  717. TryFinally(
  718. [&]() /* try block */
  719. {
  720. tk = this->ScanRegExpConstantNoAST(alloc->GetAllocator());
  721. },
  722. [&](bool /* hasException */) /* finally block */
  723. {
  724. threadContext->ReleaseTemporaryAllocator(alloc);
  725. });
  726. return tk;
  727. }
  728. template <typename EncodingPolicy>
  729. tokens Scanner<EncodingPolicy>::ScanRegExpConstant(ArenaAllocator* alloc)
  730. {
  731. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackRegex);
  732. // SEE ALSO: RegexHelper::PrimCompileDynamic()
  733. #ifdef PROFILE_EXEC
  734. m_scriptContext->ProfileBegin(Js::RegexCompilePhase);
  735. #endif
  736. ArenaAllocator* ctAllocator = alloc;
  737. UnifiedRegex::StandardChars<EncodedChar>* standardEncodedChars = m_scriptContext->GetThreadContext()->GetStandardChars((EncodedChar*)0);
  738. UnifiedRegex::StandardChars<char16>* standardChars = m_scriptContext->GetThreadContext()->GetStandardChars((char16*)0);
  739. #if ENABLE_REGEX_CONFIG_OPTIONS
  740. UnifiedRegex::DebugWriter *w = 0;
  741. if (REGEX_CONFIG_FLAG(RegexDebug))
  742. w = m_scriptContext->GetRegexDebugWriter();
  743. if (REGEX_CONFIG_FLAG(RegexProfile))
  744. m_scriptContext->GetRegexStatsDatabase()->BeginProfile();
  745. #endif
  746. UnifiedRegex::Node* root = 0;
  747. charcount_t totalLen = 0, bodyChars = 0, totalChars = 0, bodyLen = 0;
  748. UnifiedRegex::RegexFlags flags = UnifiedRegex::NoRegexFlags;
  749. UnifiedRegex::Parser<EncodingPolicy, true> parser
  750. ( m_scriptContext
  751. , ctAllocator
  752. , standardEncodedChars
  753. , standardChars
  754. , this->IsUtf8()
  755. #if ENABLE_REGEX_CONFIG_OPTIONS
  756. , w
  757. #endif
  758. );
  759. try
  760. {
  761. root = parser.ParseLiteral(m_currentCharacter, m_pchLast, bodyLen, totalLen, bodyChars, totalChars, flags);
  762. }
  763. catch (UnifiedRegex::ParseError e)
  764. {
  765. #ifdef PROFILE_EXEC
  766. m_scriptContext->ProfileEnd(Js::RegexCompilePhase);
  767. #endif
  768. m_currentCharacter += e.encodedPos;
  769. Error(e.error);
  770. }
  771. UnifiedRegex::RegexPattern* pattern;
  772. if (m_parser->IsBackgroundParser())
  773. {
  774. // Avoid allocating pattern from recycler on background thread. The main thread will create the pattern
  775. // and hook it to this parse node.
  776. pattern = parser.template CompileProgram<false>(root, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, flags);
  777. }
  778. else
  779. {
  780. pattern = parser.template CompileProgram<true>(root, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, flags);
  781. }
  782. this->RestoreMultiUnits(this->m_cMultiUnits + parser.GetMultiUnits()); // m_currentCharacter changed, sync MultiUnits
  783. return m_ptoken->SetRegex(pattern, m_parser);
  784. }
  785. template<typename EncodingPolicy>
  786. tokens Scanner<EncodingPolicy>::ScanRegExpConstantNoAST(ArenaAllocator* alloc)
  787. {
  788. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackRegex);
  789. ThreadContext *threadContext = m_scriptContext->GetThreadContext();
  790. UnifiedRegex::StandardChars<EncodedChar>* standardEncodedChars = threadContext->GetStandardChars((EncodedChar*)0);
  791. UnifiedRegex::StandardChars<char16>* standardChars = threadContext->GetStandardChars((char16*)0);
  792. charcount_t totalLen = 0, bodyChars = 0, totalChars = 0, bodyLen = 0;
  793. UnifiedRegex::Parser<EncodingPolicy, true> parser
  794. ( m_scriptContext
  795. , alloc
  796. , standardEncodedChars
  797. , standardChars
  798. , this->IsUtf8()
  799. #if ENABLE_REGEX_CONFIG_OPTIONS
  800. , 0
  801. #endif
  802. );
  803. try
  804. {
  805. parser.ParseLiteralNoAST(m_currentCharacter, m_pchLast, bodyLen, totalLen, bodyChars, totalChars);
  806. }
  807. catch (UnifiedRegex::ParseError e)
  808. {
  809. m_currentCharacter += e.encodedPos;
  810. Error(e.error);
  811. // never reached
  812. }
  813. UnifiedRegex::RegexPattern* pattern = parser.template CompileProgram<false>(nullptr, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, UnifiedRegex::NoRegexFlags);
  814. Assert(pattern == nullptr); // BuildAST == false, CompileProgram should return nullptr
  815. this->RestoreMultiUnits(this->m_cMultiUnits + parser.GetMultiUnits()); // m_currentCharacter changed, sync MultiUnits
  816. return (m_ptoken->tk = tkRegExp);
  817. }
  818. template<typename EncodingPolicy>
  819. tokens Scanner<EncodingPolicy>::ScanStringTemplateBegin(EncodedCharPtr *pp)
  820. {
  821. // String template must begin with a string constant followed by '`' or '${'
  822. ScanStringConstant<true, true>('`', pp);
  823. OLECHAR ch;
  824. EncodedCharPtr last = m_pchLast;
  825. ch = this->ReadFirst(*pp, last);
  826. if (ch == '`')
  827. {
  828. // Simple string template - no substitutions
  829. return tkStrTmplBasic;
  830. }
  831. else if (ch == '$')
  832. {
  833. ch = this->ReadFirst(*pp, last);
  834. if (ch == '{')
  835. {
  836. // Next token after expr should be tkStrTmplMid or tkStrTmplEnd.
  837. // In string template scanning mode, we expect the next char to be '}'
  838. // and will treat it as the beginning of tkStrTmplEnd or tkStrTmplMid
  839. m_fStringTemplateDepth++;
  840. // Regular string template begin - next is first substitution
  841. return tkStrTmplBegin;
  842. }
  843. }
  844. // Error - make sure pointer stays at the last character of the error token instead of after it in the error case
  845. (*pp)--;
  846. return ScanError(m_currentCharacter, tkStrTmplBegin);
  847. }
  848. template<typename EncodingPolicy>
  849. tokens Scanner<EncodingPolicy>::ScanStringTemplateMiddleOrEnd(EncodedCharPtr *pp)
  850. {
  851. // String template middle and end tokens must begin with a string constant
  852. ScanStringConstant<true, true>('`', pp);
  853. OLECHAR ch;
  854. EncodedCharPtr last = m_pchLast;
  855. ch = this->ReadFirst(*pp, last);
  856. if (ch == '`')
  857. {
  858. // No longer in string template scanning mode
  859. m_fStringTemplateDepth--;
  860. // This is the last part of the template ...`
  861. return tkStrTmplEnd;
  862. }
  863. else if (ch == '$')
  864. {
  865. ch = this->ReadFirst(*pp, last);
  866. if (ch == '{')
  867. {
  868. // This is just another middle part of the template }...${
  869. return tkStrTmplMid;
  870. }
  871. }
  872. // Error - make sure pointer stays at the last character of the error token instead of after it in the error case
  873. (*pp)--;
  874. return ScanError(m_currentCharacter, tkStrTmplEnd);
  875. }
  876. /*****************************************************************************
  877. *
  878. * Parses a string constant. Note that the string value is stored in
  879. * a volatile buffer (or allocated on the heap if too long), and thus
  880. * the string should be saved off before the next token is scanned.
  881. */
  882. template<typename EncodingPolicy>
  883. template<bool stringTemplateMode, bool createRawString>
  884. tokens Scanner<EncodingPolicy>::ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp)
  885. {
  886. static_assert((stringTemplateMode && createRawString) || (!stringTemplateMode && !createRawString), "stringTemplateMode and createRawString must have the same value");
  887. OLECHAR ch, c, rawch;
  888. int wT;
  889. EncodedCharPtr p = *pp;
  890. EncodedCharPtr last = m_pchLast;
  891. // Reset
  892. m_OctOrLeadingZeroOnLastTKNumber = false;
  893. m_EscapeOnLastTkStrCon = FALSE;
  894. m_tempChBuf.Reset();
  895. // Use template parameter to gate raw string creation.
  896. // If createRawString is false, all these operations should be no-ops
  897. if (createRawString)
  898. {
  899. m_tempChBufSecondary.Reset();
  900. }
  901. for (;;)
  902. {
  903. switch ((rawch = ch = this->ReadFirst(p, last)))
  904. {
  905. case kchRET:
  906. if (stringTemplateMode)
  907. {
  908. if (this->PeekFirst(p, last) == kchNWL)
  909. {
  910. // Eat the <LF> char, ignore return
  911. this->ReadFirst(p, last);
  912. }
  913. // Both <CR> and <CR><LF> are normalized to <LF> in template cooked and raw values
  914. ch = rawch = kchNWL;
  915. }
  916. // Fall through
  917. case kchNWL:
  918. if (stringTemplateMode)
  919. {
  920. // Notify the scanner to update current line, number of lines etc
  921. NotifyScannedNewLine();
  922. // We haven't updated m_currentCharacter yet, so make sure the MinLine info is correct in case we error out.
  923. m_pchMinLine = p;
  924. break;
  925. }
  926. m_currentCharacter = p - 1;
  927. Error(ERRnoStrEnd);
  928. case '"':
  929. case '\'':
  930. if (ch == delim)
  931. goto LBreak;
  932. break;
  933. case '`':
  934. // In string template scan mode, don't consume the '`' - we need to differentiate
  935. // between a closed string template and the expression open sequence - ${
  936. if (stringTemplateMode)
  937. {
  938. p--;
  939. goto LBreak;
  940. }
  941. // If we aren't scanning for a string template, do the default thing
  942. goto LMainDefault;
  943. case '$':
  944. // If we are parsing a string literal part of a string template, ${ indicates we need to switch
  945. // to parsing an expression.
  946. if (stringTemplateMode && this->PeekFirst(p, last) == '{')
  947. {
  948. // Rewind to the $ and return
  949. p--;
  950. goto LBreak;
  951. }
  952. // If we aren't scanning for a string template, do the default thing
  953. goto LMainDefault;
  954. case kchNUL:
  955. if (p > last)
  956. {
  957. m_currentCharacter = p - 1;
  958. Error(ERRnoStrEnd);
  959. }
  960. break;
  961. default:
  962. LMainDefault:
  963. if (this->IsMultiUnitChar(ch))
  964. {
  965. rawch = ch = this->template ReadRest<true>(ch, p, last);
  966. }
  967. break;
  968. case kchBSL:
  969. // In raw mode '\\' is not an escape character, just add the char into the raw buffer.
  970. m_tempChBufSecondary.template AppendCh<createRawString>(ch);
  971. m_EscapeOnLastTkStrCon=TRUE;
  972. // In raw mode, we append the raw char itself and not the escaped value so save the char.
  973. rawch = ch = this->ReadFirst(p, last);
  974. codepoint_t codePoint = 0;
  975. uint errorType = (uint)ERRbadHexDigit;
  976. switch (ch)
  977. {
  978. case 'b':
  979. ch = 0x08;
  980. break;
  981. case 't':
  982. ch = 0x09;
  983. break;
  984. case 'v':
  985. ch = 0x0B; //Only in ES5 mode
  986. break; //same as default
  987. case 'n':
  988. ch = 0x0A;
  989. break;
  990. case 'f':
  991. ch = 0x0C;
  992. break;
  993. case 'r':
  994. ch = 0x0D;
  995. break;
  996. case 'x':
  997. // Insert the 'x' here before jumping to parse the hex digits.
  998. m_tempChBufSecondary.template AppendCh<createRawString>(ch);
  999. // 2 hex digits
  1000. ch = 0;
  1001. goto LTwoHex;
  1002. case 'u':
  1003. // Raw string just inserts a 'u' here.
  1004. m_tempChBufSecondary.template AppendCh<createRawString>(ch);
  1005. ch = 0;
  1006. if (Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1007. goto LFourHex;
  1008. else if (c != '{' || !this->es6UnicodeMode)
  1009. goto ReturnScanError;
  1010. Assert(c == '{');
  1011. // c should definitely be a '{' which should be appended to the raw string.
  1012. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1013. //At least one digit is expected
  1014. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1015. {
  1016. goto ReturnScanError;
  1017. }
  1018. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1019. codePoint = static_cast<codepoint_t>(wT);
  1020. while(Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1021. {
  1022. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1023. codePoint <<= 4;
  1024. codePoint += static_cast<codepoint_t>(wT);
  1025. if (codePoint > 0x10FFFF)
  1026. {
  1027. errorType = (uint)ERRInvalidCodePoint;
  1028. goto ReturnScanError;
  1029. }
  1030. }
  1031. if (c != '}')
  1032. {
  1033. errorType = (uint)ERRMissingCurlyBrace;
  1034. goto ReturnScanError;
  1035. }
  1036. Assert(codePoint <= 0x10FFFF);
  1037. if (codePoint >= 0x10000)
  1038. {
  1039. OLECHAR lower = 0;
  1040. Js::NumberUtilities::CodePointAsSurrogatePair(codePoint, &lower, &ch);
  1041. m_tempChBuf.AppendCh(lower);
  1042. }
  1043. else
  1044. {
  1045. ch = (char16)codePoint;
  1046. }
  1047. // In raw mode we want the last hex character or the closing curly. c should hold one or the other.
  1048. if (createRawString)
  1049. rawch = c;
  1050. break;
  1051. LFourHex:
  1052. codePoint = 0x0;
  1053. // Append first hex digit character to the raw string.
  1054. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1055. codePoint += static_cast<codepoint_t>(wT * 0x1000);
  1056. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1057. goto ReturnScanError;
  1058. // Append fourth (or second) hex digit character to the raw string.
  1059. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1060. codePoint += static_cast<codepoint_t>(wT * 0x0100);
  1061. LTwoHex:
  1062. // This code path doesn't expect curly.
  1063. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1064. goto ReturnScanError;
  1065. // Append first hex digit character to the raw string.
  1066. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1067. codePoint += static_cast<codepoint_t>(wT * 0x0010);
  1068. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1069. goto ReturnScanError;
  1070. codePoint += static_cast<codepoint_t>(wT);
  1071. // In raw mode we want the last hex character or the closing curly. c should hold one or the other.
  1072. if (createRawString)
  1073. rawch = c;
  1074. if (codePoint < 0x10000)
  1075. {
  1076. ch = static_cast<OLECHAR>(codePoint);
  1077. }
  1078. else
  1079. {
  1080. goto ReturnScanError;
  1081. }
  1082. break;
  1083. case '0':
  1084. case '1':
  1085. case '2':
  1086. case '3':
  1087. // 1 to 3 octal digits
  1088. ch -= '0';
  1089. // Octal escape sequences are not allowed inside string template literals
  1090. if (stringTemplateMode)
  1091. {
  1092. c = this->PeekFirst(p, last);
  1093. if (ch != 0 || (c >= '0' && c <= '7'))
  1094. {
  1095. errorType = (uint)ERRES5NoOctal;
  1096. goto ReturnScanError;
  1097. }
  1098. break;
  1099. }
  1100. wT = (c = this->ReadFirst(p, last)) - '0';
  1101. if ((char16)wT > 7)
  1102. {
  1103. if (ch != 0 || ((char16)wT <= 9))
  1104. {
  1105. m_OctOrLeadingZeroOnLastTKNumber = true;
  1106. }
  1107. p--;
  1108. break;
  1109. }
  1110. m_OctOrLeadingZeroOnLastTKNumber = true;
  1111. ch = static_cast< OLECHAR >(ch * 8 + wT);
  1112. goto LOneOctal;
  1113. case '4':
  1114. case '5':
  1115. case '6':
  1116. case '7':
  1117. // 1 to 2 octal digits
  1118. // Octal escape sequences are not allowed inside string template literals
  1119. if (stringTemplateMode)
  1120. {
  1121. errorType = (uint)ERRES5NoOctal;
  1122. goto ReturnScanError;
  1123. }
  1124. ch -= '0';
  1125. m_OctOrLeadingZeroOnLastTKNumber = true;
  1126. LOneOctal:
  1127. wT = (c = this->ReadFirst(p, last)) - '0';
  1128. if ((char16)wT > 7)
  1129. {
  1130. p--;
  1131. break;
  1132. }
  1133. ch = static_cast< OLECHAR >(ch * 8 + wT);
  1134. break;
  1135. case kchRET: // 0xD
  1136. if (stringTemplateMode)
  1137. {
  1138. // If this is \<CR><LF> we can eat the <LF> right now
  1139. if (this->PeekFirst(p, last) == kchNWL)
  1140. {
  1141. // Eat the <LF> char, ignore return
  1142. this->ReadFirst(p, last);
  1143. }
  1144. // Both \<CR> and \<CR><LF> are normalized to \<LF> in template raw string
  1145. rawch = kchNWL;
  1146. }
  1147. case kchLS: // 0x2028, classifies as new line
  1148. case kchPS: // 0x2029, classifies as new line
  1149. case kchNWL: // 0xA
  1150. LEcmaEscapeLineBreak:
  1151. if (stringTemplateMode)
  1152. {
  1153. // We're going to ignore the line continuation tokens for the cooked strings, but we need to append the token for raw strings
  1154. m_tempChBufSecondary.template AppendCh<createRawString>(rawch);
  1155. // Template literal strings ignore all escaped line continuation tokens
  1156. NotifyScannedNewLine();
  1157. // We haven't updated m_currentCharacter yet, so make sure the MinLine info is correct in case we error out.
  1158. m_pchMinLine = p;
  1159. continue;
  1160. }
  1161. m_currentCharacter = p;
  1162. ScanNewLine(ch);
  1163. p = m_currentCharacter;
  1164. continue;
  1165. case 0:
  1166. if (p >= last)
  1167. {
  1168. errorType = (uint)ERRnoStrEnd;
  1169. ReturnScanError:
  1170. m_currentCharacter = p - 1;
  1171. Error(errorType);
  1172. }
  1173. else if (stringTemplateMode)
  1174. {
  1175. // Escaped null character is translated into 0x0030 for raw template literals
  1176. rawch = 0x0030;
  1177. }
  1178. break;
  1179. default:
  1180. if (this->IsMultiUnitChar(ch))
  1181. {
  1182. rawch = ch = this->template ReadRest<true>(ch, p, last);
  1183. switch (ch)
  1184. {
  1185. case kchLS:
  1186. case kchPS:
  1187. goto LEcmaEscapeLineBreak;
  1188. }
  1189. }
  1190. break;
  1191. }
  1192. break;
  1193. }
  1194. m_tempChBuf.AppendCh(ch);
  1195. m_tempChBufSecondary.template AppendCh<createRawString>(rawch);
  1196. }
  1197. LBreak:
  1198. bool createPid = true;
  1199. if ((m_DeferredParseFlags & ScanFlagSuppressStrPid) != 0)
  1200. {
  1201. createPid = false;
  1202. if ((m_tempChBuf.m_ichCur == 10) && (0 == memcmp(_u("use strict"), m_tempChBuf.m_prgch, m_tempChBuf.m_ichCur * sizeof(OLECHAR))))
  1203. {
  1204. createPid = true;
  1205. }
  1206. }
  1207. if (createPid)
  1208. {
  1209. m_ptoken->SetIdentifier(this->GetHashTbl()->PidHashNameLen(m_tempChBuf.m_prgch, m_tempChBuf.m_ichCur));
  1210. }
  1211. else
  1212. {
  1213. m_ptoken->SetIdentifier(NULL);
  1214. }
  1215. m_scanState = ScanStateNormal;
  1216. m_doubleQuoteOnLastTkStrCon = '"' == delim;
  1217. *pp = p;
  1218. return tkStrCon;
  1219. }
  1220. template<typename EncodingPolicy>
  1221. tokens Scanner<EncodingPolicy>::ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp)
  1222. {
  1223. return ScanStringConstant<false, false>(delim, pp);
  1224. }
  1225. /*****************************************************************************
  1226. *
  1227. * Consume a C-style comment.
  1228. */
  1229. template<typename EncodingPolicy>
  1230. tokens Scanner<EncodingPolicy>::SkipComment(EncodedCharPtr *pp, /* out */ bool* containTypeDef)
  1231. {
  1232. Assert(containTypeDef != nullptr);
  1233. EncodedCharPtr p = *pp;
  1234. *containTypeDef = false;
  1235. EncodedCharPtr last = m_pchLast;
  1236. OLECHAR ch;
  1237. for (;;)
  1238. {
  1239. switch((ch = this->ReadFirst(p, last)))
  1240. {
  1241. case '*':
  1242. if (*p == '/')
  1243. {
  1244. *pp = p + 1;
  1245. return tkNone;
  1246. }
  1247. break;
  1248. // ES 2015 11.3 Line Terminators
  1249. case kchLS: // 0x2028, classifies as new line
  1250. case kchPS: // 0x2029, classifies as new line
  1251. LEcmaLineBreak:
  1252. goto LLineBreak;
  1253. case kchRET:
  1254. case kchNWL:
  1255. LLineBreak:
  1256. m_fHadEol = TRUE;
  1257. m_currentCharacter = p;
  1258. ScanNewLine(ch);
  1259. p = m_currentCharacter;
  1260. break;
  1261. case kchNUL:
  1262. if (p >= last)
  1263. {
  1264. m_currentCharacter = p - 1;
  1265. *pp = p - 1;
  1266. Error(ERRnoCmtEnd);
  1267. }
  1268. break;
  1269. default:
  1270. if (this->IsMultiUnitChar(ch))
  1271. {
  1272. ch = this->template ReadRest<true>(ch, p, last);
  1273. switch (ch)
  1274. {
  1275. case kchLS:
  1276. case kchPS:
  1277. goto LEcmaLineBreak;
  1278. }
  1279. }
  1280. break;
  1281. }
  1282. }
  1283. }
  1284. /*****************************************************************************
  1285. *
  1286. * We've encountered a newline - update various counters and things.
  1287. */
  1288. template<typename EncodingPolicy>
  1289. void Scanner<EncodingPolicy>::ScanNewLine(uint ch)
  1290. {
  1291. if (ch == '\r' && PeekNextChar() == '\n')
  1292. {
  1293. ReadNextChar();
  1294. }
  1295. NotifyScannedNewLine();
  1296. }
  1297. /*****************************************************************************
  1298. *
  1299. * We've encountered a newline - update various counters and things.
  1300. */
  1301. template<typename EncodingPolicy>
  1302. void Scanner<EncodingPolicy>::NotifyScannedNewLine()
  1303. {
  1304. // update in scanner: previous line, current line, number of lines.
  1305. m_line++;
  1306. m_pchPrevLine = m_pchMinLine;
  1307. m_pchMinLine = m_currentCharacter;
  1308. m_cMinLineMultiUnits = this->m_cMultiUnits;
  1309. }
  1310. /*****************************************************************************
  1311. *
  1312. * Delivers a token stream.
  1313. */
  1314. template<typename EncodingPolicy>
  1315. tokens Scanner<EncodingPolicy>::ScanForcingPid()
  1316. {
  1317. if (m_DeferredParseFlags != ScanFlagNone)
  1318. {
  1319. BYTE deferredParseFlagsSave = m_DeferredParseFlags;
  1320. m_DeferredParseFlags = ScanFlagNone;
  1321. tokens result = tkEOF;
  1322. TryFinally(
  1323. [&]() /* try block */
  1324. {
  1325. result = this->Scan();
  1326. },
  1327. [&](bool) /* finally block */
  1328. {
  1329. this->m_DeferredParseFlags = deferredParseFlagsSave;
  1330. });
  1331. return result;
  1332. }
  1333. return Scan();
  1334. }
  1335. template<typename EncodingPolicy>
  1336. tokens Scanner<EncodingPolicy>::Scan()
  1337. {
  1338. return ScanCore(true);
  1339. }
  1340. template<typename EncodingPolicy>
  1341. tokens Scanner<EncodingPolicy>::ScanNoKeywords()
  1342. {
  1343. return ScanCore(false);
  1344. }
  1345. template<typename EncodingPolicy>
  1346. tokens Scanner<EncodingPolicy>::ScanAhead()
  1347. {
  1348. return ScanNoKeywords();
  1349. }
  1350. template<typename EncodingPolicy>
  1351. tokens Scanner<EncodingPolicy>::ScanCore(bool identifyKwds)
  1352. {
  1353. codepoint_t ch;
  1354. OLECHAR firstChar;
  1355. OLECHAR secondChar;
  1356. EncodedCharPtr pchT;
  1357. size_t multiUnits = 0;
  1358. EncodedCharPtr p = m_currentCharacter;
  1359. EncodedCharPtr last = m_pchLast;
  1360. bool seenDelimitedCommentEnd = false;
  1361. // store the last token
  1362. m_tkPrevious = m_ptoken->tk;
  1363. m_iecpLimTokPrevious = IecpLimTok(); // Introduced for use by lambda parsing to find correct span of expression lambdas
  1364. m_ichLimTokPrevious = IchLimTok();
  1365. size_t savedMultiUnits = this->m_cMultiUnits;
  1366. if (p >= last)
  1367. {
  1368. m_pchMinTok = p;
  1369. m_cMinTokMultiUnits = this->m_cMultiUnits;
  1370. goto LEof;
  1371. }
  1372. tokens token;
  1373. m_fHadEol = FALSE;
  1374. CharTypes chType;
  1375. charcount_t commentStartLine;
  1376. if (m_scanState && *p != 0)
  1377. {
  1378. if (m_scanState == ScanStateStringTemplateMiddleOrEnd)
  1379. {
  1380. AssertMsg(m_fStringTemplateDepth > 0,
  1381. "Shouldn't be trying to parse a string template end or middle token if we aren't scanning a string template");
  1382. m_scanState = ScanStateNormal;
  1383. pchT = p;
  1384. token = ScanStringTemplateMiddleOrEnd(&pchT);
  1385. p = pchT;
  1386. goto LDone;
  1387. }
  1388. }
  1389. for (;;)
  1390. {
  1391. LLoop:
  1392. m_pchMinTok = p;
  1393. m_cMinTokMultiUnits = this->m_cMultiUnits;
  1394. ch = this->ReadFirst(p, last);
  1395. #if DEBUG
  1396. chType = this->charClassifier->GetCharType((OLECHAR)ch);
  1397. #endif
  1398. switch (ch)
  1399. {
  1400. LDefault:
  1401. default:
  1402. if (ch == kchLS ||
  1403. ch == kchPS )
  1404. {
  1405. goto LNewLine;
  1406. }
  1407. {
  1408. BOOL isMultiUnit = this->IsMultiUnitChar((OLECHAR)ch);
  1409. if (isMultiUnit)
  1410. {
  1411. ch = this->template ReadRest<true>((OLECHAR)ch, p, last);
  1412. }
  1413. if (es6UnicodeMode && Js::NumberUtilities::IsSurrogateLowerPart(ch))
  1414. {
  1415. codepoint_t upper = this->PeekFull(p, last);
  1416. if (Js::NumberUtilities::IsSurrogateUpperPart(upper))
  1417. {
  1418. // Consume the rest of the utf8 bytes for the codepoint
  1419. OLECHAR decodedUpper = this->ReadSurrogatePairUpper(p, last);
  1420. Assert(decodedUpper == (OLECHAR) upper);
  1421. ch = Js::NumberUtilities::SurrogatePairAsCodePoint(ch, upper);
  1422. }
  1423. }
  1424. if (this->charClassifier->IsIdStart(ch))
  1425. {
  1426. // We treat IDContinue as an error.
  1427. token = ScanIdentifierContinue(identifyKwds, false, !!isMultiUnit, m_pchMinTok, p, &p);
  1428. break;
  1429. }
  1430. }
  1431. chType = this->charClassifier->GetCharType(ch);
  1432. switch (chType)
  1433. {
  1434. case _C_WSP: continue;
  1435. case _C_NWL: goto LNewLine;
  1436. // All other types (except errors) are handled by the outer switch.
  1437. }
  1438. Assert(chType == _C_LET || chType == _C_ERR || chType == _C_UNK || chType == _C_BKQ || chType == _C_SHP || chType == _C_AT || chType == _C_DIG);
  1439. m_currentCharacter = p - 1;
  1440. Error(ERRillegalChar);
  1441. continue;
  1442. case '\0':
  1443. // Put back the null in case we get called again.
  1444. p--;
  1445. if (p < last)
  1446. {
  1447. // A \0 prior to the end of the text is an invalid character.
  1448. m_currentCharacter = p;
  1449. Error(ERRillegalChar);
  1450. }
  1451. LEof:
  1452. Assert(p >= last);
  1453. token = tkEOF;
  1454. break;
  1455. case 0x0009:
  1456. case 0x000B:
  1457. case 0x000C:
  1458. case 0x0020:
  1459. Assert(chType == _C_WSP);
  1460. continue;
  1461. case '.':
  1462. if (!Js::NumberUtilities::IsDigit(*p))
  1463. {
  1464. // Not a double
  1465. if (m_scriptContext->GetConfig()->IsES6SpreadEnabled() &&
  1466. this->PeekFirst(p, last) == '.' &&
  1467. this->PeekFirst(p + 1, last) == '.')
  1468. {
  1469. token = tkEllipsis;
  1470. p += 2;
  1471. }
  1472. else
  1473. {
  1474. token = tkDot;
  1475. }
  1476. break;
  1477. }
  1478. // May be a double, fall through
  1479. case '0': case '1': case '2': case '3': case '4':
  1480. case '5': case '6': case '7': case '8': case '9':
  1481. {
  1482. double dbl;
  1483. Assert(chType == _C_DIG || chType == _C_DOT);
  1484. p = m_pchMinTok;
  1485. this->RestoreMultiUnits(m_cMinTokMultiUnits);
  1486. LikelyNumberType likelyType = LikelyNumberType::Int;
  1487. pchT = FScanNumber(p, &dbl, likelyType, savedMultiUnits);
  1488. if (p == pchT)
  1489. {
  1490. this->RestoreMultiUnits(savedMultiUnits);
  1491. Assert(this->PeekFirst(p, last) != '.');
  1492. Error(ERRbadNumber);
  1493. }
  1494. Assert(!Js::NumberUtilities::IsNan(dbl));
  1495. if (likelyType == LikelyNumberType::BigInt)
  1496. {
  1497. Assert(m_scriptContext->GetConfig()->IsESBigIntEnabled());
  1498. AssertOrFailFast(pchT - p < UINT_MAX);
  1499. token = tkBigIntCon;
  1500. m_ptoken->SetBigInt(this->GetHashTbl()->PidHashNameLen(p, pchT, (uint32) (pchT - p)));
  1501. p = pchT;
  1502. break;
  1503. }
  1504. p = pchT;
  1505. int32 value;
  1506. if ((likelyType == LikelyNumberType::Int) && Js::NumberUtilities::FDblIsInt32(dbl, &value))
  1507. {
  1508. m_ptoken->SetLong(value);
  1509. token = tkIntCon;
  1510. }
  1511. else
  1512. {
  1513. token = tkFltCon;
  1514. m_ptoken->SetDouble(dbl, likelyType == LikelyNumberType::Int);
  1515. }
  1516. break;
  1517. }
  1518. case '(': Assert(chType == _C_LPR); token = tkLParen; break;
  1519. case ')': Assert(chType == _C_RPR); token = tkRParen; break;
  1520. case ',': Assert(chType == _C_CMA); token = tkComma; break;
  1521. case ';': Assert(chType == _C_SMC); token = tkSColon; break;
  1522. case '[': Assert(chType == _C_LBR); token = tkLBrack; break;
  1523. case ']': Assert(chType == _C_RBR); token = tkRBrack; break;
  1524. case '~': Assert(chType == _C_TIL); token = tkTilde; break;
  1525. case '?': Assert(chType == _C_QUE); token = tkQMark; break;
  1526. case '{': Assert(chType == _C_LC); token = tkLCurly; break;
  1527. // ES 2015 11.3 Line Terminators
  1528. case '\r':
  1529. case '\n':
  1530. // kchLS:
  1531. // kchPS:
  1532. LNewLine:
  1533. m_currentCharacter = p;
  1534. ScanNewLine(ch);
  1535. p = m_currentCharacter;
  1536. m_fHadEol = TRUE;
  1537. continue;
  1538. LReserved:
  1539. {
  1540. // We will derive the PID from the token
  1541. Assert(token < tkID);
  1542. m_ptoken->SetIdentifier(NULL);
  1543. goto LDone;
  1544. }
  1545. LEval:
  1546. {
  1547. token = tkID;
  1548. if (!this->m_parser) goto LIdentifier;
  1549. m_ptoken->SetIdentifier(this->m_parser->GetEvalPid());
  1550. goto LDone;
  1551. }
  1552. LArguments:
  1553. {
  1554. token = tkID;
  1555. if (!this->m_parser) goto LIdentifier;
  1556. m_ptoken->SetIdentifier(this->m_parser->GetArgumentsPid());
  1557. goto LDone;
  1558. }
  1559. LTarget:
  1560. {
  1561. token = tkID;
  1562. if (!this->m_parser) goto LIdentifier;
  1563. m_ptoken->SetIdentifier(this->m_parser->GetTargetPid());
  1564. goto LDone;
  1565. }
  1566. #include "kwd-swtch.h"
  1567. case 'A': case 'B': case 'C': case 'D': case 'E':
  1568. case 'F': case 'G': case 'H': case 'I': case 'J':
  1569. case 'K': case 'L': case 'M': case 'N': case 'O':
  1570. case 'P': case 'Q': case 'R': case 'S': case 'T':
  1571. case 'U': case 'V': case 'W': case 'X': case 'Y':
  1572. case 'Z':
  1573. // Lower-case letters handled in kwd-swtch.h above during reserved word recognition.
  1574. case '$': case '_':
  1575. LIdentifier:
  1576. Assert(this->charClassifier->IsIdStart(ch));
  1577. Assert(ch < 0x10000 && !this->IsMultiUnitChar((OLECHAR)ch));
  1578. token = ScanIdentifierContinue(identifyKwds, false, false, m_pchMinTok, p, &p);
  1579. break;
  1580. case '`':
  1581. Assert(chType == _C_BKQ);
  1582. pchT = p;
  1583. token = ScanStringTemplateBegin(&pchT);
  1584. p = pchT;
  1585. break;
  1586. case '}':
  1587. Assert(chType == _C_RC);
  1588. token = tkRCurly;
  1589. break;
  1590. case '\\':
  1591. pchT = p - 1;
  1592. token = ScanIdentifier(identifyKwds, &pchT);
  1593. if (tkScanError == token)
  1594. {
  1595. m_currentCharacter = p;
  1596. Error(ERRillegalChar);
  1597. }
  1598. p = pchT;
  1599. break;
  1600. case ':':
  1601. token = tkColon;
  1602. break;
  1603. case '=':
  1604. token = tkAsg;
  1605. switch (this->PeekFirst(p, last))
  1606. {
  1607. case '=':
  1608. p++;
  1609. token = tkEQ;
  1610. if (this->PeekFirst(p, last) == '=')
  1611. {
  1612. p++;
  1613. token = tkEqv;
  1614. }
  1615. break;
  1616. case '>':
  1617. p++;
  1618. token = tkDArrow;
  1619. break;
  1620. }
  1621. break;
  1622. case '!':
  1623. token = tkBang;
  1624. if (this->PeekFirst(p, last) == '=')
  1625. {
  1626. p++;
  1627. token = tkNE;
  1628. if (this->PeekFirst(p, last) == '=')
  1629. {
  1630. p++;
  1631. token = tkNEqv;
  1632. }
  1633. }
  1634. break;
  1635. case '+':
  1636. token = tkAdd;
  1637. switch (this->PeekFirst(p, last))
  1638. {
  1639. case '=':
  1640. p++;
  1641. token = tkAsgAdd;
  1642. break;
  1643. case '+':
  1644. p++;
  1645. token = tkInc;
  1646. break;
  1647. }
  1648. break;
  1649. case '-':
  1650. token = tkSub;
  1651. switch (this->PeekFirst(p, last))
  1652. {
  1653. case '=':
  1654. p++;
  1655. token = tkAsgSub;
  1656. break;
  1657. case '-':
  1658. p++;
  1659. token = tkDec;
  1660. if (!m_fIsModuleCode)
  1661. {
  1662. // https://tc39.github.io/ecma262/#prod-annexB-MultiLineComment
  1663. // If there was a new line in the multi-line comment, the text after --> is a comment.
  1664. if ('>' == this->PeekFirst(p, last) && m_fHadEol)
  1665. {
  1666. goto LSkipLineComment;
  1667. }
  1668. }
  1669. break;
  1670. }
  1671. break;
  1672. case '*':
  1673. token = tkStar;
  1674. switch(this->PeekFirst(p, last))
  1675. {
  1676. case '=' :
  1677. p++;
  1678. token = tkAsgMul;
  1679. break;
  1680. case '*' :
  1681. if (!m_scriptContext->GetConfig()->IsES7ExponentiationOperatorEnabled())
  1682. {
  1683. break;
  1684. }
  1685. p++;
  1686. token = tkExpo;
  1687. if (this->PeekFirst(p, last) == '=')
  1688. {
  1689. p++;
  1690. token = tkAsgExpo;
  1691. }
  1692. }
  1693. break;
  1694. case '#':
  1695. // Hashbang syntax is a single line comment only if it is the first token in the source
  1696. if (m_scriptContext->GetConfig()->IsESHashbangEnabled() && this->PeekFirst(p, last) == '!' && m_pchBase == m_pchMinTok)
  1697. {
  1698. p++;
  1699. goto LSkipLineComment;
  1700. }
  1701. goto LDefault;
  1702. case '/':
  1703. token = tkDiv;
  1704. switch(this->PeekFirst(p, last))
  1705. {
  1706. case '=':
  1707. p++;
  1708. token = tkAsgDiv;
  1709. break;
  1710. case '/':
  1711. if (p >= last)
  1712. {
  1713. AssertMsg(!m_fIsModuleCode, "Do we have other line comment cases scanning pass last?");
  1714. // Effective source length may have excluded HTMLCommentSuffix "//... -->". If we are scanning
  1715. // those, we have passed "last" already. Move back and return EOF.
  1716. p = last;
  1717. goto LEof;
  1718. }
  1719. ch = *++p;
  1720. firstChar = (OLECHAR)ch;
  1721. LSkipLineComment:
  1722. pchT = NULL;
  1723. for (;;)
  1724. {
  1725. switch ((ch = this->ReadFirst(p, last)))
  1726. {
  1727. case kchLS: // 0x2028, classifies as new line
  1728. case kchPS: // 0x2029, classifies as new line
  1729. LEcmaCommentLineBreak:
  1730. // kchPS and kchLS are more than one unit in UTF-8.
  1731. if (pchT)
  1732. {
  1733. // kchPS and kchLS are more than one unit in UTF-8.
  1734. p = pchT;
  1735. }
  1736. else
  1737. {
  1738. // But only a single code unit in UTF16
  1739. p--;
  1740. }
  1741. this->RestoreMultiUnits(multiUnits);
  1742. goto LCommentLineBreak;
  1743. case kchNWL:
  1744. case kchRET:
  1745. p--;
  1746. LCommentLineBreak:
  1747. // Subtract the comment length from the total char count for the purpose
  1748. // of deciding whether to defer AST and byte code generation.
  1749. m_parser->ReduceDeferredScriptLength((ULONG)(p - m_pchMinTok));
  1750. break;
  1751. case kchNUL:
  1752. // Because we used ReadFirst, we have advanced p. The character that we are looking at is actually is p - 1.
  1753. // If p == last, we are looking at p - 1, it is still within the source buffer, and we need to consider it part of the comment
  1754. // Only if p > last that we have pass the source buffer and consider it a line break
  1755. if (p > last)
  1756. {
  1757. p--;
  1758. goto LCommentLineBreak;
  1759. }
  1760. continue;
  1761. default:
  1762. if (this->IsMultiUnitChar((OLECHAR)ch))
  1763. {
  1764. pchT = p - 1;
  1765. multiUnits = this->m_cMultiUnits;
  1766. switch (ch = this->template ReadRest<true>((OLECHAR)ch, p, last))
  1767. {
  1768. case kchLS:
  1769. case kchPS:
  1770. goto LEcmaCommentLineBreak;
  1771. }
  1772. }
  1773. continue;
  1774. }
  1775. break;
  1776. }
  1777. continue;
  1778. case '*':
  1779. ch = *++p;
  1780. firstChar = (OLECHAR)ch;
  1781. if ((p + 1) < last)
  1782. {
  1783. secondChar = (OLECHAR)(*(p + 1));
  1784. }
  1785. else
  1786. {
  1787. secondChar = '\0';
  1788. }
  1789. pchT = p;
  1790. commentStartLine = m_line;
  1791. bool containTypeDef;
  1792. if (tkNone == (token = SkipComment(&pchT, &containTypeDef)))
  1793. {
  1794. // Subtract the comment length from the total char count for the purpose
  1795. // of deciding whether to defer AST and byte code generation.
  1796. m_parser->ReduceDeferredScriptLength((ULONG)(pchT - m_pchMinTok));
  1797. p = pchT;
  1798. seenDelimitedCommentEnd = true;
  1799. goto LLoop;
  1800. }
  1801. p = pchT;
  1802. break;
  1803. }
  1804. break;
  1805. case '%':
  1806. Assert(chType == _C_PCT);
  1807. token = tkPct;
  1808. if (this->PeekFirst(p, last) == '=')
  1809. {
  1810. p++;
  1811. token = tkAsgMod;
  1812. }
  1813. break;
  1814. case '<':
  1815. Assert(chType == _C_LT);
  1816. token = tkLT;
  1817. switch (this->PeekFirst(p, last))
  1818. {
  1819. case '=':
  1820. p++;
  1821. token = tkLE;
  1822. break;
  1823. case '<':
  1824. p++;
  1825. token = tkLsh;
  1826. if (this->PeekFirst(p, last) == '=')
  1827. {
  1828. p++;
  1829. token = tkAsgLsh;
  1830. break;
  1831. }
  1832. break;
  1833. case '!':
  1834. // ES 2015 B.1.3 - HTML comments are only allowed when parsing non-module code.
  1835. if (!m_fIsModuleCode && this->PeekFirst(p + 1, last) == '-' && this->PeekFirst(p + 2, last) == '-')
  1836. {
  1837. // This is a "<!--" comment - treat as //
  1838. if (p >= last)
  1839. {
  1840. // Effective source length may have excluded HTMLCommentSuffix "<!-- ... -->". If we are scanning
  1841. // those, we have passed "last" already. Move back and return EOF.
  1842. p = last;
  1843. goto LEof;
  1844. }
  1845. firstChar = '!';
  1846. goto LSkipLineComment;
  1847. }
  1848. break;
  1849. }
  1850. break;
  1851. case '>':
  1852. Assert(chType == _C_GT);
  1853. token = tkGT;
  1854. switch (this->PeekFirst(p, last))
  1855. {
  1856. case '=':
  1857. p++;
  1858. token = tkGE;
  1859. break;
  1860. case '>':
  1861. p++;
  1862. token = tkRsh;
  1863. switch (this->PeekFirst(p, last))
  1864. {
  1865. case '=':
  1866. p++;
  1867. token = tkAsgRsh;
  1868. break;
  1869. case '>':
  1870. p++;
  1871. token = tkRs2;
  1872. if (*p == '=')
  1873. {
  1874. p++;
  1875. token = tkAsgRs2;
  1876. }
  1877. break;
  1878. }
  1879. break;
  1880. }
  1881. break;
  1882. case '^':
  1883. Assert(chType == _C_XOR);
  1884. token = tkXor;
  1885. if (this->PeekFirst(p, last) == '=')
  1886. {
  1887. p++;
  1888. token = tkAsgXor;
  1889. }
  1890. break;
  1891. case '|':
  1892. Assert(chType == _C_BAR);
  1893. token = tkOr;
  1894. switch (this->PeekFirst(p, last))
  1895. {
  1896. case '=':
  1897. p++;
  1898. token = tkAsgOr;
  1899. break;
  1900. case '|':
  1901. p++;
  1902. token = tkLogOr;
  1903. break;
  1904. }
  1905. break;
  1906. case '&':
  1907. Assert(chType == _C_AMP);
  1908. token = tkAnd;
  1909. switch (this->PeekFirst(p, last))
  1910. {
  1911. case '=':
  1912. p++;
  1913. token = tkAsgAnd;
  1914. break;
  1915. case '&':
  1916. p++;
  1917. token = tkLogAnd;
  1918. break;
  1919. }
  1920. break;
  1921. case '\'':
  1922. case '"':
  1923. Assert(chType == _C_QUO || chType == _C_APO);
  1924. pchT = p;
  1925. token = this->ScanStringConstant((OLECHAR)ch, &pchT);
  1926. p = pchT;
  1927. break;
  1928. }
  1929. break;
  1930. }
  1931. LDone:
  1932. m_currentCharacter = p;
  1933. return (m_ptoken->tk = token);
  1934. }
  1935. template <typename EncodingPolicy>
  1936. IdentPtr Scanner<EncodingPolicy>::GetSecondaryBufferAsPid()
  1937. {
  1938. bool createPid = true;
  1939. if ((m_DeferredParseFlags & ScanFlagSuppressStrPid) != 0)
  1940. {
  1941. createPid = false;
  1942. }
  1943. if (createPid)
  1944. {
  1945. return this->GetHashTbl()->PidHashNameLen(m_tempChBufSecondary.m_prgch, m_tempChBufSecondary.m_ichCur);
  1946. }
  1947. else
  1948. {
  1949. return nullptr;
  1950. }
  1951. }
  1952. template <typename EncodingPolicy>
  1953. LPCOLESTR Scanner<EncodingPolicy>::StringFromLong(int32 lw)
  1954. {
  1955. _ltow_s(lw, m_tempChBuf.m_prgch, m_tempChBuf.m_cchMax, 10);
  1956. return m_tempChBuf.m_prgch;
  1957. }
  1958. template <typename EncodingPolicy>
  1959. IdentPtr Scanner<EncodingPolicy>::PidFromLong(int32 lw)
  1960. {
  1961. return this->GetHashTbl()->PidHashName(StringFromLong(lw));
  1962. }
  1963. template <typename EncodingPolicy>
  1964. LPCOLESTR Scanner<EncodingPolicy>::StringFromDbl(double dbl)
  1965. {
  1966. if (!Js::NumberUtilities::FDblToStr(dbl, m_tempChBuf.m_prgch, m_tempChBuf.m_cchMax))
  1967. {
  1968. Error(ERRnoMemory);
  1969. }
  1970. return m_tempChBuf.m_prgch;
  1971. }
  1972. template <typename EncodingPolicy>
  1973. IdentPtr Scanner<EncodingPolicy>::PidFromDbl(double dbl)
  1974. {
  1975. return this->GetHashTbl()->PidHashName(StringFromDbl(dbl));
  1976. }
  1977. template <typename EncodingPolicy>
  1978. void Scanner<EncodingPolicy>::Capture(_Out_ RestorePoint* restorePoint)
  1979. {
  1980. Capture(restorePoint, 0, 0);
  1981. }
  1982. template <typename EncodingPolicy>
  1983. void Scanner<EncodingPolicy>::Capture(_Out_ RestorePoint* restorePoint, uint functionIdIncrement, size_t lengthDecr)
  1984. {
  1985. restorePoint->m_ichMinTok = this->IchMinTok();
  1986. restorePoint->m_ichMinLine = this->IchMinLine();
  1987. restorePoint->m_cMinTokMultiUnits = this->m_cMinTokMultiUnits;
  1988. restorePoint->m_cMinLineMultiUnits = this->m_cMinLineMultiUnits;
  1989. restorePoint->m_line = this->m_line;
  1990. restorePoint->m_fHadEol = this->m_fHadEol;
  1991. restorePoint->functionIdIncrement = functionIdIncrement;
  1992. restorePoint->lengthDecr = lengthDecr;
  1993. #ifdef DEBUG
  1994. restorePoint->m_cMultiUnits = this->m_cMultiUnits;
  1995. #endif
  1996. }
  1997. template <typename EncodingPolicy>
  1998. void Scanner<EncodingPolicy>::SeekTo(const RestorePoint& restorePoint)
  1999. {
  2000. SeekAndScan<false>(restorePoint);
  2001. }
  2002. template <typename EncodingPolicy>
  2003. void Scanner<EncodingPolicy>::SeekToForcingPid(const RestorePoint& restorePoint)
  2004. {
  2005. SeekAndScan<true>(restorePoint);
  2006. }
  2007. template <typename EncodingPolicy>
  2008. template <bool forcePid>
  2009. void Scanner<EncodingPolicy>::SeekAndScan(const RestorePoint& restorePoint)
  2010. {
  2011. this->m_currentCharacter = this->m_pchBase + restorePoint.m_ichMinTok + restorePoint.m_cMinTokMultiUnits;
  2012. this->m_pchMinLine = this->m_pchBase + restorePoint.m_ichMinLine + restorePoint.m_cMinLineMultiUnits;
  2013. this->m_cMinLineMultiUnits = restorePoint.m_cMinLineMultiUnits;
  2014. this->RestoreMultiUnits(restorePoint.m_cMinTokMultiUnits);
  2015. if (forcePid)
  2016. {
  2017. this->ScanForcingPid();
  2018. }
  2019. else
  2020. {
  2021. this->Scan();
  2022. }
  2023. this->m_line = restorePoint.m_line;
  2024. this->m_fHadEol = restorePoint.m_fHadEol;
  2025. this->m_parser->ReduceDeferredScriptLength(restorePoint.lengthDecr);
  2026. Assert(this->m_cMultiUnits == restorePoint.m_cMultiUnits);
  2027. }
  2028. template <typename EncodingPolicy>
  2029. void Scanner<EncodingPolicy>::SeekTo(const RestorePoint& restorePoint, uint *nextFunctionId)
  2030. {
  2031. SeekTo(restorePoint);
  2032. *nextFunctionId += restorePoint.functionIdIncrement;
  2033. }
  2034. // Called by CompileScriptException::ProcessError to retrieve a BSTR for the line on which an error occurred.
  2035. template<typename EncodingPolicy>
  2036. HRESULT Scanner<EncodingPolicy>::SysAllocErrorLine(int32 ichMinLine, __out BSTR* pbstrLine)
  2037. {
  2038. if( !pbstrLine )
  2039. {
  2040. return E_POINTER;
  2041. }
  2042. // If we overflow the string, we have a serious problem...
  2043. if (ichMinLine < 0 || static_cast<size_t>(ichMinLine) > AdjustedLength() )
  2044. {
  2045. return E_UNEXPECTED;
  2046. }
  2047. typename EncodingPolicy::EncodedCharPtr pStart = static_cast<size_t>(ichMinLine) == IchMinLine() ? m_pchMinLine : m_pchBase + this->CharacterOffsetToUnitOffset(m_pchBase, m_currentCharacter, m_pchLast, ichMinLine);
  2048. // Determine the length by scanning for the next newline
  2049. size_t cb = 0;
  2050. charcount_t cch = LineLength(pStart, m_pchLast, &cb);
  2051. Assert(cch <= LONG_MAX);
  2052. typename EncodingPolicy::EncodedCharPtr pEnd = static_cast<size_t>(ichMinLine) == IchMinLine() ? m_pchMinLine + cb : m_pchBase + this->CharacterOffsetToUnitOffset(m_pchBase, m_currentCharacter, m_pchLast, cch);
  2053. *pbstrLine = SysAllocStringLen(NULL, cch);
  2054. if (!*pbstrLine)
  2055. {
  2056. return E_OUTOFMEMORY;
  2057. }
  2058. this->ConvertToUnicode(*pbstrLine, cch, pStart, pEnd);
  2059. return S_OK;
  2060. }
  2061. template class Scanner<NotNullTerminatedUTF8EncodingPolicy>;