2
0

Scan.cpp 70 KB

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