Scan.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331
  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, bool& likelyInt)
  500. {
  501. EncodedCharPtr last = m_pchLast;
  502. EncodedCharPtr pchT = nullptr;
  503. bool baseSpecified = false;
  504. likelyInt = true;
  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. likelyInt = false;
  528. // Floating point
  529. goto LFloat;
  530. case 'x':
  531. case 'X':
  532. // Hex
  533. *pdbl = Js::NumberUtilities::DblFromHex(p + 2, &pchT);
  534. baseSpecifierCheck();
  535. goto LIdCheck;
  536. case 'o':
  537. case 'O':
  538. // Octal
  539. *pdbl = Js::NumberUtilities::DblFromOctal(p + 2, &pchT);
  540. baseSpecifierCheck();
  541. goto LIdCheck;
  542. case 'b':
  543. case 'B':
  544. // Binary
  545. *pdbl = Js::NumberUtilities::DblFromBinary(p + 2, &pchT);
  546. baseSpecifierCheck();
  547. goto LIdCheck;
  548. default:
  549. // Octal
  550. *pdbl = Js::NumberUtilities::DblFromOctal(p, &pchT);
  551. Assert(pchT > p);
  552. #if !SOURCERELEASE
  553. // If an octal literal is malformed then it is in fact a decimal literal.
  554. #endif // !SOURCERELEASE
  555. if(*pdbl != 0 || pchT > p + 1)
  556. m_OctOrLeadingZeroOnLastTKNumber = true; //report as an octal or hex for JSON when leading 0. Just '0' is ok
  557. switch (*pchT)
  558. {
  559. case '8':
  560. case '9':
  561. // case 'e':
  562. // case 'E':
  563. // case '.':
  564. m_OctOrLeadingZeroOnLastTKNumber = false; //08... or 09....
  565. goto LFloat;
  566. }
  567. goto LIdCheck;
  568. }
  569. }
  570. else
  571. {
  572. LFloat:
  573. *pdbl = Js::NumberUtilities::StrToDbl(p, &pchT, likelyInt);
  574. Assert(pchT == p || !Js::NumberUtilities::IsNan(*pdbl));
  575. // fall through to LIdCheck
  576. }
  577. LIdCheck:
  578. // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
  579. // The SourceCharacter immediately following a NumericLiteral must not be an IdentifierStart or DecimalDigit.
  580. // For example : 3in is an error and not the two input elements 3 and in
  581. // If a base was speficied, use the first character denoting the constant. In this case, pchT is pointing to the base specifier.
  582. EncodedCharPtr startingLocation = baseSpecified ? pchT + 1 : pchT;
  583. codepoint_t outChar = *startingLocation;
  584. if (this->IsMultiUnitChar((OLECHAR)outChar))
  585. {
  586. outChar = this->template ReadRest<true>((OLECHAR)outChar, startingLocation, last);
  587. }
  588. if (this->charClassifier->IsIdStart(outChar))
  589. {
  590. Error(ERRIdAfterLit);
  591. }
  592. // IsIdStart does not cover the unicode escape case. Try to read a unicode escape from the 'u' char.
  593. if (*pchT == '\\')
  594. {
  595. startingLocation++; // TryReadEscape expects us to point to the 'u', and since it is by reference we need to do it beforehand.
  596. if (TryReadEscape(startingLocation, m_pchLast, &outChar))
  597. {
  598. Error(ERRIdAfterLit);
  599. }
  600. }
  601. if (Js::NumberUtilities::IsDigit(*startingLocation))
  602. {
  603. Error(ERRbadNumber);
  604. }
  605. return pchT;
  606. }
  607. template <typename EncodingPolicy>
  608. tokens Scanner<EncodingPolicy>::TryRescanRegExp()
  609. {
  610. EncodedCharPtr current = m_currentCharacter;
  611. tokens result = RescanRegExp();
  612. if (result == tkScanError)
  613. m_currentCharacter = current;
  614. return result;
  615. }
  616. template <typename EncodingPolicy>
  617. tokens Scanner<EncodingPolicy>::RescanRegExp()
  618. {
  619. #if DEBUG
  620. switch (m_ptoken->tk)
  621. {
  622. case tkDiv:
  623. Assert(m_currentCharacter == m_pchMinTok + 1);
  624. break;
  625. case tkAsgDiv:
  626. Assert(m_currentCharacter == m_pchMinTok + 2);
  627. break;
  628. default:
  629. AssertMsg(FALSE, "Who is calling RescanRegExp?");
  630. break;
  631. }
  632. #endif //DEBUG
  633. m_currentCharacter = m_pchMinTok;
  634. if (*m_currentCharacter != '/')
  635. Error(ERRnoSlash);
  636. m_currentCharacter++;
  637. tokens tk = tkNone;
  638. {
  639. ArenaAllocator alloc(_u("RescanRegExp"), m_parser->GetAllocator()->GetPageAllocator(), m_parser->GetAllocator()->outOfMemoryFunc);
  640. tk = ScanRegExpConstant(&alloc);
  641. }
  642. return tk;
  643. }
  644. template <typename EncodingPolicy>
  645. tokens Scanner<EncodingPolicy>::RescanRegExpNoAST()
  646. {
  647. #if DEBUG
  648. switch (m_ptoken->tk)
  649. {
  650. case tkDiv:
  651. Assert(m_currentCharacter == m_pchMinTok + 1);
  652. break;
  653. case tkAsgDiv:
  654. Assert(m_currentCharacter == m_pchMinTok + 2);
  655. break;
  656. default:
  657. AssertMsg(FALSE, "Who is calling RescanRegExpNoParseTree?");
  658. break;
  659. }
  660. #endif //DEBUG
  661. m_currentCharacter = m_pchMinTok;
  662. if (*m_currentCharacter != '/')
  663. Error(ERRnoSlash);
  664. m_currentCharacter++;
  665. tokens tk = tkNone;
  666. {
  667. ArenaAllocator alloc(_u("RescanRegExp"), m_parser->GetAllocator()->GetPageAllocator(), m_parser->GetAllocator()->outOfMemoryFunc);
  668. {
  669. tk = ScanRegExpConstantNoAST(&alloc);
  670. }
  671. }
  672. return tk;
  673. }
  674. template <typename EncodingPolicy>
  675. tokens Scanner<EncodingPolicy>::RescanRegExpTokenizer()
  676. {
  677. #if DEBUG
  678. switch (m_ptoken->tk)
  679. {
  680. case tkDiv:
  681. Assert(m_currentCharacter == m_pchMinTok + 1);
  682. break;
  683. case tkAsgDiv:
  684. Assert(m_currentCharacter == m_pchMinTok + 2);
  685. break;
  686. default:
  687. AssertMsg(FALSE, "Who is calling RescanRegExpNoParseTree?");
  688. break;
  689. }
  690. #endif //DEBUG
  691. m_currentCharacter = m_pchMinTok;
  692. if (*m_currentCharacter != '/')
  693. Error(ERRnoSlash);
  694. m_currentCharacter++;
  695. tokens tk = tkNone;
  696. ThreadContext *threadContext = ThreadContext::GetContextForCurrentThread();
  697. threadContext->EnsureRecycler();
  698. Js::TempArenaAllocatorObject *alloc = threadContext->GetTemporaryAllocator(_u("RescanRegExp"));
  699. TryFinally(
  700. [&]() /* try block */
  701. {
  702. tk = this->ScanRegExpConstantNoAST(alloc->GetAllocator());
  703. },
  704. [&](bool /* hasException */) /* finally block */
  705. {
  706. threadContext->ReleaseTemporaryAllocator(alloc);
  707. });
  708. return tk;
  709. }
  710. template <typename EncodingPolicy>
  711. tokens Scanner<EncodingPolicy>::ScanRegExpConstant(ArenaAllocator* alloc)
  712. {
  713. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackRegex);
  714. // SEE ALSO: RegexHelper::PrimCompileDynamic()
  715. #ifdef PROFILE_EXEC
  716. m_scriptContext->ProfileBegin(Js::RegexCompilePhase);
  717. #endif
  718. ArenaAllocator* ctAllocator = alloc;
  719. UnifiedRegex::StandardChars<EncodedChar>* standardEncodedChars = m_scriptContext->GetThreadContext()->GetStandardChars((EncodedChar*)0);
  720. UnifiedRegex::StandardChars<char16>* standardChars = m_scriptContext->GetThreadContext()->GetStandardChars((char16*)0);
  721. #if ENABLE_REGEX_CONFIG_OPTIONS
  722. UnifiedRegex::DebugWriter *w = 0;
  723. if (REGEX_CONFIG_FLAG(RegexDebug))
  724. w = m_scriptContext->GetRegexDebugWriter();
  725. if (REGEX_CONFIG_FLAG(RegexProfile))
  726. m_scriptContext->GetRegexStatsDatabase()->BeginProfile();
  727. #endif
  728. UnifiedRegex::Node* root = 0;
  729. charcount_t totalLen = 0, bodyChars = 0, totalChars = 0, bodyLen = 0;
  730. UnifiedRegex::RegexFlags flags = UnifiedRegex::NoRegexFlags;
  731. UnifiedRegex::Parser<EncodingPolicy, true> parser
  732. ( m_scriptContext
  733. , ctAllocator
  734. , standardEncodedChars
  735. , standardChars
  736. , this->IsUtf8()
  737. #if ENABLE_REGEX_CONFIG_OPTIONS
  738. , w
  739. #endif
  740. );
  741. try
  742. {
  743. root = parser.ParseLiteral(m_currentCharacter, m_pchLast, bodyLen, totalLen, bodyChars, totalChars, flags);
  744. }
  745. catch (UnifiedRegex::ParseError e)
  746. {
  747. #ifdef PROFILE_EXEC
  748. m_scriptContext->ProfileEnd(Js::RegexCompilePhase);
  749. #endif
  750. m_currentCharacter += e.encodedPos;
  751. Error(e.error);
  752. }
  753. UnifiedRegex::RegexPattern* pattern;
  754. if (m_parser->IsBackgroundParser())
  755. {
  756. // Avoid allocating pattern from recycler on background thread. The main thread will create the pattern
  757. // and hook it to this parse node.
  758. pattern = parser.template CompileProgram<false>(root, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, flags);
  759. }
  760. else
  761. {
  762. pattern = parser.template CompileProgram<true>(root, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, flags);
  763. }
  764. this->RestoreMultiUnits(this->m_cMultiUnits + parser.GetMultiUnits()); // m_currentCharacter changed, sync MultiUnits
  765. return m_ptoken->SetRegex(pattern, m_parser);
  766. }
  767. template<typename EncodingPolicy>
  768. tokens Scanner<EncodingPolicy>::ScanRegExpConstantNoAST(ArenaAllocator* alloc)
  769. {
  770. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackRegex);
  771. ThreadContext *threadContext = m_scriptContext->GetThreadContext();
  772. UnifiedRegex::StandardChars<EncodedChar>* standardEncodedChars = threadContext->GetStandardChars((EncodedChar*)0);
  773. UnifiedRegex::StandardChars<char16>* standardChars = threadContext->GetStandardChars((char16*)0);
  774. charcount_t totalLen = 0, bodyChars = 0, totalChars = 0, bodyLen = 0;
  775. UnifiedRegex::Parser<EncodingPolicy, true> parser
  776. ( m_scriptContext
  777. , alloc
  778. , standardEncodedChars
  779. , standardChars
  780. , this->IsUtf8()
  781. #if ENABLE_REGEX_CONFIG_OPTIONS
  782. , 0
  783. #endif
  784. );
  785. try
  786. {
  787. parser.ParseLiteralNoAST(m_currentCharacter, m_pchLast, bodyLen, totalLen, bodyChars, totalChars);
  788. }
  789. catch (UnifiedRegex::ParseError e)
  790. {
  791. m_currentCharacter += e.encodedPos;
  792. Error(e.error);
  793. // never reached
  794. }
  795. UnifiedRegex::RegexPattern* pattern = parser.template CompileProgram<false>(nullptr, m_currentCharacter, totalLen, bodyChars, bodyLen, totalChars, UnifiedRegex::NoRegexFlags);
  796. Assert(pattern == nullptr); // BuildAST == false, CompileProgram should return nullptr
  797. this->RestoreMultiUnits(this->m_cMultiUnits + parser.GetMultiUnits()); // m_currentCharacter changed, sync MultiUnits
  798. return (m_ptoken->tk = tkRegExp);
  799. }
  800. template<typename EncodingPolicy>
  801. tokens Scanner<EncodingPolicy>::ScanStringTemplateBegin(EncodedCharPtr *pp)
  802. {
  803. // String template must begin with a string constant followed by '`' or '${'
  804. ScanStringConstant<true, true>('`', pp);
  805. OLECHAR ch;
  806. EncodedCharPtr last = m_pchLast;
  807. ch = this->ReadFirst(*pp, last);
  808. if (ch == '`')
  809. {
  810. // Simple string template - no substitutions
  811. return tkStrTmplBasic;
  812. }
  813. else if (ch == '$')
  814. {
  815. ch = this->ReadFirst(*pp, last);
  816. if (ch == '{')
  817. {
  818. // Next token after expr should be tkStrTmplMid or tkStrTmplEnd.
  819. // In string template scanning mode, we expect the next char to be '}'
  820. // and will treat it as the beginning of tkStrTmplEnd or tkStrTmplMid
  821. m_fStringTemplateDepth++;
  822. // Regular string template begin - next is first substitution
  823. return tkStrTmplBegin;
  824. }
  825. }
  826. // Error - make sure pointer stays at the last character of the error token instead of after it in the error case
  827. (*pp)--;
  828. return ScanError(m_currentCharacter, tkStrTmplBegin);
  829. }
  830. template<typename EncodingPolicy>
  831. tokens Scanner<EncodingPolicy>::ScanStringTemplateMiddleOrEnd(EncodedCharPtr *pp)
  832. {
  833. // String template middle and end tokens must begin with a string constant
  834. ScanStringConstant<true, true>('`', pp);
  835. OLECHAR ch;
  836. EncodedCharPtr last = m_pchLast;
  837. ch = this->ReadFirst(*pp, last);
  838. if (ch == '`')
  839. {
  840. // No longer in string template scanning mode
  841. m_fStringTemplateDepth--;
  842. // This is the last part of the template ...`
  843. return tkStrTmplEnd;
  844. }
  845. else if (ch == '$')
  846. {
  847. ch = this->ReadFirst(*pp, last);
  848. if (ch == '{')
  849. {
  850. // This is just another middle part of the template }...${
  851. return tkStrTmplMid;
  852. }
  853. }
  854. // Error - make sure pointer stays at the last character of the error token instead of after it in the error case
  855. (*pp)--;
  856. return ScanError(m_currentCharacter, tkStrTmplEnd);
  857. }
  858. /*****************************************************************************
  859. *
  860. * Parses a string constant. Note that the string value is stored in
  861. * a volatile buffer (or allocated on the heap if too long), and thus
  862. * the string should be saved off before the next token is scanned.
  863. */
  864. template<typename EncodingPolicy>
  865. template<bool stringTemplateMode, bool createRawString>
  866. tokens Scanner<EncodingPolicy>::ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp)
  867. {
  868. static_assert((stringTemplateMode && createRawString) || (!stringTemplateMode && !createRawString), "stringTemplateMode and createRawString must have the same value");
  869. OLECHAR ch, c, rawch;
  870. int wT;
  871. EncodedCharPtr p = *pp;
  872. EncodedCharPtr last = m_pchLast;
  873. // Reset
  874. m_OctOrLeadingZeroOnLastTKNumber = false;
  875. m_EscapeOnLastTkStrCon = FALSE;
  876. m_tempChBuf.Reset();
  877. // Use template parameter to gate raw string creation.
  878. // If createRawString is false, all these operations should be no-ops
  879. if (createRawString)
  880. {
  881. m_tempChBufSecondary.Reset();
  882. }
  883. for (;;)
  884. {
  885. switch ((rawch = ch = this->ReadFirst(p, last)))
  886. {
  887. case kchRET:
  888. if (stringTemplateMode)
  889. {
  890. if (this->PeekFirst(p, last) == kchNWL)
  891. {
  892. // Eat the <LF> char, ignore return
  893. this->ReadFirst(p, last);
  894. }
  895. // Both <CR> and <CR><LF> are normalized to <LF> in template cooked and raw values
  896. ch = rawch = kchNWL;
  897. }
  898. LEcmaLineBreak:
  899. // Fall through
  900. case kchNWL:
  901. if (stringTemplateMode)
  902. {
  903. // Notify the scanner to update current line, number of lines etc
  904. NotifyScannedNewLine();
  905. // We haven't updated m_currentCharacter yet, so make sure the MinLine info is correct in case we error out.
  906. m_pchMinLine = p;
  907. break;
  908. }
  909. m_currentCharacter = p - 1;
  910. Error(ERRnoStrEnd);
  911. case '"':
  912. case '\'':
  913. if (ch == delim)
  914. goto LBreak;
  915. break;
  916. case '`':
  917. // In string template scan mode, don't consume the '`' - we need to differentiate
  918. // between a closed string template and the expression open sequence - ${
  919. if (stringTemplateMode)
  920. {
  921. p--;
  922. goto LBreak;
  923. }
  924. // If we aren't scanning for a string template, do the default thing
  925. goto LMainDefault;
  926. case '$':
  927. // If we are parsing a string literal part of a string template, ${ indicates we need to switch
  928. // to parsing an expression.
  929. if (stringTemplateMode && this->PeekFirst(p, last) == '{')
  930. {
  931. // Rewind to the $ and return
  932. p--;
  933. goto LBreak;
  934. }
  935. // If we aren't scanning for a string template, do the default thing
  936. goto LMainDefault;
  937. case kchNUL:
  938. if (p > last)
  939. {
  940. m_currentCharacter = p - 1;
  941. Error(ERRnoStrEnd);
  942. }
  943. break;
  944. default:
  945. LMainDefault:
  946. if (this->IsMultiUnitChar(ch))
  947. {
  948. if ((ch == kchLS || ch == kchPS))
  949. {
  950. goto LEcmaLineBreak;
  951. }
  952. rawch = ch = this->template ReadRest<true>(ch, p, last);
  953. switch (ch)
  954. {
  955. case kchLS: // 0x2028, classifies as new line
  956. case kchPS: // 0x2029, classifies as new line
  957. goto LEcmaLineBreak;
  958. }
  959. }
  960. break;
  961. case kchBSL:
  962. // In raw mode '\\' is not an escape character, just add the char into the raw buffer.
  963. m_tempChBufSecondary.template AppendCh<createRawString>(ch);
  964. m_EscapeOnLastTkStrCon=TRUE;
  965. // In raw mode, we append the raw char itself and not the escaped value so save the char.
  966. rawch = ch = this->ReadFirst(p, last);
  967. codepoint_t codePoint = 0;
  968. uint errorType = (uint)ERRbadHexDigit;
  969. switch (ch)
  970. {
  971. case 'b':
  972. ch = 0x08;
  973. break;
  974. case 't':
  975. ch = 0x09;
  976. break;
  977. case 'v':
  978. ch = 0x0B; //Only in ES5 mode
  979. break; //same as default
  980. case 'n':
  981. ch = 0x0A;
  982. break;
  983. case 'f':
  984. ch = 0x0C;
  985. break;
  986. case 'r':
  987. ch = 0x0D;
  988. break;
  989. case 'x':
  990. // Insert the 'x' here before jumping to parse the hex digits.
  991. m_tempChBufSecondary.template AppendCh<createRawString>(ch);
  992. // 2 hex digits
  993. ch = 0;
  994. goto LTwoHex;
  995. case 'u':
  996. // Raw string just inserts a 'u' here.
  997. m_tempChBufSecondary.template AppendCh<createRawString>(ch);
  998. ch = 0;
  999. if (Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1000. goto LFourHex;
  1001. else if (c != '{' || !this->es6UnicodeMode)
  1002. goto ReturnScanError;
  1003. Assert(c == '{');
  1004. // c should definitely be a '{' which should be appended to the raw string.
  1005. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1006. //At least one digit is expected
  1007. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1008. {
  1009. goto ReturnScanError;
  1010. }
  1011. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1012. codePoint = static_cast<codepoint_t>(wT);
  1013. while(Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1014. {
  1015. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1016. codePoint <<= 4;
  1017. codePoint += static_cast<codepoint_t>(wT);
  1018. if (codePoint > 0x10FFFF)
  1019. {
  1020. errorType = (uint)ERRInvalidCodePoint;
  1021. goto ReturnScanError;
  1022. }
  1023. }
  1024. if (c != '}')
  1025. {
  1026. errorType = (uint)ERRMissingCurlyBrace;
  1027. goto ReturnScanError;
  1028. }
  1029. Assert(codePoint <= 0x10FFFF);
  1030. if (codePoint >= 0x10000)
  1031. {
  1032. OLECHAR lower = 0;
  1033. Js::NumberUtilities::CodePointAsSurrogatePair(codePoint, &lower, &ch);
  1034. m_tempChBuf.AppendCh(lower);
  1035. }
  1036. else
  1037. {
  1038. ch = (char16)codePoint;
  1039. }
  1040. // In raw mode we want the last hex character or the closing curly. c should hold one or the other.
  1041. if (createRawString)
  1042. rawch = c;
  1043. break;
  1044. LFourHex:
  1045. codePoint = 0x0;
  1046. // Append first hex digit character to the raw string.
  1047. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1048. codePoint += static_cast<codepoint_t>(wT * 0x1000);
  1049. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1050. goto ReturnScanError;
  1051. // Append fourth (or second) hex digit character to the raw string.
  1052. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1053. codePoint += static_cast<codepoint_t>(wT * 0x0100);
  1054. LTwoHex:
  1055. // This code path doesn't expect curly.
  1056. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1057. goto ReturnScanError;
  1058. // Append first hex digit character to the raw string.
  1059. m_tempChBufSecondary.template AppendCh<createRawString>(c);
  1060. codePoint += static_cast<codepoint_t>(wT * 0x0010);
  1061. if (!Js::NumberUtilities::FHexDigit(c = this->ReadFirst(p, last), &wT))
  1062. goto ReturnScanError;
  1063. codePoint += static_cast<codepoint_t>(wT);
  1064. // In raw mode we want the last hex character or the closing curly. c should hold one or the other.
  1065. if (createRawString)
  1066. rawch = c;
  1067. if (codePoint < 0x10000)
  1068. {
  1069. ch = static_cast<OLECHAR>(codePoint);
  1070. }
  1071. else
  1072. {
  1073. goto ReturnScanError;
  1074. }
  1075. break;
  1076. case '0':
  1077. case '1':
  1078. case '2':
  1079. case '3':
  1080. // 1 to 3 octal digits
  1081. ch -= '0';
  1082. // Octal escape sequences are not allowed inside string template literals
  1083. if (stringTemplateMode)
  1084. {
  1085. c = this->PeekFirst(p, last);
  1086. if (ch != 0 || (c >= '0' && c <= '7'))
  1087. {
  1088. errorType = (uint)ERRES5NoOctal;
  1089. goto ReturnScanError;
  1090. }
  1091. break;
  1092. }
  1093. wT = (c = this->ReadFirst(p, last)) - '0';
  1094. if ((char16)wT > 7)
  1095. {
  1096. if (ch != 0 || ((char16)wT <= 9))
  1097. {
  1098. m_OctOrLeadingZeroOnLastTKNumber = true;
  1099. }
  1100. p--;
  1101. break;
  1102. }
  1103. m_OctOrLeadingZeroOnLastTKNumber = true;
  1104. ch = static_cast< OLECHAR >(ch * 8 + wT);
  1105. goto LOneOctal;
  1106. case '4':
  1107. case '5':
  1108. case '6':
  1109. case '7':
  1110. // 1 to 2 octal digits
  1111. // Octal escape sequences are not allowed inside string template literals
  1112. if (stringTemplateMode)
  1113. {
  1114. errorType = (uint)ERRES5NoOctal;
  1115. goto ReturnScanError;
  1116. }
  1117. ch -= '0';
  1118. m_OctOrLeadingZeroOnLastTKNumber = true;
  1119. LOneOctal:
  1120. wT = (c = this->ReadFirst(p, last)) - '0';
  1121. if ((char16)wT > 7)
  1122. {
  1123. p--;
  1124. break;
  1125. }
  1126. ch = static_cast< OLECHAR >(ch * 8 + wT);
  1127. break;
  1128. case kchRET: // 0xD
  1129. if (stringTemplateMode)
  1130. {
  1131. // If this is \<CR><LF> we can eat the <LF> right now
  1132. if (this->PeekFirst(p, last) == kchNWL)
  1133. {
  1134. // Eat the <LF> char, ignore return
  1135. this->ReadFirst(p, last);
  1136. }
  1137. // Both \<CR> and \<CR><LF> are normalized to \<LF> in template raw string
  1138. rawch = kchNWL;
  1139. }
  1140. case kchLS: // 0x2028, classifies as new line
  1141. case kchPS: // 0x2029, classifies as new line
  1142. case kchNWL: // 0xA
  1143. LEcmaEscapeLineBreak:
  1144. if (stringTemplateMode)
  1145. {
  1146. // We're going to ignore the line continuation tokens for the cooked strings, but we need to append the token for raw strings
  1147. m_tempChBufSecondary.template AppendCh<createRawString>(rawch);
  1148. // Template literal strings ignore all escaped line continuation tokens
  1149. NotifyScannedNewLine();
  1150. // We haven't updated m_currentCharacter yet, so make sure the MinLine info is correct in case we error out.
  1151. m_pchMinLine = p;
  1152. continue;
  1153. }
  1154. m_currentCharacter = p;
  1155. ScanNewLine(ch);
  1156. p = m_currentCharacter;
  1157. continue;
  1158. case 0:
  1159. if (p >= last)
  1160. {
  1161. errorType = (uint)ERRnoStrEnd;
  1162. ReturnScanError:
  1163. m_currentCharacter = p - 1;
  1164. Error(errorType);
  1165. }
  1166. else if (stringTemplateMode)
  1167. {
  1168. // Escaped null character is translated into 0x0030 for raw template literals
  1169. rawch = 0x0030;
  1170. }
  1171. break;
  1172. default:
  1173. if (this->IsMultiUnitChar(ch))
  1174. {
  1175. rawch = ch = this->template ReadRest<true>(ch, p, last);
  1176. switch (ch)
  1177. {
  1178. case kchLS:
  1179. case kchPS:
  1180. goto LEcmaEscapeLineBreak;
  1181. }
  1182. }
  1183. break;
  1184. }
  1185. break;
  1186. }
  1187. m_tempChBuf.AppendCh(ch);
  1188. m_tempChBufSecondary.template AppendCh<createRawString>(rawch);
  1189. }
  1190. LBreak:
  1191. bool createPid = true;
  1192. if ((m_DeferredParseFlags & ScanFlagSuppressStrPid) != 0)
  1193. {
  1194. createPid = false;
  1195. if ((m_tempChBuf.m_ichCur == 10) && (0 == memcmp(_u("use strict"), m_tempChBuf.m_prgch, m_tempChBuf.m_ichCur * sizeof(OLECHAR))))
  1196. {
  1197. createPid = true;
  1198. }
  1199. }
  1200. if (createPid)
  1201. {
  1202. m_ptoken->SetIdentifier(this->GetHashTbl()->PidHashNameLen(m_tempChBuf.m_prgch, m_tempChBuf.m_ichCur));
  1203. }
  1204. else
  1205. {
  1206. m_ptoken->SetIdentifier(NULL);
  1207. }
  1208. m_scanState = ScanStateNormal;
  1209. m_doubleQuoteOnLastTkStrCon = '"' == delim;
  1210. *pp = p;
  1211. return tkStrCon;
  1212. }
  1213. template<typename EncodingPolicy>
  1214. tokens Scanner<EncodingPolicy>::ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp)
  1215. {
  1216. return ScanStringConstant<false, false>(delim, pp);
  1217. }
  1218. /*****************************************************************************
  1219. *
  1220. * Consume a C-style comment.
  1221. */
  1222. template<typename EncodingPolicy>
  1223. tokens Scanner<EncodingPolicy>::SkipComment(EncodedCharPtr *pp, /* out */ bool* containTypeDef)
  1224. {
  1225. Assert(containTypeDef != nullptr);
  1226. EncodedCharPtr p = *pp;
  1227. *containTypeDef = false;
  1228. EncodedCharPtr last = m_pchLast;
  1229. OLECHAR ch;
  1230. for (;;)
  1231. {
  1232. switch((ch = this->ReadFirst(p, last)))
  1233. {
  1234. case '*':
  1235. if (*p == '/')
  1236. {
  1237. *pp = p + 1;
  1238. return tkNone;
  1239. }
  1240. break;
  1241. // ES 2015 11.3 Line Terminators
  1242. case kchLS: // 0x2028, classifies as new line
  1243. case kchPS: // 0x2029, classifies as new line
  1244. LEcmaLineBreak:
  1245. goto LLineBreak;
  1246. case kchRET:
  1247. case kchNWL:
  1248. LLineBreak:
  1249. m_fHadEol = TRUE;
  1250. m_currentCharacter = p;
  1251. ScanNewLine(ch);
  1252. p = m_currentCharacter;
  1253. break;
  1254. case kchNUL:
  1255. if (p >= last)
  1256. {
  1257. m_currentCharacter = p - 1;
  1258. *pp = p - 1;
  1259. Error(ERRnoCmtEnd);
  1260. }
  1261. break;
  1262. default:
  1263. if (this->IsMultiUnitChar(ch))
  1264. {
  1265. ch = this->template ReadRest<true>(ch, p, last);
  1266. switch (ch)
  1267. {
  1268. case kchLS:
  1269. case kchPS:
  1270. goto LEcmaLineBreak;
  1271. }
  1272. }
  1273. break;
  1274. }
  1275. }
  1276. }
  1277. /*****************************************************************************
  1278. *
  1279. * We've encountered a newline - update various counters and things.
  1280. */
  1281. template<typename EncodingPolicy>
  1282. void Scanner<EncodingPolicy>::ScanNewLine(uint ch)
  1283. {
  1284. if (ch == '\r' && PeekNextChar() == '\n')
  1285. {
  1286. ReadNextChar();
  1287. }
  1288. NotifyScannedNewLine();
  1289. }
  1290. /*****************************************************************************
  1291. *
  1292. * We've encountered a newline - update various counters and things.
  1293. */
  1294. template<typename EncodingPolicy>
  1295. void Scanner<EncodingPolicy>::NotifyScannedNewLine()
  1296. {
  1297. // update in scanner: previous line, current line, number of lines.
  1298. m_line++;
  1299. m_pchPrevLine = m_pchMinLine;
  1300. m_pchMinLine = m_currentCharacter;
  1301. m_cMinLineMultiUnits = this->m_cMultiUnits;
  1302. }
  1303. /*****************************************************************************
  1304. *
  1305. * Delivers a token stream.
  1306. */
  1307. template<typename EncodingPolicy>
  1308. tokens Scanner<EncodingPolicy>::ScanForcingPid()
  1309. {
  1310. if (m_DeferredParseFlags != ScanFlagNone)
  1311. {
  1312. BYTE deferredParseFlagsSave = m_DeferredParseFlags;
  1313. m_DeferredParseFlags = ScanFlagNone;
  1314. tokens result = tkEOF;
  1315. TryFinally(
  1316. [&]() /* try block */
  1317. {
  1318. result = this->Scan();
  1319. },
  1320. [&](bool) /* finally block */
  1321. {
  1322. this->m_DeferredParseFlags = deferredParseFlagsSave;
  1323. });
  1324. return result;
  1325. }
  1326. return Scan();
  1327. }
  1328. template<typename EncodingPolicy>
  1329. tokens Scanner<EncodingPolicy>::Scan()
  1330. {
  1331. return ScanCore(true);
  1332. }
  1333. template<typename EncodingPolicy>
  1334. tokens Scanner<EncodingPolicy>::ScanNoKeywords()
  1335. {
  1336. return ScanCore(false);
  1337. }
  1338. template<typename EncodingPolicy>
  1339. tokens Scanner<EncodingPolicy>::ScanAhead()
  1340. {
  1341. return ScanNoKeywords();
  1342. }
  1343. template<typename EncodingPolicy>
  1344. tokens Scanner<EncodingPolicy>::ScanCore(bool identifyKwds)
  1345. {
  1346. codepoint_t ch;
  1347. OLECHAR firstChar;
  1348. OLECHAR secondChar;
  1349. EncodedCharPtr pchT;
  1350. size_t multiUnits = 0;
  1351. EncodedCharPtr p = m_currentCharacter;
  1352. EncodedCharPtr last = m_pchLast;
  1353. bool seenDelimitedCommentEnd = false;
  1354. // store the last token
  1355. m_tkPrevious = m_ptoken->tk;
  1356. m_iecpLimTokPrevious = IecpLimTok(); // Introduced for use by lambda parsing to find correct span of expression lambdas
  1357. m_ichLimTokPrevious = IchLimTok();
  1358. if (p >= last)
  1359. {
  1360. m_pchMinTok = p;
  1361. m_cMinTokMultiUnits = this->m_cMultiUnits;
  1362. goto LEof;
  1363. }
  1364. tokens token;
  1365. m_fHadEol = FALSE;
  1366. CharTypes chType;
  1367. charcount_t commentStartLine;
  1368. if (m_scanState && *p != 0)
  1369. {
  1370. if (m_scanState == ScanStateStringTemplateMiddleOrEnd)
  1371. {
  1372. AssertMsg(m_fStringTemplateDepth > 0,
  1373. "Shouldn't be trying to parse a string template end or middle token if we aren't scanning a string template");
  1374. m_scanState = ScanStateNormal;
  1375. pchT = p;
  1376. token = ScanStringTemplateMiddleOrEnd(&pchT);
  1377. p = pchT;
  1378. goto LDone;
  1379. }
  1380. }
  1381. for (;;)
  1382. {
  1383. LLoop:
  1384. m_pchMinTok = p;
  1385. m_cMinTokMultiUnits = this->m_cMultiUnits;
  1386. ch = this->ReadFirst(p, last);
  1387. #if DEBUG
  1388. chType = this->charClassifier->GetCharType((OLECHAR)ch);
  1389. #endif
  1390. switch (ch)
  1391. {
  1392. default:
  1393. if (ch == kchLS ||
  1394. ch == kchPS )
  1395. {
  1396. goto LNewLine;
  1397. }
  1398. {
  1399. BOOL isMultiUnit = this->IsMultiUnitChar((OLECHAR)ch);
  1400. if (isMultiUnit)
  1401. {
  1402. ch = this->template ReadRest<true>((OLECHAR)ch, p, last);
  1403. }
  1404. if (es6UnicodeMode && Js::NumberUtilities::IsSurrogateLowerPart(ch))
  1405. {
  1406. codepoint_t upper = this->PeekFull(p, last);
  1407. if (Js::NumberUtilities::IsSurrogateUpperPart(upper))
  1408. {
  1409. // Consume the rest of the utf8 bytes for the codepoint
  1410. OLECHAR decodedUpper = this->ReadSurrogatePairUpper(p, last);
  1411. Assert(decodedUpper == (OLECHAR) upper);
  1412. ch = Js::NumberUtilities::SurrogatePairAsCodePoint(ch, upper);
  1413. }
  1414. }
  1415. if (this->charClassifier->IsIdStart(ch))
  1416. {
  1417. // We treat IDContinue as an error.
  1418. token = ScanIdentifierContinue(identifyKwds, false, !!isMultiUnit, m_pchMinTok, p, &p);
  1419. break;
  1420. }
  1421. }
  1422. chType = this->charClassifier->GetCharType(ch);
  1423. switch (chType)
  1424. {
  1425. case _C_WSP: continue;
  1426. case _C_NWL: goto LNewLine;
  1427. // All other types (except errors) are handled by the outer switch.
  1428. }
  1429. Assert(chType == _C_LET || chType == _C_ERR || chType == _C_UNK || chType == _C_BKQ || chType == _C_SHP || chType == _C_AT || chType == _C_DIG);
  1430. m_currentCharacter = p - 1;
  1431. Error(ERRillegalChar);
  1432. continue;
  1433. case '\0':
  1434. // Put back the null in case we get called again.
  1435. p--;
  1436. if (p < last)
  1437. {
  1438. // A \0 prior to the end of the text is an invalid character.
  1439. m_currentCharacter = p;
  1440. Error(ERRillegalChar);
  1441. }
  1442. LEof:
  1443. Assert(p >= last);
  1444. token = tkEOF;
  1445. break;
  1446. case 0x0009:
  1447. case 0x000B:
  1448. case 0x000C:
  1449. case 0x0020:
  1450. Assert(chType == _C_WSP);
  1451. continue;
  1452. case '.':
  1453. if (!Js::NumberUtilities::IsDigit(*p))
  1454. {
  1455. // Not a double
  1456. if (m_scriptContext->GetConfig()->IsES6SpreadEnabled() &&
  1457. this->PeekFirst(p, last) == '.' &&
  1458. this->PeekFirst(p + 1, last) == '.')
  1459. {
  1460. token = tkEllipsis;
  1461. p += 2;
  1462. }
  1463. else
  1464. {
  1465. token = tkDot;
  1466. }
  1467. break;
  1468. }
  1469. // May be a double, fall through
  1470. case '0': case '1': case '2': case '3': case '4':
  1471. case '5': case '6': case '7': case '8': case '9':
  1472. {
  1473. double dbl;
  1474. Assert(chType == _C_DIG || chType == _C_DOT);
  1475. p = m_pchMinTok;
  1476. this->RestoreMultiUnits(m_cMinTokMultiUnits);
  1477. bool likelyInt = true;
  1478. pchT = FScanNumber(p, &dbl, likelyInt);
  1479. if (p == pchT)
  1480. {
  1481. Assert(this->PeekFirst(p, last) != '.');
  1482. Error(ERRbadNumber);
  1483. }
  1484. Assert(!Js::NumberUtilities::IsNan(dbl));
  1485. p = pchT;
  1486. int32 value;
  1487. if (likelyInt && Js::NumberUtilities::FDblIsInt32(dbl, &value))
  1488. {
  1489. m_ptoken->SetLong(value);
  1490. token = tkIntCon;
  1491. }
  1492. else
  1493. {
  1494. token = tkFltCon;
  1495. m_ptoken->SetDouble(dbl, likelyInt);
  1496. }
  1497. break;
  1498. }
  1499. case '(': Assert(chType == _C_LPR); token = tkLParen; break;
  1500. case ')': Assert(chType == _C_RPR); token = tkRParen; break;
  1501. case ',': Assert(chType == _C_CMA); token = tkComma; break;
  1502. case ';': Assert(chType == _C_SMC); token = tkSColon; break;
  1503. case '[': Assert(chType == _C_LBR); token = tkLBrack; break;
  1504. case ']': Assert(chType == _C_RBR); token = tkRBrack; break;
  1505. case '~': Assert(chType == _C_TIL); token = tkTilde; break;
  1506. case '?': Assert(chType == _C_QUE); token = tkQMark; break;
  1507. case '{': Assert(chType == _C_LC); token = tkLCurly; break;
  1508. // ES 2015 11.3 Line Terminators
  1509. case '\r':
  1510. case '\n':
  1511. // kchLS:
  1512. // kchPS:
  1513. LNewLine:
  1514. m_currentCharacter = p;
  1515. ScanNewLine(ch);
  1516. p = m_currentCharacter;
  1517. m_fHadEol = TRUE;
  1518. continue;
  1519. LReserved:
  1520. {
  1521. // We will derive the PID from the token
  1522. Assert(token < tkID);
  1523. m_ptoken->SetIdentifier(NULL);
  1524. goto LDone;
  1525. }
  1526. LEval:
  1527. {
  1528. token = tkID;
  1529. if (!this->m_parser) goto LIdentifier;
  1530. m_ptoken->SetIdentifier(this->m_parser->GetEvalPid());
  1531. goto LDone;
  1532. }
  1533. LArguments:
  1534. {
  1535. token = tkID;
  1536. if (!this->m_parser) goto LIdentifier;
  1537. m_ptoken->SetIdentifier(this->m_parser->GetArgumentsPid());
  1538. goto LDone;
  1539. }
  1540. LTarget:
  1541. {
  1542. token = tkID;
  1543. if (!this->m_parser) goto LIdentifier;
  1544. m_ptoken->SetIdentifier(this->m_parser->GetTargetPid());
  1545. goto LDone;
  1546. }
  1547. #include "kwd-swtch.h"
  1548. case 'A': case 'B': case 'C': case 'D': case 'E':
  1549. case 'F': case 'G': case 'H': case 'I': case 'J':
  1550. case 'K': case 'L': case 'M': case 'N': case 'O':
  1551. case 'P': case 'Q': case 'R': case 'S': case 'T':
  1552. case 'U': case 'V': case 'W': case 'X': case 'Y':
  1553. case 'Z':
  1554. // Lower-case letters handled in kwd-swtch.h above during reserved word recognition.
  1555. case '$': case '_':
  1556. LIdentifier:
  1557. Assert(this->charClassifier->IsIdStart(ch));
  1558. Assert(ch < 0x10000 && !this->IsMultiUnitChar((OLECHAR)ch));
  1559. token = ScanIdentifierContinue(identifyKwds, false, false, m_pchMinTok, p, &p);
  1560. break;
  1561. case '`':
  1562. Assert(chType == _C_BKQ);
  1563. pchT = p;
  1564. token = ScanStringTemplateBegin(&pchT);
  1565. p = pchT;
  1566. break;
  1567. case '}':
  1568. Assert(chType == _C_RC);
  1569. token = tkRCurly;
  1570. break;
  1571. case '\\':
  1572. pchT = p - 1;
  1573. token = ScanIdentifier(identifyKwds, &pchT);
  1574. if (tkScanError == token)
  1575. {
  1576. m_currentCharacter = p;
  1577. Error(ERRillegalChar);
  1578. }
  1579. p = pchT;
  1580. break;
  1581. case ':':
  1582. token = tkColon;
  1583. break;
  1584. case '=':
  1585. token = tkAsg;
  1586. switch (this->PeekFirst(p, last))
  1587. {
  1588. case '=':
  1589. p++;
  1590. token = tkEQ;
  1591. if (this->PeekFirst(p, last) == '=')
  1592. {
  1593. p++;
  1594. token = tkEqv;
  1595. }
  1596. break;
  1597. case '>':
  1598. p++;
  1599. token = tkDArrow;
  1600. break;
  1601. }
  1602. break;
  1603. case '!':
  1604. token = tkBang;
  1605. if (this->PeekFirst(p, last) == '=')
  1606. {
  1607. p++;
  1608. token = tkNE;
  1609. if (this->PeekFirst(p, last) == '=')
  1610. {
  1611. p++;
  1612. token = tkNEqv;
  1613. }
  1614. }
  1615. break;
  1616. case '+':
  1617. token = tkAdd;
  1618. switch (this->PeekFirst(p, last))
  1619. {
  1620. case '=':
  1621. p++;
  1622. token = tkAsgAdd;
  1623. break;
  1624. case '+':
  1625. p++;
  1626. token = tkInc;
  1627. break;
  1628. }
  1629. break;
  1630. case '-':
  1631. token = tkSub;
  1632. switch (this->PeekFirst(p, last))
  1633. {
  1634. case '=':
  1635. p++;
  1636. token = tkAsgSub;
  1637. break;
  1638. case '-':
  1639. p++;
  1640. token = tkDec;
  1641. if (!m_fIsModuleCode)
  1642. {
  1643. // https://tc39.github.io/ecma262/#prod-annexB-MultiLineComment
  1644. // If there was a new line in the multi-line comment, the text after --> is a comment.
  1645. if ('>' == this->PeekFirst(p, last) && m_fHadEol)
  1646. {
  1647. goto LSkipLineComment;
  1648. }
  1649. }
  1650. break;
  1651. }
  1652. break;
  1653. case '*':
  1654. token = tkStar;
  1655. switch(this->PeekFirst(p, last))
  1656. {
  1657. case '=' :
  1658. p++;
  1659. token = tkAsgMul;
  1660. break;
  1661. case '*' :
  1662. if (!m_scriptContext->GetConfig()->IsES7ExponentiationOperatorEnabled())
  1663. {
  1664. break;
  1665. }
  1666. p++;
  1667. token = tkExpo;
  1668. if (this->PeekFirst(p, last) == '=')
  1669. {
  1670. p++;
  1671. token = tkAsgExpo;
  1672. }
  1673. }
  1674. break;
  1675. case '/':
  1676. token = tkDiv;
  1677. switch(this->PeekFirst(p, last))
  1678. {
  1679. case '=':
  1680. p++;
  1681. token = tkAsgDiv;
  1682. break;
  1683. case '/':
  1684. if (p >= last)
  1685. {
  1686. AssertMsg(!m_fIsModuleCode, "Do we have other line comment cases scanning pass last?");
  1687. // Effective source length may have excluded HTMLCommentSuffix "//... -->". If we are scanning
  1688. // those, we have passed "last" already. Move back and return EOF.
  1689. p = last;
  1690. goto LEof;
  1691. }
  1692. ch = *++p;
  1693. firstChar = (OLECHAR)ch;
  1694. LSkipLineComment:
  1695. pchT = NULL;
  1696. for (;;)
  1697. {
  1698. switch ((ch = this->ReadFirst(p, last)))
  1699. {
  1700. case kchLS: // 0x2028, classifies as new line
  1701. case kchPS: // 0x2029, classifies as new line
  1702. LEcmaCommentLineBreak:
  1703. // kchPS and kchLS are more than one unit in UTF-8.
  1704. if (pchT)
  1705. {
  1706. // kchPS and kchLS are more than one unit in UTF-8.
  1707. p = pchT;
  1708. }
  1709. else
  1710. {
  1711. // But only a single code unit in UTF16
  1712. p--;
  1713. }
  1714. this->RestoreMultiUnits(multiUnits);
  1715. goto LCommentLineBreak;
  1716. case kchNWL:
  1717. case kchRET:
  1718. p--;
  1719. LCommentLineBreak:
  1720. // Subtract the comment length from the total char count for the purpose
  1721. // of deciding whether to defer AST and byte code generation.
  1722. m_parser->ReduceDeferredScriptLength((ULONG)(p - m_pchMinTok));
  1723. break;
  1724. case kchNUL:
  1725. // Because we used ReadFirst, we have advanced p. The character that we are looking at is actually is p - 1.
  1726. // 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
  1727. // Only if p > last that we have pass the source buffer and consider it a line break
  1728. if (p > last)
  1729. {
  1730. p--;
  1731. goto LCommentLineBreak;
  1732. }
  1733. continue;
  1734. default:
  1735. if (this->IsMultiUnitChar((OLECHAR)ch))
  1736. {
  1737. pchT = p - 1;
  1738. multiUnits = this->m_cMultiUnits;
  1739. switch (ch = this->template ReadRest<true>((OLECHAR)ch, p, last))
  1740. {
  1741. case kchLS:
  1742. case kchPS:
  1743. goto LEcmaCommentLineBreak;
  1744. }
  1745. }
  1746. continue;
  1747. }
  1748. break;
  1749. }
  1750. continue;
  1751. case '*':
  1752. ch = *++p;
  1753. firstChar = (OLECHAR)ch;
  1754. if ((p + 1) < last)
  1755. {
  1756. secondChar = (OLECHAR)(*(p + 1));
  1757. }
  1758. else
  1759. {
  1760. secondChar = '\0';
  1761. }
  1762. pchT = p;
  1763. commentStartLine = m_line;
  1764. bool containTypeDef;
  1765. if (tkNone == (token = SkipComment(&pchT, &containTypeDef)))
  1766. {
  1767. // Subtract the comment length from the total char count for the purpose
  1768. // of deciding whether to defer AST and byte code generation.
  1769. m_parser->ReduceDeferredScriptLength((ULONG)(pchT - m_pchMinTok));
  1770. p = pchT;
  1771. seenDelimitedCommentEnd = true;
  1772. goto LLoop;
  1773. }
  1774. p = pchT;
  1775. break;
  1776. }
  1777. break;
  1778. case '%':
  1779. Assert(chType == _C_PCT);
  1780. token = tkPct;
  1781. if (this->PeekFirst(p, last) == '=')
  1782. {
  1783. p++;
  1784. token = tkAsgMod;
  1785. }
  1786. break;
  1787. case '<':
  1788. Assert(chType == _C_LT);
  1789. token = tkLT;
  1790. switch (this->PeekFirst(p, last))
  1791. {
  1792. case '=':
  1793. p++;
  1794. token = tkLE;
  1795. break;
  1796. case '<':
  1797. p++;
  1798. token = tkLsh;
  1799. if (this->PeekFirst(p, last) == '=')
  1800. {
  1801. p++;
  1802. token = tkAsgLsh;
  1803. break;
  1804. }
  1805. break;
  1806. case '!':
  1807. // ES 2015 B.1.3 - HTML comments are only allowed when parsing non-module code.
  1808. if (!m_fIsModuleCode && this->PeekFirst(p + 1, last) == '-' && this->PeekFirst(p + 2, last) == '-')
  1809. {
  1810. // This is a "<!--" comment - treat as //
  1811. if (p >= last)
  1812. {
  1813. // Effective source length may have excluded HTMLCommentSuffix "<!-- ... -->". If we are scanning
  1814. // those, we have passed "last" already. Move back and return EOF.
  1815. p = last;
  1816. goto LEof;
  1817. }
  1818. firstChar = '!';
  1819. goto LSkipLineComment;
  1820. }
  1821. break;
  1822. }
  1823. break;
  1824. case '>':
  1825. Assert(chType == _C_GT);
  1826. token = tkGT;
  1827. switch (this->PeekFirst(p, last))
  1828. {
  1829. case '=':
  1830. p++;
  1831. token = tkGE;
  1832. break;
  1833. case '>':
  1834. p++;
  1835. token = tkRsh;
  1836. switch (this->PeekFirst(p, last))
  1837. {
  1838. case '=':
  1839. p++;
  1840. token = tkAsgRsh;
  1841. break;
  1842. case '>':
  1843. p++;
  1844. token = tkRs2;
  1845. if (*p == '=')
  1846. {
  1847. p++;
  1848. token = tkAsgRs2;
  1849. }
  1850. break;
  1851. }
  1852. break;
  1853. }
  1854. break;
  1855. case '^':
  1856. Assert(chType == _C_XOR);
  1857. token = tkXor;
  1858. if (this->PeekFirst(p, last) == '=')
  1859. {
  1860. p++;
  1861. token = tkAsgXor;
  1862. }
  1863. break;
  1864. case '|':
  1865. Assert(chType == _C_BAR);
  1866. token = tkOr;
  1867. switch (this->PeekFirst(p, last))
  1868. {
  1869. case '=':
  1870. p++;
  1871. token = tkAsgOr;
  1872. break;
  1873. case '|':
  1874. p++;
  1875. token = tkLogOr;
  1876. break;
  1877. }
  1878. break;
  1879. case '&':
  1880. Assert(chType == _C_AMP);
  1881. token = tkAnd;
  1882. switch (this->PeekFirst(p, last))
  1883. {
  1884. case '=':
  1885. p++;
  1886. token = tkAsgAnd;
  1887. break;
  1888. case '&':
  1889. p++;
  1890. token = tkLogAnd;
  1891. break;
  1892. }
  1893. break;
  1894. case '\'':
  1895. case '"':
  1896. Assert(chType == _C_QUO || chType == _C_APO);
  1897. pchT = p;
  1898. token = this->ScanStringConstant((OLECHAR)ch, &pchT);
  1899. p = pchT;
  1900. break;
  1901. }
  1902. break;
  1903. }
  1904. LDone:
  1905. m_currentCharacter = p;
  1906. return (m_ptoken->tk = token);
  1907. }
  1908. template <typename EncodingPolicy>
  1909. IdentPtr Scanner<EncodingPolicy>::GetSecondaryBufferAsPid()
  1910. {
  1911. bool createPid = true;
  1912. if ((m_DeferredParseFlags & ScanFlagSuppressStrPid) != 0)
  1913. {
  1914. createPid = false;
  1915. }
  1916. if (createPid)
  1917. {
  1918. return this->GetHashTbl()->PidHashNameLen(m_tempChBufSecondary.m_prgch, m_tempChBufSecondary.m_ichCur);
  1919. }
  1920. else
  1921. {
  1922. return nullptr;
  1923. }
  1924. }
  1925. template <typename EncodingPolicy>
  1926. LPCOLESTR Scanner<EncodingPolicy>::StringFromLong(int32 lw)
  1927. {
  1928. _ltow_s(lw, m_tempChBuf.m_prgch, m_tempChBuf.m_cchMax, 10);
  1929. return m_tempChBuf.m_prgch;
  1930. }
  1931. template <typename EncodingPolicy>
  1932. IdentPtr Scanner<EncodingPolicy>::PidFromLong(int32 lw)
  1933. {
  1934. return this->GetHashTbl()->PidHashName(StringFromLong(lw));
  1935. }
  1936. template <typename EncodingPolicy>
  1937. LPCOLESTR Scanner<EncodingPolicy>::StringFromDbl(double dbl)
  1938. {
  1939. if (!Js::NumberUtilities::FDblToStr(dbl, m_tempChBuf.m_prgch, m_tempChBuf.m_cchMax))
  1940. {
  1941. Error(ERRnoMemory);
  1942. }
  1943. return m_tempChBuf.m_prgch;
  1944. }
  1945. template <typename EncodingPolicy>
  1946. IdentPtr Scanner<EncodingPolicy>::PidFromDbl(double dbl)
  1947. {
  1948. return this->GetHashTbl()->PidHashName(StringFromDbl(dbl));
  1949. }
  1950. template <typename EncodingPolicy>
  1951. void Scanner<EncodingPolicy>::Capture(_Out_ RestorePoint* restorePoint)
  1952. {
  1953. Capture(restorePoint, 0, 0);
  1954. }
  1955. template <typename EncodingPolicy>
  1956. void Scanner<EncodingPolicy>::Capture(_Out_ RestorePoint* restorePoint, uint functionIdIncrement, size_t lengthDecr)
  1957. {
  1958. restorePoint->m_ichMinTok = this->IchMinTok();
  1959. restorePoint->m_ichMinLine = this->IchMinLine();
  1960. restorePoint->m_cMinTokMultiUnits = this->m_cMinTokMultiUnits;
  1961. restorePoint->m_cMinLineMultiUnits = this->m_cMinLineMultiUnits;
  1962. restorePoint->m_line = this->m_line;
  1963. restorePoint->m_fHadEol = this->m_fHadEol;
  1964. restorePoint->functionIdIncrement = functionIdIncrement;
  1965. restorePoint->lengthDecr = lengthDecr;
  1966. #ifdef DEBUG
  1967. restorePoint->m_cMultiUnits = this->m_cMultiUnits;
  1968. #endif
  1969. }
  1970. template <typename EncodingPolicy>
  1971. void Scanner<EncodingPolicy>::SeekTo(const RestorePoint& restorePoint)
  1972. {
  1973. SeekAndScan<false>(restorePoint);
  1974. }
  1975. template <typename EncodingPolicy>
  1976. void Scanner<EncodingPolicy>::SeekToForcingPid(const RestorePoint& restorePoint)
  1977. {
  1978. SeekAndScan<true>(restorePoint);
  1979. }
  1980. template <typename EncodingPolicy>
  1981. template <bool forcePid>
  1982. void Scanner<EncodingPolicy>::SeekAndScan(const RestorePoint& restorePoint)
  1983. {
  1984. this->m_currentCharacter = this->m_pchBase + restorePoint.m_ichMinTok + restorePoint.m_cMinTokMultiUnits;
  1985. this->m_pchMinLine = this->m_pchBase + restorePoint.m_ichMinLine + restorePoint.m_cMinLineMultiUnits;
  1986. this->m_cMinLineMultiUnits = restorePoint.m_cMinLineMultiUnits;
  1987. this->RestoreMultiUnits(restorePoint.m_cMinTokMultiUnits);
  1988. if (forcePid)
  1989. {
  1990. this->ScanForcingPid();
  1991. }
  1992. else
  1993. {
  1994. this->Scan();
  1995. }
  1996. this->m_line = restorePoint.m_line;
  1997. this->m_fHadEol = restorePoint.m_fHadEol;
  1998. this->m_parser->ReduceDeferredScriptLength(restorePoint.lengthDecr);
  1999. Assert(this->m_cMultiUnits == restorePoint.m_cMultiUnits);
  2000. }
  2001. template <typename EncodingPolicy>
  2002. void Scanner<EncodingPolicy>::SeekTo(const RestorePoint& restorePoint, uint *nextFunctionId)
  2003. {
  2004. SeekTo(restorePoint);
  2005. *nextFunctionId += restorePoint.functionIdIncrement;
  2006. }
  2007. // Called by CompileScriptException::ProcessError to retrieve a BSTR for the line on which an error occurred.
  2008. template<typename EncodingPolicy>
  2009. HRESULT Scanner<EncodingPolicy>::SysAllocErrorLine(int32 ichMinLine, __out BSTR* pbstrLine)
  2010. {
  2011. if( !pbstrLine )
  2012. {
  2013. return E_POINTER;
  2014. }
  2015. // If we overflow the string, we have a serious problem...
  2016. if (ichMinLine < 0 || static_cast<size_t>(ichMinLine) > AdjustedLength() )
  2017. {
  2018. return E_UNEXPECTED;
  2019. }
  2020. typename EncodingPolicy::EncodedCharPtr pStart = static_cast<size_t>(ichMinLine) == IchMinLine() ? m_pchMinLine : m_pchBase + this->CharacterOffsetToUnitOffset(m_pchBase, m_currentCharacter, m_pchLast, ichMinLine);
  2021. // Determine the length by scanning for the next newline
  2022. charcount_t cch = LineLength(pStart, m_pchLast);
  2023. Assert(cch <= LONG_MAX);
  2024. typename EncodingPolicy::EncodedCharPtr pEnd = static_cast<size_t>(ichMinLine) == IchMinLine() ? m_pchMinLine + cch : m_pchBase + this->CharacterOffsetToUnitOffset(m_pchBase, m_currentCharacter, m_pchLast, cch);
  2025. *pbstrLine = SysAllocStringLen(NULL, cch);
  2026. if (!*pbstrLine)
  2027. {
  2028. return E_OUTOFMEMORY;
  2029. }
  2030. this->ConvertToUnicode(*pbstrLine, cch, pStart, pEnd);
  2031. return S_OK;
  2032. }
  2033. template class Scanner<NotNullTerminatedUTF8EncodingPolicy>;