Scan.cpp 73 KB

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