2
0

Scan.cpp 71 KB

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