Scan.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349
  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)
  164. {
  165. charcount_t result = 0;
  166. EncodedCharPtr p = first;
  167. for (;;)
  168. {
  169. switch( this->template ReadFull<false>(p, last) )
  170. {
  171. case kchNWL: // _C_NWL
  172. case kchRET:
  173. case kchLS:
  174. case kchPS:
  175. case kchNUL: // _C_NUL
  176. return result;
  177. }
  178. result++;
  179. }
  180. }
  181. template <typename EncodingPolicy>
  182. charcount_t Scanner<EncodingPolicy>::UpdateLine(int32 &line, EncodedCharPtr start, EncodedCharPtr last, charcount_t ichStart, charcount_t ichEnd)
  183. {
  184. EncodedCharPtr p = start;
  185. charcount_t ich = ichStart;
  186. int32 current = line;
  187. charcount_t lastStart = ichStart;
  188. while (ich < ichEnd)
  189. {
  190. ich++;
  191. switch (this->template ReadFull<false>(p, last))
  192. {
  193. case kchRET:
  194. if (this->PeekFull(p, last) == kchNWL)
  195. {
  196. ich++;
  197. this->template ReadFull<false>(p, last);
  198. }
  199. // fall-through
  200. case kchNWL:
  201. case kchLS:
  202. case kchPS:
  203. current++;
  204. lastStart = ich;
  205. break;
  206. case kchNUL:
  207. goto done;
  208. }
  209. }
  210. done:
  211. line = current;
  212. return lastStart;
  213. }
  214. template <typename EncodingPolicy>
  215. bool Scanner<EncodingPolicy>::TryReadEscape(EncodedCharPtr& startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar)
  216. {
  217. Assert(outChar != nullptr);
  218. Assert(startingLocation <= endOfSource);
  219. EncodedCharPtr currentLocation = startingLocation;
  220. codepoint_t charToOutput = 0x0;
  221. // '\' is Assumed as there is only one caller
  222. // Read 'u' characters
  223. if (currentLocation >= endOfSource || this->ReadFirst(currentLocation, endOfSource) != 'u')
  224. {
  225. return false;
  226. }
  227. bool expectCurly = false;
  228. if (currentLocation < endOfSource && this->PeekFirst(currentLocation, endOfSource) == '{' && es6UnicodeMode)
  229. {
  230. expectCurly = true;
  231. // Move past the character
  232. this->ReadFirst(currentLocation, endOfSource);
  233. }
  234. uint i = 0;
  235. OLECHAR ch = 0;
  236. int hexValue = 0;
  237. uint maxHexDigits = (expectCurly ? MAXUINT32 : 4u);
  238. for(; i < maxHexDigits && currentLocation < endOfSource; i++)
  239. {
  240. if (!Js::NumberUtilities::FHexDigit(ch = this->ReadFirst(currentLocation, endOfSource), &hexValue))
  241. {
  242. break;
  243. }
  244. charToOutput = charToOutput * 0x10 + hexValue;
  245. if (charToOutput > 0x10FFFF)
  246. {
  247. return false;
  248. }
  249. }
  250. //At least 4 characters have to be read
  251. if (i == 0 || (i != 4 && !expectCurly))
  252. {
  253. return false;
  254. }
  255. Assert(expectCurly ? es6UnicodeMode : true);
  256. if (expectCurly && ch != '}')
  257. {
  258. return false;
  259. }
  260. *outChar = charToOutput;
  261. startingLocation = currentLocation;
  262. return true;
  263. }
  264. template <typename EncodingPolicy>
  265. template <bool bScan>
  266. bool Scanner<EncodingPolicy>::TryReadCodePointRest(codepoint_t lower, EncodedCharPtr& startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *outContainsMultiUnitChar)
  267. {
  268. Assert(outChar != nullptr);
  269. Assert(outContainsMultiUnitChar != nullptr);
  270. Assert(es6UnicodeMode);
  271. Assert(Js::NumberUtilities::IsSurrogateLowerPart(lower));
  272. EncodedCharPtr currentLocation = startingLocation;
  273. *outChar = lower;
  274. if (currentLocation < endOfSource)
  275. {
  276. size_t restorePoint = this->m_cMultiUnits;
  277. codepoint_t upper = this->template ReadFull<bScan>(currentLocation, endOfSource);
  278. if (Js::NumberUtilities::IsSurrogateUpperPart(upper))
  279. {
  280. *outChar = Js::NumberUtilities::SurrogatePairAsCodePoint(lower, upper);
  281. if (this->IsMultiUnitChar(static_cast<OLECHAR>(upper)))
  282. {
  283. *outContainsMultiUnitChar = true;
  284. }
  285. startingLocation = currentLocation;
  286. }
  287. else
  288. {
  289. this->RestoreMultiUnits(restorePoint);
  290. }
  291. }
  292. return true;
  293. }
  294. template <typename EncodingPolicy>
  295. template <bool bScan>
  296. inline bool Scanner<EncodingPolicy>::TryReadCodePoint(EncodedCharPtr &startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *hasEscape, bool *outContainsMultiUnitChar)
  297. {
  298. Assert(outChar != nullptr);
  299. Assert(outContainsMultiUnitChar != nullptr);
  300. if (startingLocation >= endOfSource)
  301. {
  302. return false;
  303. }
  304. codepoint_t ch = this->template ReadFull<bScan>(startingLocation, endOfSource);
  305. if (FBigChar(ch))
  306. {
  307. if (this->IsMultiUnitChar(static_cast<OLECHAR>(ch)))
  308. {
  309. *outContainsMultiUnitChar = true;
  310. }
  311. if (es6UnicodeMode && Js::NumberUtilities::IsSurrogateLowerPart(ch))
  312. {
  313. return TryReadCodePointRest<bScan>(ch, startingLocation, endOfSource, outChar, outContainsMultiUnitChar);
  314. }
  315. }
  316. else if (ch == '\\' && TryReadEscape(startingLocation, endOfSource, &ch))
  317. {
  318. *hasEscape = true;
  319. }
  320. *outChar = ch;
  321. return true;
  322. }
  323. template <typename EncodingPolicy>
  324. tokens Scanner<EncodingPolicy>::ScanIdentifier(bool identifyKwds, EncodedCharPtr *pp)
  325. {
  326. EncodedCharPtr p = *pp;
  327. EncodedCharPtr pchMin = p;
  328. // JS6 allows unicode characters in the form of \uxxxx escape sequences
  329. // to be part of the identifier.
  330. bool fHasEscape = false;
  331. bool fHasMultiChar = false;
  332. codepoint_t codePoint = INVALID_CODEPOINT;
  333. size_t multiUnitsBeforeLast = this->m_cMultiUnits;
  334. // Check if we started the id
  335. if (!TryReadCodePoint<true>(p, m_pchLast, &codePoint, &fHasEscape, &fHasMultiChar))
  336. {
  337. // If no chars. could be scanned as part of the identifier, return error.
  338. return tkScanError;
  339. }
  340. Assert(codePoint < 0x110000u);
  341. if (!charClassifier->IsIdStart(codePoint))
  342. {
  343. // Put back the last character
  344. this->RestoreMultiUnits(multiUnitsBeforeLast);
  345. // If no chars. could be scanned as part of the identifier, return error.
  346. return tkScanError;
  347. }
  348. return ScanIdentifierContinue(identifyKwds, fHasEscape, fHasMultiChar, pchMin, p, pp);
  349. }
  350. template <typename EncodingPolicy>
  351. BOOL Scanner<EncodingPolicy>::FastIdentifierContinue(EncodedCharPtr&p, EncodedCharPtr last)
  352. {
  353. if (EncodingPolicy::MultiUnitEncoding)
  354. {
  355. while (p < last)
  356. {
  357. EncodedChar currentChar = *p;
  358. if (this->IsMultiUnitChar(currentChar))
  359. {
  360. // multi unit character, we may not have reach the end yet
  361. return FALSE;
  362. }
  363. Assert(currentChar != '\\' || !charClassifier->IsIdContinueFast<false>(currentChar));
  364. if (!charClassifier->IsIdContinueFast<false>(currentChar))
  365. {
  366. // only reach the end of the identifier if it is not the start of an escape sequence
  367. return currentChar != '\\';
  368. }
  369. p++;
  370. }
  371. // We have reach the end of the identifier.
  372. return TRUE;
  373. }
  374. // Not fast path for non multi unit encoding
  375. return false;
  376. }
  377. template <typename EncodingPolicy>
  378. tokens Scanner<EncodingPolicy>::ScanIdentifierContinue(bool identifyKwds, bool fHasEscape, bool fHasMultiChar,
  379. EncodedCharPtr pchMin, EncodedCharPtr p, EncodedCharPtr *pp)
  380. {
  381. EncodedCharPtr last = m_pchLast;
  382. while (true)
  383. {
  384. // Fast path for utf8, non-multi unit char and not escape
  385. if (FastIdentifierContinue(p, last))
  386. {
  387. break;
  388. }
  389. // Slow path that has to deal with multi unit encoding
  390. codepoint_t codePoint = INVALID_CODEPOINT;
  391. EncodedCharPtr pchBeforeLast = p;
  392. size_t multiUnitsBeforeLast = this->m_cMultiUnits;
  393. if (TryReadCodePoint<true>(p, last, &codePoint, &fHasEscape, &fHasMultiChar))
  394. {
  395. Assert(codePoint < 0x110000u);
  396. if (charClassifier->IsIdContinue(codePoint))
  397. {
  398. continue;
  399. }
  400. }
  401. // Put back the last character
  402. p = pchBeforeLast;
  403. this->RestoreMultiUnits(multiUnitsBeforeLast);
  404. break;
  405. }
  406. Assert(p - pchMin > 0 && p - pchMin <= LONG_MAX);
  407. *pp = p;
  408. if (!identifyKwds)
  409. {
  410. return tkID;
  411. }
  412. // UTF16 Scanner are only for syntax coloring, so it shouldn't come here.
  413. if (EncodingPolicy::MultiUnitEncoding && !fHasMultiChar && !fHasEscape)
  414. {
  415. Assert(sizeof(EncodedChar) == 1);
  416. // If there are no escape, that the main scan loop would have found the keyword already
  417. // So we can just assume it is an ID
  418. DebugOnly(int32 cch = UnescapeToTempBuf(pchMin, p));
  419. DebugOnly(tokens tk = Ident::TkFromNameLen(m_tempChBuf.m_prgch, cch, IsStrictMode()));
  420. Assert(tk == tkID || (tk == tkYIELD && !this->YieldIsKeyword()) || (tk == tkAWAIT && !this->AwaitIsKeyword()));
  421. m_ptoken->SetIdentifier(reinterpret_cast<const char *>(pchMin), (int32)(p - pchMin));
  422. return tkID;
  423. }
  424. IdentPtr pid = PidOfIdentiferAt(pchMin, p, fHasEscape, fHasMultiChar);
  425. m_ptoken->SetIdentifier(pid);
  426. if (!fHasEscape)
  427. {
  428. // If it doesn't have escape, then Scan() should have taken care of keywords (except
  429. // yield if m_fYieldIsKeyword is false, in which case yield is treated as an identifier, and except
  430. // await if m_fAwaitIsKeyword is false, in which case await is treated as an identifier).
  431. // We don't have to check if the name is reserved word and return it as an Identifier
  432. Assert(pid->Tk(IsStrictMode()) == tkID
  433. || (pid->Tk(IsStrictMode()) == tkYIELD && !this->YieldIsKeyword())
  434. || (pid->Tk(IsStrictMode()) == tkAWAIT && !this->AwaitIsKeyword()));
  435. return tkID;
  436. }
  437. tokens tk = pid->Tk(IsStrictMode());
  438. return tk == tkID || (tk == tkYIELD && !this->YieldIsKeyword()) || (tk == tkAWAIT && !this->AwaitIsKeyword()) ? tkID : tkNone;
  439. }
  440. template <typename EncodingPolicy>
  441. IdentPtr Scanner<EncodingPolicy>::PidAt(size_t iecpMin, size_t iecpLim)
  442. {
  443. Assert(iecpMin < AdjustedLength() && iecpLim <= AdjustedLength() && iecpLim > iecpMin);
  444. return PidOfIdentiferAt(m_pchBase + iecpMin, m_pchBase + iecpLim);
  445. }
  446. template <typename EncodingPolicy>
  447. uint32 Scanner<EncodingPolicy>::UnescapeToTempBuf(EncodedCharPtr p, EncodedCharPtr last)
  448. {
  449. m_tempChBuf.Reset();
  450. while( p < last )
  451. {
  452. codepoint_t codePoint;
  453. bool hasEscape, isMultiChar;
  454. bool gotCodePoint = TryReadCodePoint<false>(p, last, &codePoint, &hasEscape, &isMultiChar);
  455. Assert(gotCodePoint);
  456. Assert(codePoint < 0x110000);
  457. if (codePoint < 0x10000)
  458. {
  459. m_tempChBuf.AppendCh((OLECHAR)codePoint);
  460. }
  461. else
  462. {
  463. char16 lower, upper;
  464. Js::NumberUtilities::CodePointAsSurrogatePair(codePoint, &lower, &upper);
  465. m_tempChBuf.AppendCh(lower);
  466. m_tempChBuf.AppendCh(upper);
  467. }
  468. }
  469. return m_tempChBuf.m_ichCur;
  470. }
  471. template <typename EncodingPolicy>
  472. IdentPtr Scanner<EncodingPolicy>::PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last)
  473. {
  474. int32 cch = UnescapeToTempBuf(p, last);
  475. return this->GetHashTbl()->PidHashNameLen(m_tempChBuf.m_prgch, cch);
  476. }
  477. template <typename EncodingPolicy>
  478. IdentPtr Scanner<EncodingPolicy>::PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last, bool fHadEscape, bool fHasMultiChar)
  479. {
  480. // If there is an escape sequence in the JS6 identifier or it is a UTF8
  481. // source then we have to convert it to the equivalent char so we use a
  482. // buffer for translation.
  483. if ((EncodingPolicy::MultiUnitEncoding && fHasMultiChar) || fHadEscape)
  484. {
  485. return PidOfIdentiferAt(p, last);
  486. }
  487. else if (EncodingPolicy::MultiUnitEncoding)
  488. {
  489. Assert(sizeof(EncodedChar) == 1);
  490. return this->GetHashTbl()->PidHashNameLen(reinterpret_cast<const char *>(p), reinterpret_cast<const char *>(last), (int32)(last - p));
  491. }
  492. else
  493. {
  494. Assert(sizeof(EncodedChar) == 2);
  495. return this->GetHashTbl()->PidHashNameLen(reinterpret_cast< const char16 * >(p), (int32)(last - p));
  496. }
  497. }
  498. template <typename EncodingPolicy>
  499. typename Scanner<EncodingPolicy>::EncodedCharPtr Scanner<EncodingPolicy>::FScanNumber(EncodedCharPtr p, double *pdbl, LikelyNumberType& likelyType, size_t savedMultiUnits)
  500. {
  501. EncodedCharPtr last = m_pchLast;
  502. EncodedCharPtr pchT = nullptr;
  503. bool baseSpecified = false;
  504. likelyType = LikelyNumberType::Int;
  505. // Reset
  506. m_OctOrLeadingZeroOnLastTKNumber = false;
  507. auto baseSpecifierCheck = [&pchT, &pdbl, p, &baseSpecified]()
  508. {
  509. if (pchT == p + 2)
  510. {
  511. // An octal token '0' was followed by a base specifier: /0[xXoObB]/
  512. // This literal can no longer be a double
  513. *pdbl = 0;
  514. // Advance the character pointer to the base specifier
  515. pchT = p + 1;
  516. // Set the flag so we know to offset the potential identifier search after the literal
  517. baseSpecified = true;
  518. }
  519. };
  520. if ('0' == this->PeekFirst(p, last))
  521. {
  522. switch(this->PeekFirst(p + 1, last))
  523. {
  524. case '.':
  525. case 'e':
  526. case 'E':
  527. case 'n':
  528. likelyType = LikelyNumberType::Double;
  529. // Floating point
  530. goto LFloat;
  531. case 'x':
  532. case 'X':
  533. // Hex
  534. *pdbl = Js::NumberUtilities::DblFromHex(p + 2, &pchT);
  535. baseSpecifierCheck();
  536. goto LIdCheck;
  537. case 'o':
  538. case 'O':
  539. // Octal
  540. *pdbl = Js::NumberUtilities::DblFromOctal(p + 2, &pchT);
  541. baseSpecifierCheck();
  542. goto LIdCheck;
  543. case 'b':
  544. case 'B':
  545. // Binary
  546. *pdbl = Js::NumberUtilities::DblFromBinary(p + 2, &pchT);
  547. baseSpecifierCheck();
  548. goto LIdCheck;
  549. default:
  550. // Octal
  551. *pdbl = Js::NumberUtilities::DblFromOctal(p, &pchT);
  552. Assert(pchT > p);
  553. #if !SOURCERELEASE
  554. // If an octal literal is malformed then it is in fact a decimal literal.
  555. #endif // !SOURCERELEASE
  556. if(*pdbl != 0 || pchT > p + 1)
  557. m_OctOrLeadingZeroOnLastTKNumber = true; //report as an octal or hex for JSON when leading 0. Just '0' is ok
  558. switch (*pchT)
  559. {
  560. case '8':
  561. case '9':
  562. // case 'e':
  563. // case 'E':
  564. // case '.':
  565. m_OctOrLeadingZeroOnLastTKNumber = false; //08... or 09....
  566. goto LFloat;
  567. }
  568. goto LIdCheck;
  569. }
  570. }
  571. else
  572. {
  573. LFloat:
  574. *pdbl = Js::NumberUtilities::StrToDbl(p, &pchT, likelyType, m_scriptContext->GetConfig()->IsESBigIntEnabled());
  575. Assert(pchT == p || !Js::NumberUtilities::IsNan(*pdbl));
  576. if (likelyType == LikelyNumberType::BigInt)
  577. {
  578. Assert(*pdbl == 0);
  579. }
  580. // fall through to LIdCheck
  581. }
  582. LIdCheck:
  583. // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
  584. // The SourceCharacter immediately following a NumericLiteral must not be an IdentifierStart or DecimalDigit.
  585. // For example : 3in is an error and not the two input elements 3 and in
  586. // If a base was speficied, use the first character denoting the constant. In this case, pchT is pointing to the base specifier.
  587. EncodedCharPtr startingLocation = baseSpecified ? pchT + 1 : pchT;
  588. codepoint_t outChar = *startingLocation;
  589. if (this->IsMultiUnitChar((OLECHAR)outChar))
  590. {
  591. outChar = this->template ReadRest<true>((OLECHAR)outChar, startingLocation, last);
  592. }
  593. if (this->charClassifier->IsIdStart(outChar))
  594. {
  595. this->RestoreMultiUnits(savedMultiUnits);
  596. Error(ERRIdAfterLit);
  597. }
  598. // IsIdStart does not cover the unicode escape case. Try to read a unicode escape from the 'u' char.
  599. if (*pchT == '\\')
  600. {
  601. startingLocation++; // TryReadEscape expects us to point to the 'u', and since it is by reference we need to do it beforehand.
  602. if (TryReadEscape(startingLocation, m_pchLast, &outChar))
  603. {
  604. this->RestoreMultiUnits(savedMultiUnits);
  605. Error(ERRIdAfterLit);
  606. }
  607. }
  608. if (Js::NumberUtilities::IsDigit(*startingLocation))
  609. {
  610. this->RestoreMultiUnits(savedMultiUnits);
  611. Error(ERRbadNumber);
  612. }
  613. return pchT;
  614. }
  615. template <typename EncodingPolicy>
  616. tokens Scanner<EncodingPolicy>::TryRescanRegExp()
  617. {
  618. EncodedCharPtr current = m_currentCharacter;
  619. tokens result = RescanRegExp();
  620. if (result == tkScanError)
  621. m_currentCharacter = current;
  622. return result;
  623. }
  624. template <typename EncodingPolicy>
  625. tokens Scanner<EncodingPolicy>::RescanRegExp()
  626. {
  627. #if DEBUG
  628. switch (m_ptoken->tk)
  629. {
  630. case tkDiv:
  631. Assert(m_currentCharacter == m_pchMinTok + 1);
  632. break;
  633. case tkAsgDiv:
  634. Assert(m_currentCharacter == m_pchMinTok + 2);
  635. break;
  636. default:
  637. AssertMsg(FALSE, "Who is calling RescanRegExp?");
  638. break;
  639. }
  640. #endif //DEBUG
  641. m_currentCharacter = m_pchMinTok;
  642. if (*m_currentCharacter != '/')
  643. Error(ERRnoSlash);
  644. m_currentCharacter++;
  645. tokens tk = tkNone;
  646. {
  647. ArenaAllocator alloc(_u("RescanRegExp"), m_parser->GetAllocator()->GetPageAllocator(), m_parser->GetAllocator()->outOfMemoryFunc);
  648. tk = ScanRegExpConstant(&alloc);
  649. }
  650. return tk;
  651. }
  652. template <typename EncodingPolicy>
  653. tokens Scanner<EncodingPolicy>::RescanRegExpNoAST()
  654. {
  655. #if DEBUG
  656. switch (m_ptoken->tk)
  657. {
  658. case tkDiv:
  659. Assert(m_currentCharacter == m_pchMinTok + 1);
  660. break;
  661. case tkAsgDiv:
  662. Assert(m_currentCharacter == m_pchMinTok + 2);
  663. break;
  664. default:
  665. AssertMsg(FALSE, "Who is calling RescanRegExpNoParseTree?");
  666. break;
  667. }
  668. #endif //DEBUG
  669. m_currentCharacter = m_pchMinTok;
  670. if (*m_currentCharacter != '/')
  671. Error(ERRnoSlash);
  672. m_currentCharacter++;
  673. tokens tk = tkNone;
  674. {
  675. ArenaAllocator alloc(_u("RescanRegExp"), m_parser->GetAllocator()->GetPageAllocator(), m_parser->GetAllocator()->outOfMemoryFunc);
  676. {
  677. tk = ScanRegExpConstantNoAST(&alloc);
  678. }
  679. }
  680. return tk;
  681. }
  682. template <typename EncodingPolicy>
  683. tokens Scanner<EncodingPolicy>::RescanRegExpTokenizer()
  684. {
  685. #if DEBUG
  686. switch (m_ptoken->tk)
  687. {
  688. case tkDiv:
  689. Assert(m_currentCharacter == m_pchMinTok + 1);
  690. break;
  691. case tkAsgDiv:
  692. Assert(m_currentCharacter == m_pchMinTok + 2);
  693. break;
  694. default:
  695. AssertMsg(FALSE, "Who is calling RescanRegExpNoParseTree?");
  696. break;
  697. }
  698. #endif //DEBUG
  699. m_currentCharacter = m_pchMinTok;
  700. if (*m_currentCharacter != '/')
  701. Error(ERRnoSlash);
  702. m_currentCharacter++;
  703. tokens tk = tkNone;
  704. ThreadContext *threadContext = ThreadContext::GetContextForCurrentThread();
  705. threadContext->EnsureRecycler();
  706. Js::TempArenaAllocatorObject *alloc = threadContext->GetTemporaryAllocator(_u("RescanRegExp"));
  707. TryFinally(
  708. [&]() /* try block */
  709. {
  710. tk = this->ScanRegExpConstantNoAST(alloc->GetAllocator());
  711. },
  712. [&](bool /* hasException */) /* finally block */
  713. {
  714. threadContext->ReleaseTemporaryAllocator(alloc);
  715. });
  716. return tk;
  717. }
  718. template <typename EncodingPolicy>
  719. tokens Scanner<EncodingPolicy>::ScanRegExpConstant(ArenaAllocator* alloc)
  720. {
  721. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackRegex);
  722. // SEE ALSO: RegexHelper::PrimCompileDynamic()
  723. #ifdef PROFILE_EXEC
  724. m_scriptContext->ProfileBegin(Js::RegexCompilePhase);
  725. #endif
  726. ArenaAllocator* ctAllocator = alloc;
  727. UnifiedRegex::StandardChars<EncodedChar>* standardEncodedChars = m_scriptContext->GetThreadContext()->GetStandardChars((EncodedChar*)0);
  728. UnifiedRegex::StandardChars<char16>* standardChars = m_scriptContext->GetThreadContext()->GetStandardChars((char16*)0);
  729. #if ENABLE_REGEX_CONFIG_OPTIONS
  730. UnifiedRegex::DebugWriter *w = 0;
  731. if (REGEX_CONFIG_FLAG(RegexDebug))
  732. w = m_scriptContext->GetRegexDebugWriter();
  733. if (REGEX_CONFIG_FLAG(RegexProfile))
  734. m_scriptContext->GetRegexStatsDatabase()->BeginProfile();
  735. #endif
  736. UnifiedRegex::Node* root = 0;
  737. charcount_t totalLen = 0, bodyChars = 0, totalChars = 0, bodyLen = 0;
  738. UnifiedRegex::RegexFlags flags = UnifiedRegex::NoRegexFlags;
  739. UnifiedRegex::Parser<EncodingPolicy, true> parser
  740. ( m_scriptContext
  741. , ctAllocator
  742. , standardEncodedChars
  743. , standardChars
  744. , this->IsUtf8()
  745. #if ENABLE_REGEX_CONFIG_OPTIONS
  746. , w
  747. #endif
  748. );
  749. try
  750. {
  751. root = parser.ParseLiteral(m_currentCharacter, m_pchLast, bodyLen, totalLen, bodyChars, totalChars, flags);
  752. }
  753. catch (UnifiedRegex::ParseError e)
  754. {
  755. #ifdef PROFILE_EXEC
  756. m_scriptContext->ProfileEnd(Js::RegexCompilePhase);
  757. #endif
  758. m_currentCharacter += e.encodedPos;
  759. Error(e.error);
  760. }
  761. UnifiedRegex::RegexPattern* pattern;
  762. if (m_parser->IsBackgroundParser())
  763. {
  764. // Avoid allocating pattern from recycler on background thread. The main thread will create the pattern
  765. // and hook it to this parse node.
  766. pattern = parser.template CompileProgram<false>(root, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, flags);
  767. }
  768. else
  769. {
  770. pattern = parser.template CompileProgram<true>(root, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, flags);
  771. }
  772. this->RestoreMultiUnits(this->m_cMultiUnits + parser.GetMultiUnits()); // m_currentCharacter changed, sync MultiUnits
  773. return m_ptoken->SetRegex(pattern, m_parser);
  774. }
  775. template<typename EncodingPolicy>
  776. tokens Scanner<EncodingPolicy>::ScanRegExpConstantNoAST(ArenaAllocator* alloc)
  777. {
  778. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackRegex);
  779. ThreadContext *threadContext = m_scriptContext->GetThreadContext();
  780. UnifiedRegex::StandardChars<EncodedChar>* standardEncodedChars = threadContext->GetStandardChars((EncodedChar*)0);
  781. UnifiedRegex::StandardChars<char16>* standardChars = threadContext->GetStandardChars((char16*)0);
  782. charcount_t totalLen = 0, bodyChars = 0, totalChars = 0, bodyLen = 0;
  783. UnifiedRegex::Parser<EncodingPolicy, true> parser
  784. ( m_scriptContext
  785. , alloc
  786. , standardEncodedChars
  787. , standardChars
  788. , this->IsUtf8()
  789. #if ENABLE_REGEX_CONFIG_OPTIONS
  790. , 0
  791. #endif
  792. );
  793. try
  794. {
  795. parser.ParseLiteralNoAST(m_currentCharacter, m_pchLast, bodyLen, totalLen, bodyChars, totalChars);
  796. }
  797. catch (UnifiedRegex::ParseError e)
  798. {
  799. m_currentCharacter += e.encodedPos;
  800. Error(e.error);
  801. // never reached
  802. }
  803. UnifiedRegex::RegexPattern* pattern = parser.template CompileProgram<false>(nullptr, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, UnifiedRegex::NoRegexFlags);
  804. Assert(pattern == nullptr); // BuildAST == false, CompileProgram should return nullptr
  805. this->RestoreMultiUnits(this->m_cMultiUnits + parser.GetMultiUnits()); // m_currentCharacter changed, sync MultiUnits
  806. return (m_ptoken->tk = tkRegExp);
  807. }
  808. template<typename EncodingPolicy>
  809. tokens Scanner<EncodingPolicy>::ScanStringTemplateBegin(EncodedCharPtr *pp)
  810. {
  811. // String template must begin with a string constant followed by '`' or '${'
  812. ScanStringConstant<true, true>('`', pp);
  813. OLECHAR ch;
  814. EncodedCharPtr last = m_pchLast;
  815. ch = this->ReadFirst(*pp, last);
  816. if (ch == '`')
  817. {
  818. // Simple string template - no substitutions
  819. return tkStrTmplBasic;
  820. }
  821. else if (ch == '$')
  822. {
  823. ch = this->ReadFirst(*pp, last);
  824. if (ch == '{')
  825. {
  826. // Next token after expr should be tkStrTmplMid or tkStrTmplEnd.
  827. // In string template scanning mode, we expect the next char to be '}'
  828. // and will treat it as the beginning of tkStrTmplEnd or tkStrTmplMid
  829. m_fStringTemplateDepth++;
  830. // Regular string template begin - next is first substitution
  831. return tkStrTmplBegin;
  832. }
  833. }
  834. // Error - make sure pointer stays at the last character of the error token instead of after it in the error case
  835. (*pp)--;
  836. return ScanError(m_currentCharacter, tkStrTmplBegin);
  837. }
  838. template<typename EncodingPolicy>
  839. tokens Scanner<EncodingPolicy>::ScanStringTemplateMiddleOrEnd(EncodedCharPtr *pp)
  840. {
  841. // String template middle and end tokens must begin with a string constant
  842. ScanStringConstant<true, true>('`', pp);
  843. OLECHAR ch;
  844. EncodedCharPtr last = m_pchLast;
  845. ch = this->ReadFirst(*pp, last);
  846. if (ch == '`')
  847. {
  848. // No longer in string template scanning mode
  849. m_fStringTemplateDepth--;
  850. // This is the last part of the template ...`
  851. return tkStrTmplEnd;
  852. }
  853. else if (ch == '$')
  854. {
  855. ch = this->ReadFirst(*pp, last);
  856. if (ch == '{')
  857. {
  858. // This is just another middle part of the template }...${
  859. return tkStrTmplMid;
  860. }
  861. }
  862. // Error - make sure pointer stays at the last character of the error token instead of after it in the error case
  863. (*pp)--;
  864. return ScanError(m_currentCharacter, tkStrTmplEnd);
  865. }
  866. /*****************************************************************************
  867. *
  868. * Parses a string constant. Note that the string value is stored in
  869. * a volatile buffer (or allocated on the heap if too long), and thus
  870. * the string should be saved off before the next token is scanned.
  871. */
  872. template<typename EncodingPolicy>
  873. template<bool stringTemplateMode, bool createRawString>
  874. tokens Scanner<EncodingPolicy>::ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp)
  875. {
  876. static_assert((stringTemplateMode && createRawString) || (!stringTemplateMode && !createRawString), "stringTemplateMode and createRawString must have the same value");
  877. OLECHAR ch, c, rawch;
  878. int wT;
  879. EncodedCharPtr p = *pp;
  880. EncodedCharPtr last = m_pchLast;
  881. // Reset
  882. m_OctOrLeadingZeroOnLastTKNumber = false;
  883. m_EscapeOnLastTkStrCon = FALSE;
  884. m_tempChBuf.Reset();
  885. // Use template parameter to gate raw string creation.
  886. // If createRawString is false, all these operations should be no-ops
  887. if (createRawString)
  888. {
  889. m_tempChBufSecondary.Reset();
  890. }
  891. for (;;)
  892. {
  893. switch ((rawch = ch = this->ReadFirst(p, last)))
  894. {
  895. case kchRET:
  896. if (stringTemplateMode)
  897. {
  898. if (this->PeekFirst(p, last) == kchNWL)
  899. {
  900. // Eat the <LF> char, ignore return
  901. this->ReadFirst(p, last);
  902. }
  903. // Both <CR> and <CR><LF> are normalized to <LF> in template cooked and raw values
  904. ch = rawch = kchNWL;
  905. }
  906. LEcmaLineBreak:
  907. // Fall through
  908. case kchNWL:
  909. if (stringTemplateMode)
  910. {
  911. // Notify the scanner to update current line, number of lines etc
  912. NotifyScannedNewLine();
  913. // We haven't updated m_currentCharacter yet, so make sure the MinLine info is correct in case we error out.
  914. m_pchMinLine = p;
  915. break;
  916. }
  917. m_currentCharacter = p - 1;
  918. Error(ERRnoStrEnd);
  919. case '"':
  920. case '\'':
  921. if (ch == delim)
  922. goto LBreak;
  923. break;
  924. case '`':
  925. // In string template scan mode, don't consume the '`' - we need to differentiate
  926. // between a closed string template and the expression open sequence - ${
  927. if (stringTemplateMode)
  928. {
  929. p--;
  930. goto LBreak;
  931. }
  932. // If we aren't scanning for a string template, do the default thing
  933. goto LMainDefault;
  934. case '$':
  935. // If we are parsing a string literal part of a string template, ${ indicates we need to switch
  936. // to parsing an expression.
  937. if (stringTemplateMode && this->PeekFirst(p, last) == '{')
  938. {
  939. // Rewind to the $ and return
  940. p--;
  941. goto LBreak;
  942. }
  943. // If we aren't scanning for a string template, do the default thing
  944. goto LMainDefault;
  945. case kchNUL:
  946. if (p > last)
  947. {
  948. m_currentCharacter = p - 1;
  949. Error(ERRnoStrEnd);
  950. }
  951. break;
  952. default:
  953. LMainDefault:
  954. if (this->IsMultiUnitChar(ch))
  955. {
  956. if ((ch == kchLS || ch == kchPS))
  957. {
  958. goto LEcmaLineBreak;
  959. }
  960. rawch = ch = this->template ReadRest<true>(ch, p, last);
  961. switch (ch)
  962. {
  963. case kchLS: // 0x2028, classifies as new line
  964. case kchPS: // 0x2029, classifies as new line
  965. goto LEcmaLineBreak;
  966. }
  967. }
  968. break;
  969. case kchBSL:
  970. // In raw mode '\\' is not an escape character, just add the char into the raw buffer.
  971. m_tempChBufSecondary.template AppendCh<createRawString>(ch);
  972. m_EscapeOnLastTkStrCon=TRUE;
  973. // In raw mode, we append the raw char itself and not the escaped value so save the char.
  974. rawch = ch = this->ReadFirst(p, last);
  975. codepoint_t codePoint = 0;
  976. uint errorType = (uint)ERRbadHexDigit;
  977. switch (ch)
  978. {
  979. case 'b':
  980. ch = 0x08;
  981. break;
  982. case 't':
  983. ch = 0x09;
  984. break;
  985. case 'v':
  986. ch = 0x0B; //Only in ES5 mode
  987. break; //same as default
  988. case 'n':
  989. ch = 0x0A;
  990. break;
  991. case 'f':
  992. ch = 0x0C;
  993. break;
  994. case 'r':
  995. ch = 0x0D;
  996. break;
  997. case 'x':
  998. // Insert the 'x' here before jumping to parse the hex digits.
  999. m_tempChBufSecondary.template AppendCh<createRawString>(ch);
  1000. // 2 hex digits
  1001. ch = 0;
  1002. goto LTwoHex;
  1003. case 'u':
  1004. // Raw string just inserts a 'u' here.
  1005. m_tempChBufSecondary.template AppendCh<createRawString>(ch);
  1006. ch = 0;
  1007. if (Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1008. goto LFourHex;
  1009. else if (c != '{' || !this->es6UnicodeMode)
  1010. goto ReturnScanError;
  1011. Assert(c == '{');
  1012. // c should definitely be a '{' which should be appended to the raw string.
  1013. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1014. //At least one digit is expected
  1015. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1016. {
  1017. goto ReturnScanError;
  1018. }
  1019. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1020. codePoint = static_cast<codepoint_t>(wT);
  1021. while(Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1022. {
  1023. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1024. codePoint <<= 4;
  1025. codePoint += static_cast<codepoint_t>(wT);
  1026. if (codePoint > 0x10FFFF)
  1027. {
  1028. errorType = (uint)ERRInvalidCodePoint;
  1029. goto ReturnScanError;
  1030. }
  1031. }
  1032. if (c != '}')
  1033. {
  1034. errorType = (uint)ERRMissingCurlyBrace;
  1035. goto ReturnScanError;
  1036. }
  1037. Assert(codePoint <= 0x10FFFF);
  1038. if (codePoint >= 0x10000)
  1039. {
  1040. OLECHAR lower = 0;
  1041. Js::NumberUtilities::CodePointAsSurrogatePair(codePoint, &lower, &ch);
  1042. m_tempChBuf.AppendCh(lower);
  1043. }
  1044. else
  1045. {
  1046. ch = (char16)codePoint;
  1047. }
  1048. // In raw mode we want the last hex character or the closing curly. c should hold one or the other.
  1049. if (createRawString)
  1050. rawch = c;
  1051. break;
  1052. LFourHex:
  1053. codePoint = 0x0;
  1054. // Append first hex digit character to the raw string.
  1055. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1056. codePoint += static_cast<codepoint_t>(wT * 0x1000);
  1057. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1058. goto ReturnScanError;
  1059. // Append fourth (or second) hex digit character to the raw string.
  1060. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1061. codePoint += static_cast<codepoint_t>(wT * 0x0100);
  1062. LTwoHex:
  1063. // This code path doesn't expect curly.
  1064. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1065. goto ReturnScanError;
  1066. // Append first hex digit character to the raw string.
  1067. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1068. codePoint += static_cast<codepoint_t>(wT * 0x0010);
  1069. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1070. goto ReturnScanError;
  1071. codePoint += static_cast<codepoint_t>(wT);
  1072. // In raw mode we want the last hex character or the closing curly. c should hold one or the other.
  1073. if (createRawString)
  1074. rawch = c;
  1075. if (codePoint < 0x10000)
  1076. {
  1077. ch = static_cast<OLECHAR>(codePoint);
  1078. }
  1079. else
  1080. {
  1081. goto ReturnScanError;
  1082. }
  1083. break;
  1084. case '0':
  1085. case '1':
  1086. case '2':
  1087. case '3':
  1088. // 1 to 3 octal digits
  1089. ch -= '0';
  1090. // Octal escape sequences are not allowed inside string template literals
  1091. if (stringTemplateMode)
  1092. {
  1093. c = this->PeekFirst(p, last);
  1094. if (ch != 0 || (c >= '0' && c <= '7'))
  1095. {
  1096. errorType = (uint)ERRES5NoOctal;
  1097. goto ReturnScanError;
  1098. }
  1099. break;
  1100. }
  1101. wT = (c = this->ReadFirst(p, last)) - '0';
  1102. if ((char16)wT > 7)
  1103. {
  1104. if (ch != 0 || ((char16)wT <= 9))
  1105. {
  1106. m_OctOrLeadingZeroOnLastTKNumber = true;
  1107. }
  1108. p--;
  1109. break;
  1110. }
  1111. m_OctOrLeadingZeroOnLastTKNumber = true;
  1112. ch = static_cast< OLECHAR >(ch * 8 + wT);
  1113. goto LOneOctal;
  1114. case '4':
  1115. case '5':
  1116. case '6':
  1117. case '7':
  1118. // 1 to 2 octal digits
  1119. // Octal escape sequences are not allowed inside string template literals
  1120. if (stringTemplateMode)
  1121. {
  1122. errorType = (uint)ERRES5NoOctal;
  1123. goto ReturnScanError;
  1124. }
  1125. ch -= '0';
  1126. m_OctOrLeadingZeroOnLastTKNumber = true;
  1127. LOneOctal:
  1128. wT = (c = this->ReadFirst(p, last)) - '0';
  1129. if ((char16)wT > 7)
  1130. {
  1131. p--;
  1132. break;
  1133. }
  1134. ch = static_cast< OLECHAR >(ch * 8 + wT);
  1135. break;
  1136. case kchRET: // 0xD
  1137. if (stringTemplateMode)
  1138. {
  1139. // If this is \<CR><LF> we can eat the <LF> right now
  1140. if (this->PeekFirst(p, last) == kchNWL)
  1141. {
  1142. // Eat the <LF> char, ignore return
  1143. this->ReadFirst(p, last);
  1144. }
  1145. // Both \<CR> and \<CR><LF> are normalized to \<LF> in template raw string
  1146. rawch = kchNWL;
  1147. }
  1148. case kchLS: // 0x2028, classifies as new line
  1149. case kchPS: // 0x2029, classifies as new line
  1150. case kchNWL: // 0xA
  1151. LEcmaEscapeLineBreak:
  1152. if (stringTemplateMode)
  1153. {
  1154. // We're going to ignore the line continuation tokens for the cooked strings, but we need to append the token for raw strings
  1155. m_tempChBufSecondary.template AppendCh<createRawString>(rawch);
  1156. // Template literal strings ignore all escaped line continuation tokens
  1157. NotifyScannedNewLine();
  1158. // We haven't updated m_currentCharacter yet, so make sure the MinLine info is correct in case we error out.
  1159. m_pchMinLine = p;
  1160. continue;
  1161. }
  1162. m_currentCharacter = p;
  1163. ScanNewLine(ch);
  1164. p = m_currentCharacter;
  1165. continue;
  1166. case 0:
  1167. if (p >= last)
  1168. {
  1169. errorType = (uint)ERRnoStrEnd;
  1170. ReturnScanError:
  1171. m_currentCharacter = p - 1;
  1172. Error(errorType);
  1173. }
  1174. else if (stringTemplateMode)
  1175. {
  1176. // Escaped null character is translated into 0x0030 for raw template literals
  1177. rawch = 0x0030;
  1178. }
  1179. break;
  1180. default:
  1181. if (this->IsMultiUnitChar(ch))
  1182. {
  1183. rawch = ch = this->template ReadRest<true>(ch, p, last);
  1184. switch (ch)
  1185. {
  1186. case kchLS:
  1187. case kchPS:
  1188. goto LEcmaEscapeLineBreak;
  1189. }
  1190. }
  1191. break;
  1192. }
  1193. break;
  1194. }
  1195. m_tempChBuf.AppendCh(ch);
  1196. m_tempChBufSecondary.template AppendCh<createRawString>(rawch);
  1197. }
  1198. LBreak:
  1199. bool createPid = true;
  1200. if ((m_DeferredParseFlags & ScanFlagSuppressStrPid) != 0)
  1201. {
  1202. createPid = false;
  1203. if ((m_tempChBuf.m_ichCur == 10) && (0 == memcmp(_u("use strict"), m_tempChBuf.m_prgch, m_tempChBuf.m_ichCur * sizeof(OLECHAR))))
  1204. {
  1205. createPid = true;
  1206. }
  1207. }
  1208. if (createPid)
  1209. {
  1210. m_ptoken->SetIdentifier(this->GetHashTbl()->PidHashNameLen(m_tempChBuf.m_prgch, m_tempChBuf.m_ichCur));
  1211. }
  1212. else
  1213. {
  1214. m_ptoken->SetIdentifier(NULL);
  1215. }
  1216. m_scanState = ScanStateNormal;
  1217. m_doubleQuoteOnLastTkStrCon = '"' == delim;
  1218. *pp = p;
  1219. return tkStrCon;
  1220. }
  1221. template<typename EncodingPolicy>
  1222. tokens Scanner<EncodingPolicy>::ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp)
  1223. {
  1224. return ScanStringConstant<false, false>(delim, pp);
  1225. }
  1226. /*****************************************************************************
  1227. *
  1228. * Consume a C-style comment.
  1229. */
  1230. template<typename EncodingPolicy>
  1231. tokens Scanner<EncodingPolicy>::SkipComment(EncodedCharPtr *pp, /* out */ bool* containTypeDef)
  1232. {
  1233. Assert(containTypeDef != nullptr);
  1234. EncodedCharPtr p = *pp;
  1235. *containTypeDef = false;
  1236. EncodedCharPtr last = m_pchLast;
  1237. OLECHAR ch;
  1238. for (;;)
  1239. {
  1240. switch((ch = this->ReadFirst(p, last)))
  1241. {
  1242. case '*':
  1243. if (*p == '/')
  1244. {
  1245. *pp = p + 1;
  1246. return tkNone;
  1247. }
  1248. break;
  1249. // ES 2015 11.3 Line Terminators
  1250. case kchLS: // 0x2028, classifies as new line
  1251. case kchPS: // 0x2029, classifies as new line
  1252. LEcmaLineBreak:
  1253. goto LLineBreak;
  1254. case kchRET:
  1255. case kchNWL:
  1256. LLineBreak:
  1257. m_fHadEol = TRUE;
  1258. m_currentCharacter = p;
  1259. ScanNewLine(ch);
  1260. p = m_currentCharacter;
  1261. break;
  1262. case kchNUL:
  1263. if (p >= last)
  1264. {
  1265. m_currentCharacter = p - 1;
  1266. *pp = p - 1;
  1267. Error(ERRnoCmtEnd);
  1268. }
  1269. break;
  1270. default:
  1271. if (this->IsMultiUnitChar(ch))
  1272. {
  1273. ch = this->template ReadRest<true>(ch, p, last);
  1274. switch (ch)
  1275. {
  1276. case kchLS:
  1277. case kchPS:
  1278. goto LEcmaLineBreak;
  1279. }
  1280. }
  1281. break;
  1282. }
  1283. }
  1284. }
  1285. /*****************************************************************************
  1286. *
  1287. * We've encountered a newline - update various counters and things.
  1288. */
  1289. template<typename EncodingPolicy>
  1290. void Scanner<EncodingPolicy>::ScanNewLine(uint ch)
  1291. {
  1292. if (ch == '\r' && PeekNextChar() == '\n')
  1293. {
  1294. ReadNextChar();
  1295. }
  1296. NotifyScannedNewLine();
  1297. }
  1298. /*****************************************************************************
  1299. *
  1300. * We've encountered a newline - update various counters and things.
  1301. */
  1302. template<typename EncodingPolicy>
  1303. void Scanner<EncodingPolicy>::NotifyScannedNewLine()
  1304. {
  1305. // update in scanner: previous line, current line, number of lines.
  1306. m_line++;
  1307. m_pchPrevLine = m_pchMinLine;
  1308. m_pchMinLine = m_currentCharacter;
  1309. m_cMinLineMultiUnits = this->m_cMultiUnits;
  1310. }
  1311. /*****************************************************************************
  1312. *
  1313. * Delivers a token stream.
  1314. */
  1315. template<typename EncodingPolicy>
  1316. tokens Scanner<EncodingPolicy>::ScanForcingPid()
  1317. {
  1318. if (m_DeferredParseFlags != ScanFlagNone)
  1319. {
  1320. BYTE deferredParseFlagsSave = m_DeferredParseFlags;
  1321. m_DeferredParseFlags = ScanFlagNone;
  1322. tokens result = tkEOF;
  1323. TryFinally(
  1324. [&]() /* try block */
  1325. {
  1326. result = this->Scan();
  1327. },
  1328. [&](bool) /* finally block */
  1329. {
  1330. this->m_DeferredParseFlags = deferredParseFlagsSave;
  1331. });
  1332. return result;
  1333. }
  1334. return Scan();
  1335. }
  1336. template<typename EncodingPolicy>
  1337. tokens Scanner<EncodingPolicy>::Scan()
  1338. {
  1339. return ScanCore(true);
  1340. }
  1341. template<typename EncodingPolicy>
  1342. tokens Scanner<EncodingPolicy>::ScanNoKeywords()
  1343. {
  1344. return ScanCore(false);
  1345. }
  1346. template<typename EncodingPolicy>
  1347. tokens Scanner<EncodingPolicy>::ScanAhead()
  1348. {
  1349. return ScanNoKeywords();
  1350. }
  1351. template<typename EncodingPolicy>
  1352. tokens Scanner<EncodingPolicy>::ScanCore(bool identifyKwds)
  1353. {
  1354. codepoint_t ch;
  1355. OLECHAR firstChar;
  1356. OLECHAR secondChar;
  1357. EncodedCharPtr pchT;
  1358. size_t multiUnits = 0;
  1359. EncodedCharPtr p = m_currentCharacter;
  1360. EncodedCharPtr last = m_pchLast;
  1361. bool seenDelimitedCommentEnd = false;
  1362. // store the last token
  1363. m_tkPrevious = m_ptoken->tk;
  1364. m_iecpLimTokPrevious = IecpLimTok(); // Introduced for use by lambda parsing to find correct span of expression lambdas
  1365. m_ichLimTokPrevious = IchLimTok();
  1366. size_t savedMultiUnits = this->m_cMultiUnits;
  1367. if (p >= last)
  1368. {
  1369. m_pchMinTok = p;
  1370. m_cMinTokMultiUnits = this->m_cMultiUnits;
  1371. goto LEof;
  1372. }
  1373. tokens token;
  1374. m_fHadEol = FALSE;
  1375. CharTypes chType;
  1376. charcount_t commentStartLine;
  1377. if (m_scanState && *p != 0)
  1378. {
  1379. if (m_scanState == ScanStateStringTemplateMiddleOrEnd)
  1380. {
  1381. AssertMsg(m_fStringTemplateDepth > 0,
  1382. "Shouldn't be trying to parse a string template end or middle token if we aren't scanning a string template");
  1383. m_scanState = ScanStateNormal;
  1384. pchT = p;
  1385. token = ScanStringTemplateMiddleOrEnd(&pchT);
  1386. p = pchT;
  1387. goto LDone;
  1388. }
  1389. }
  1390. for (;;)
  1391. {
  1392. LLoop:
  1393. m_pchMinTok = p;
  1394. m_cMinTokMultiUnits = this->m_cMultiUnits;
  1395. ch = this->ReadFirst(p, last);
  1396. #if DEBUG
  1397. chType = this->charClassifier->GetCharType((OLECHAR)ch);
  1398. #endif
  1399. switch (ch)
  1400. {
  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. token = tkDiv;
  1696. switch(this->PeekFirst(p, last))
  1697. {
  1698. case '=':
  1699. p++;
  1700. token = tkAsgDiv;
  1701. break;
  1702. case '/':
  1703. if (p >= last)
  1704. {
  1705. AssertMsg(!m_fIsModuleCode, "Do we have other line comment cases scanning pass last?");
  1706. // Effective source length may have excluded HTMLCommentSuffix "//... -->". If we are scanning
  1707. // those, we have passed "last" already. Move back and return EOF.
  1708. p = last;
  1709. goto LEof;
  1710. }
  1711. ch = *++p;
  1712. firstChar = (OLECHAR)ch;
  1713. LSkipLineComment:
  1714. pchT = NULL;
  1715. for (;;)
  1716. {
  1717. switch ((ch = this->ReadFirst(p, last)))
  1718. {
  1719. case kchLS: // 0x2028, classifies as new line
  1720. case kchPS: // 0x2029, classifies as new line
  1721. LEcmaCommentLineBreak:
  1722. // kchPS and kchLS are more than one unit in UTF-8.
  1723. if (pchT)
  1724. {
  1725. // kchPS and kchLS are more than one unit in UTF-8.
  1726. p = pchT;
  1727. }
  1728. else
  1729. {
  1730. // But only a single code unit in UTF16
  1731. p--;
  1732. }
  1733. this->RestoreMultiUnits(multiUnits);
  1734. goto LCommentLineBreak;
  1735. case kchNWL:
  1736. case kchRET:
  1737. p--;
  1738. LCommentLineBreak:
  1739. // Subtract the comment length from the total char count for the purpose
  1740. // of deciding whether to defer AST and byte code generation.
  1741. m_parser->ReduceDeferredScriptLength((ULONG)(p - m_pchMinTok));
  1742. break;
  1743. case kchNUL:
  1744. // Because we used ReadFirst, we have advanced p. The character that we are looking at is actually is p - 1.
  1745. // 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
  1746. // Only if p > last that we have pass the source buffer and consider it a line break
  1747. if (p > last)
  1748. {
  1749. p--;
  1750. goto LCommentLineBreak;
  1751. }
  1752. continue;
  1753. default:
  1754. if (this->IsMultiUnitChar((OLECHAR)ch))
  1755. {
  1756. pchT = p - 1;
  1757. multiUnits = this->m_cMultiUnits;
  1758. switch (ch = this->template ReadRest<true>((OLECHAR)ch, p, last))
  1759. {
  1760. case kchLS:
  1761. case kchPS:
  1762. goto LEcmaCommentLineBreak;
  1763. }
  1764. }
  1765. continue;
  1766. }
  1767. break;
  1768. }
  1769. continue;
  1770. case '*':
  1771. ch = *++p;
  1772. firstChar = (OLECHAR)ch;
  1773. if ((p + 1) < last)
  1774. {
  1775. secondChar = (OLECHAR)(*(p + 1));
  1776. }
  1777. else
  1778. {
  1779. secondChar = '\0';
  1780. }
  1781. pchT = p;
  1782. commentStartLine = m_line;
  1783. bool containTypeDef;
  1784. if (tkNone == (token = SkipComment(&pchT, &containTypeDef)))
  1785. {
  1786. // Subtract the comment length from the total char count for the purpose
  1787. // of deciding whether to defer AST and byte code generation.
  1788. m_parser->ReduceDeferredScriptLength((ULONG)(pchT - m_pchMinTok));
  1789. p = pchT;
  1790. seenDelimitedCommentEnd = true;
  1791. goto LLoop;
  1792. }
  1793. p = pchT;
  1794. break;
  1795. }
  1796. break;
  1797. case '%':
  1798. Assert(chType == _C_PCT);
  1799. token = tkPct;
  1800. if (this->PeekFirst(p, last) == '=')
  1801. {
  1802. p++;
  1803. token = tkAsgMod;
  1804. }
  1805. break;
  1806. case '<':
  1807. Assert(chType == _C_LT);
  1808. token = tkLT;
  1809. switch (this->PeekFirst(p, last))
  1810. {
  1811. case '=':
  1812. p++;
  1813. token = tkLE;
  1814. break;
  1815. case '<':
  1816. p++;
  1817. token = tkLsh;
  1818. if (this->PeekFirst(p, last) == '=')
  1819. {
  1820. p++;
  1821. token = tkAsgLsh;
  1822. break;
  1823. }
  1824. break;
  1825. case '!':
  1826. // ES 2015 B.1.3 - HTML comments are only allowed when parsing non-module code.
  1827. if (!m_fIsModuleCode && this->PeekFirst(p + 1, last) == '-' && this->PeekFirst(p + 2, last) == '-')
  1828. {
  1829. // This is a "<!--" comment - treat as //
  1830. if (p >= last)
  1831. {
  1832. // Effective source length may have excluded HTMLCommentSuffix "<!-- ... -->". If we are scanning
  1833. // those, we have passed "last" already. Move back and return EOF.
  1834. p = last;
  1835. goto LEof;
  1836. }
  1837. firstChar = '!';
  1838. goto LSkipLineComment;
  1839. }
  1840. break;
  1841. }
  1842. break;
  1843. case '>':
  1844. Assert(chType == _C_GT);
  1845. token = tkGT;
  1846. switch (this->PeekFirst(p, last))
  1847. {
  1848. case '=':
  1849. p++;
  1850. token = tkGE;
  1851. break;
  1852. case '>':
  1853. p++;
  1854. token = tkRsh;
  1855. switch (this->PeekFirst(p, last))
  1856. {
  1857. case '=':
  1858. p++;
  1859. token = tkAsgRsh;
  1860. break;
  1861. case '>':
  1862. p++;
  1863. token = tkRs2;
  1864. if (*p == '=')
  1865. {
  1866. p++;
  1867. token = tkAsgRs2;
  1868. }
  1869. break;
  1870. }
  1871. break;
  1872. }
  1873. break;
  1874. case '^':
  1875. Assert(chType == _C_XOR);
  1876. token = tkXor;
  1877. if (this->PeekFirst(p, last) == '=')
  1878. {
  1879. p++;
  1880. token = tkAsgXor;
  1881. }
  1882. break;
  1883. case '|':
  1884. Assert(chType == _C_BAR);
  1885. token = tkOr;
  1886. switch (this->PeekFirst(p, last))
  1887. {
  1888. case '=':
  1889. p++;
  1890. token = tkAsgOr;
  1891. break;
  1892. case '|':
  1893. p++;
  1894. token = tkLogOr;
  1895. break;
  1896. }
  1897. break;
  1898. case '&':
  1899. Assert(chType == _C_AMP);
  1900. token = tkAnd;
  1901. switch (this->PeekFirst(p, last))
  1902. {
  1903. case '=':
  1904. p++;
  1905. token = tkAsgAnd;
  1906. break;
  1907. case '&':
  1908. p++;
  1909. token = tkLogAnd;
  1910. break;
  1911. }
  1912. break;
  1913. case '\'':
  1914. case '"':
  1915. Assert(chType == _C_QUO || chType == _C_APO);
  1916. pchT = p;
  1917. token = this->ScanStringConstant((OLECHAR)ch, &pchT);
  1918. p = pchT;
  1919. break;
  1920. }
  1921. break;
  1922. }
  1923. LDone:
  1924. m_currentCharacter = p;
  1925. return (m_ptoken->tk = token);
  1926. }
  1927. template <typename EncodingPolicy>
  1928. IdentPtr Scanner<EncodingPolicy>::GetSecondaryBufferAsPid()
  1929. {
  1930. bool createPid = true;
  1931. if ((m_DeferredParseFlags & ScanFlagSuppressStrPid) != 0)
  1932. {
  1933. createPid = false;
  1934. }
  1935. if (createPid)
  1936. {
  1937. return this->GetHashTbl()->PidHashNameLen(m_tempChBufSecondary.m_prgch, m_tempChBufSecondary.m_ichCur);
  1938. }
  1939. else
  1940. {
  1941. return nullptr;
  1942. }
  1943. }
  1944. template <typename EncodingPolicy>
  1945. LPCOLESTR Scanner<EncodingPolicy>::StringFromLong(int32 lw)
  1946. {
  1947. _ltow_s(lw, m_tempChBuf.m_prgch, m_tempChBuf.m_cchMax, 10);
  1948. return m_tempChBuf.m_prgch;
  1949. }
  1950. template <typename EncodingPolicy>
  1951. IdentPtr Scanner<EncodingPolicy>::PidFromLong(int32 lw)
  1952. {
  1953. return this->GetHashTbl()->PidHashName(StringFromLong(lw));
  1954. }
  1955. template <typename EncodingPolicy>
  1956. LPCOLESTR Scanner<EncodingPolicy>::StringFromDbl(double dbl)
  1957. {
  1958. if (!Js::NumberUtilities::FDblToStr(dbl, m_tempChBuf.m_prgch, m_tempChBuf.m_cchMax))
  1959. {
  1960. Error(ERRnoMemory);
  1961. }
  1962. return m_tempChBuf.m_prgch;
  1963. }
  1964. template <typename EncodingPolicy>
  1965. IdentPtr Scanner<EncodingPolicy>::PidFromDbl(double dbl)
  1966. {
  1967. return this->GetHashTbl()->PidHashName(StringFromDbl(dbl));
  1968. }
  1969. template <typename EncodingPolicy>
  1970. void Scanner<EncodingPolicy>::Capture(_Out_ RestorePoint* restorePoint)
  1971. {
  1972. Capture(restorePoint, 0, 0);
  1973. }
  1974. template <typename EncodingPolicy>
  1975. void Scanner<EncodingPolicy>::Capture(_Out_ RestorePoint* restorePoint, uint functionIdIncrement, size_t lengthDecr)
  1976. {
  1977. restorePoint->m_ichMinTok = this->IchMinTok();
  1978. restorePoint->m_ichMinLine = this->IchMinLine();
  1979. restorePoint->m_cMinTokMultiUnits = this->m_cMinTokMultiUnits;
  1980. restorePoint->m_cMinLineMultiUnits = this->m_cMinLineMultiUnits;
  1981. restorePoint->m_line = this->m_line;
  1982. restorePoint->m_fHadEol = this->m_fHadEol;
  1983. restorePoint->functionIdIncrement = functionIdIncrement;
  1984. restorePoint->lengthDecr = lengthDecr;
  1985. #ifdef DEBUG
  1986. restorePoint->m_cMultiUnits = this->m_cMultiUnits;
  1987. #endif
  1988. }
  1989. template <typename EncodingPolicy>
  1990. void Scanner<EncodingPolicy>::SeekTo(const RestorePoint& restorePoint)
  1991. {
  1992. SeekAndScan<false>(restorePoint);
  1993. }
  1994. template <typename EncodingPolicy>
  1995. void Scanner<EncodingPolicy>::SeekToForcingPid(const RestorePoint& restorePoint)
  1996. {
  1997. SeekAndScan<true>(restorePoint);
  1998. }
  1999. template <typename EncodingPolicy>
  2000. template <bool forcePid>
  2001. void Scanner<EncodingPolicy>::SeekAndScan(const RestorePoint& restorePoint)
  2002. {
  2003. this->m_currentCharacter = this->m_pchBase + restorePoint.m_ichMinTok + restorePoint.m_cMinTokMultiUnits;
  2004. this->m_pchMinLine = this->m_pchBase + restorePoint.m_ichMinLine + restorePoint.m_cMinLineMultiUnits;
  2005. this->m_cMinLineMultiUnits = restorePoint.m_cMinLineMultiUnits;
  2006. this->RestoreMultiUnits(restorePoint.m_cMinTokMultiUnits);
  2007. if (forcePid)
  2008. {
  2009. this->ScanForcingPid();
  2010. }
  2011. else
  2012. {
  2013. this->Scan();
  2014. }
  2015. this->m_line = restorePoint.m_line;
  2016. this->m_fHadEol = restorePoint.m_fHadEol;
  2017. this->m_parser->ReduceDeferredScriptLength(restorePoint.lengthDecr);
  2018. Assert(this->m_cMultiUnits == restorePoint.m_cMultiUnits);
  2019. }
  2020. template <typename EncodingPolicy>
  2021. void Scanner<EncodingPolicy>::SeekTo(const RestorePoint& restorePoint, uint *nextFunctionId)
  2022. {
  2023. SeekTo(restorePoint);
  2024. *nextFunctionId += restorePoint.functionIdIncrement;
  2025. }
  2026. // Called by CompileScriptException::ProcessError to retrieve a BSTR for the line on which an error occurred.
  2027. template<typename EncodingPolicy>
  2028. HRESULT Scanner<EncodingPolicy>::SysAllocErrorLine(int32 ichMinLine, __out BSTR* pbstrLine)
  2029. {
  2030. if( !pbstrLine )
  2031. {
  2032. return E_POINTER;
  2033. }
  2034. // If we overflow the string, we have a serious problem...
  2035. if (ichMinLine < 0 || static_cast<size_t>(ichMinLine) > AdjustedLength() )
  2036. {
  2037. return E_UNEXPECTED;
  2038. }
  2039. typename EncodingPolicy::EncodedCharPtr pStart = static_cast<size_t>(ichMinLine) == IchMinLine() ? m_pchMinLine : m_pchBase + this->CharacterOffsetToUnitOffset(m_pchBase, m_currentCharacter, m_pchLast, ichMinLine);
  2040. // Determine the length by scanning for the next newline
  2041. charcount_t cch = LineLength(pStart, m_pchLast);
  2042. Assert(cch <= LONG_MAX);
  2043. typename EncodingPolicy::EncodedCharPtr pEnd = static_cast<size_t>(ichMinLine) == IchMinLine() ? m_pchMinLine + cch : m_pchBase + this->CharacterOffsetToUnitOffset(m_pchBase, m_currentCharacter, m_pchLast, cch);
  2044. *pbstrLine = SysAllocStringLen(NULL, cch);
  2045. if (!*pbstrLine)
  2046. {
  2047. return E_OUTOFMEMORY;
  2048. }
  2049. this->ConvertToUnicode(*pbstrLine, cch, pStart, pEnd);
  2050. return S_OK;
  2051. }
  2052. template class Scanner<NotNullTerminatedUTF8EncodingPolicy>;