Scan.cpp 71 KB

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