Scan.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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. #pragma once
  6. #ifdef ENABLE_GLOBALIZATION
  7. namespace Js
  8. {
  9. class DelayLoadWindowsGlobalization;
  10. }
  11. #include "Windows.Globalization.h"
  12. #endif
  13. int CountNewlines(LPCOLESTR psz);
  14. class Parser;
  15. struct ParseContext;
  16. struct Token
  17. {
  18. private:
  19. union
  20. {
  21. struct
  22. {
  23. IdentPtr pid;
  24. const char * pchMin;
  25. int32 length;
  26. };
  27. int32 lw;
  28. struct
  29. {
  30. double dbl;
  31. // maybeInt will be true if the number did not contain 'e', 'E' , or '.'
  32. // notably important in asm.js where the '.' has semantic importance
  33. bool maybeInt;
  34. };
  35. UnifiedRegex::RegexPattern* pattern;
  36. struct
  37. {
  38. charcount_t ichMin;
  39. charcount_t ichLim;
  40. };
  41. } u;
  42. IdentPtr CreateIdentifier(HashTbl * hashTbl);
  43. public:
  44. Token() : tk(tkLim) {}
  45. tokens tk;
  46. BOOL IsIdentifier() const
  47. {
  48. return tk == tkID;
  49. }
  50. IdentPtr GetStr() const
  51. {
  52. Assert(tk == tkStrCon || tk == tkStrTmplBasic || tk == tkStrTmplBegin || tk == tkStrTmplMid || tk == tkStrTmplEnd);
  53. return u.pid;
  54. }
  55. IdentPtr GetIdentifier(HashTbl * hashTbl)
  56. {
  57. Assert(IsIdentifier() || IsReservedWord());
  58. if (u.pid)
  59. {
  60. return u.pid;
  61. }
  62. return CreateIdentifier(hashTbl);
  63. }
  64. int32 GetLong() const
  65. {
  66. Assert(tk == tkIntCon);
  67. return u.lw;
  68. }
  69. double GetDouble() const
  70. {
  71. Assert(tk == tkFltCon);
  72. return u.dbl;
  73. }
  74. bool GetDoubleMayBeInt() const
  75. {
  76. Assert(tk == tkFltCon);
  77. return u.maybeInt;
  78. }
  79. UnifiedRegex::RegexPattern * GetRegex()
  80. {
  81. Assert(tk == tkRegExp);
  82. return u.pattern;
  83. }
  84. // NOTE: THESE ROUTINES DEPEND ON THE ORDER THAT OPERATORS
  85. // ARE DECLARED IN kwd-xxx.h FILES.
  86. BOOL IsReservedWord() const
  87. {
  88. // Keywords and future reserved words (does not include operators)
  89. return tk < tkID;
  90. }
  91. BOOL IsKeyword() const;
  92. BOOL IsFutureReservedWord(const BOOL isStrictMode) const
  93. {
  94. // Reserved words that are not keywords
  95. return tk >= tkENUM && tk <= (isStrictMode ? tkSTATIC : tkENUM);
  96. }
  97. BOOL IsOperator() const
  98. {
  99. return tk >= tkComma && tk < tkLParen;
  100. }
  101. // UTF16 Scanner are only for syntax coloring. Only support
  102. // defer pid creation for UTF8
  103. void SetIdentifier(const char * pchMin, int32 len)
  104. {
  105. this->u.pid = nullptr;
  106. this->u.pchMin = pchMin;
  107. this->u.length = len;
  108. }
  109. void SetIdentifier(IdentPtr pid)
  110. {
  111. this->u.pid = pid;
  112. this->u.pchMin = nullptr;
  113. }
  114. void SetLong(int32 value)
  115. {
  116. this->u.lw = value;
  117. }
  118. void SetDouble(double dbl, bool maybeInt)
  119. {
  120. this->u.dbl = dbl;
  121. this->u.maybeInt = maybeInt;
  122. }
  123. tokens SetRegex(UnifiedRegex::RegexPattern *const pattern, Parser *const parser);
  124. };
  125. typedef BYTE UTF8Char;
  126. typedef UTF8Char* UTF8CharPtr;
  127. class NullTerminatedUnicodeEncodingPolicy
  128. {
  129. public:
  130. typedef OLECHAR EncodedChar;
  131. typedef const OLECHAR *EncodedCharPtr;
  132. protected:
  133. static const bool MultiUnitEncoding = false;
  134. static const size_t m_cMultiUnits = 0;
  135. static BOOL IsMultiUnitChar(OLECHAR ch) { return FALSE; }
  136. // See comment below regarding unused 'last' parameter
  137. static OLECHAR ReadFirst(EncodedCharPtr &p, EncodedCharPtr last) { return *p++; }
  138. template <bool bScan>
  139. static OLECHAR ReadRest(OLECHAR ch, EncodedCharPtr &p, EncodedCharPtr last) { return ch; }
  140. template <bool bScan>
  141. static OLECHAR ReadFull(EncodedCharPtr &p, EncodedCharPtr last) { return *p++; }
  142. static OLECHAR PeekFirst(EncodedCharPtr p, EncodedCharPtr last) { return *p; }
  143. static OLECHAR PeekFull(EncodedCharPtr p, EncodedCharPtr last) { return *p; }
  144. static OLECHAR ReadSurrogatePairUpper(const EncodedCharPtr&, const EncodedCharPtr& last)
  145. {
  146. AssertMsg(false, "method should not be called while scanning UTF16 string");
  147. return 0xfffe;
  148. }
  149. static void RestoreMultiUnits(size_t multiUnits) { }
  150. static size_t CharacterOffsetToUnitOffset(EncodedCharPtr start, EncodedCharPtr current, EncodedCharPtr last, charcount_t offset) { return offset; }
  151. static void ConvertToUnicode(__out_ecount_full(cch) LPOLESTR pch, charcount_t cch, EncodedCharPtr start, EncodedCharPtr end)
  152. {
  153. Unused(end);
  154. js_memcpy_s(pch, cch * sizeof(OLECHAR), start, cch * sizeof(OLECHAR));
  155. }
  156. public:
  157. void Clear() {}
  158. void SetIsUtf8(bool isUtf8) { }
  159. bool IsUtf8() const { return false; }
  160. };
  161. template <bool nullTerminated>
  162. class UTF8EncodingPolicyBase
  163. {
  164. public:
  165. typedef utf8char_t EncodedChar;
  166. typedef LPCUTF8 EncodedCharPtr;
  167. protected:
  168. static const bool MultiUnitEncoding = true;
  169. size_t m_cMultiUnits;
  170. utf8::DecodeOptions m_decodeOptions;
  171. UTF8EncodingPolicyBase() { Clear(); }
  172. static BOOL IsMultiUnitChar(OLECHAR ch) { return ch > 0x7f; }
  173. // Note when nullTerminated is false we still need to increment the character pointer because the scanner "puts back" this virtual null character by decrementing the pointer
  174. static OLECHAR ReadFirst(EncodedCharPtr &p, EncodedCharPtr last) { return (nullTerminated || p < last) ? static_cast<OLECHAR>(*p++) : (p++, 0); }
  175. // "bScan" indicates if this ReadFull is part of scanning. Pass true during scanning and ReadFull will update
  176. // related Scanner state. The caller is supposed to sync result "p" to Scanner's current position. Pass false
  177. // otherwise and this doesn't affect Scanner state.
  178. template <bool bScan>
  179. OLECHAR ReadFull(EncodedCharPtr &p, EncodedCharPtr last)
  180. {
  181. EncodedChar ch = (nullTerminated || p < last) ? *p++ : (p++, 0);
  182. return !IsMultiUnitChar(ch) ? static_cast<OLECHAR>(ch) : ReadRest<bScan>(ch, p, last);
  183. }
  184. OLECHAR ReadSurrogatePairUpper(EncodedCharPtr &p, EncodedCharPtr last)
  185. {
  186. EncodedChar ch = (nullTerminated || p < last) ? *p++ : (p++, 0);
  187. Assert(IsMultiUnitChar(ch));
  188. this->m_decodeOptions |= utf8::DecodeOptions::doSecondSurrogatePair;
  189. return ReadRest<true>(ch, p, last);
  190. }
  191. static OLECHAR PeekFirst(EncodedCharPtr p, EncodedCharPtr last) { return (nullTerminated || p < last) ? static_cast<OLECHAR>(*p) : 0; }
  192. OLECHAR PeekFull(EncodedCharPtr p, EncodedCharPtr last)
  193. {
  194. OLECHAR result = PeekFirst(p, last);
  195. if (IsMultiUnitChar(result))
  196. {
  197. result = ReadFull<false>(p, last);
  198. }
  199. return result;
  200. }
  201. // "bScan" indicates if this ReadRest is part of scanning. Pass true during scanning and ReadRest will update
  202. // related Scanner state. The caller is supposed to sync result "p" to Scanner's current position. Pass false
  203. // otherwise and this doesn't affect Scanner state.
  204. template <bool bScan>
  205. OLECHAR ReadRest(OLECHAR ch, EncodedCharPtr &p, EncodedCharPtr last)
  206. {
  207. EncodedCharPtr s;
  208. utf8::DecodeOptions decodeOptions = m_decodeOptions;
  209. if (bScan)
  210. {
  211. s = p;
  212. }
  213. OLECHAR result = utf8::DecodeTail(ch, p, last, m_decodeOptions);
  214. if (bScan)
  215. {
  216. if ((decodeOptions & utf8::doSecondSurrogatePair) && (p - s > 2))
  217. {
  218. // 4 byte utf8 chars equals 2 utf16 chars + 2 multi-unit chars only (refer to case4: in utf8::DecodeTail()).
  219. m_cMultiUnits += 2;
  220. }
  221. else
  222. {
  223. // If we are scanning, update m_cMultiUnits counter.
  224. m_cMultiUnits += p - s;
  225. }
  226. }
  227. return result;
  228. }
  229. void RestoreMultiUnits(size_t multiUnits) { m_cMultiUnits = multiUnits; }
  230. size_t CharacterOffsetToUnitOffset(EncodedCharPtr start, EncodedCharPtr current, EncodedCharPtr last, charcount_t offset)
  231. {
  232. // Note: current may be before or after last. If last is the null terminator, current should be within [start, last].
  233. // But if we excluded HTMLCommentSuffix for the source, last is before "// -->\0". Scanner may stop at null
  234. // terminator past last, then current is after last.
  235. Assert(current >= start);
  236. size_t currentUnitOffset = current - start;
  237. Assert(currentUnitOffset > m_cMultiUnits);
  238. Assert(currentUnitOffset - m_cMultiUnits < LONG_MAX);
  239. charcount_t currentCharacterOffset = charcount_t(currentUnitOffset - m_cMultiUnits);
  240. // If the offset is the current character offset then just return the current unit offset.
  241. if (currentCharacterOffset == offset) return currentUnitOffset;
  242. // If we have not encountered any multi-unit characters and we are moving backward the
  243. // character index and unit index are 1:1 so just return offset
  244. if (m_cMultiUnits == 0 && offset <= currentCharacterOffset) return offset;
  245. // Use local decode options
  246. utf8::DecodeOptions decodeOptions = IsUtf8() ? utf8::doDefault : utf8::doAllowThreeByteSurrogates;
  247. if (offset > currentCharacterOffset)
  248. {
  249. // If we are looking for an offset past current, current must be within [start, last]. We don't expect seeking
  250. // scanner position past last.
  251. Assert(current <= last);
  252. // If offset > currentOffset we already know the current character offset. The unit offset is the
  253. // unit index of offset - currentOffset characters from current.
  254. charcount_t charsLeft = offset - currentCharacterOffset;
  255. return currentUnitOffset + utf8::CharacterIndexToByteIndex(current, last - current, charsLeft, decodeOptions);
  256. }
  257. // If all else fails calculate the index from the start of the buffer.
  258. return utf8::CharacterIndexToByteIndex(start, currentUnitOffset, offset, decodeOptions);
  259. }
  260. void ConvertToUnicode(__out_ecount_full(cch) LPOLESTR pch, charcount_t cch, EncodedCharPtr start, EncodedCharPtr end)
  261. {
  262. m_decodeOptions = (utf8::DecodeOptions)(m_decodeOptions & ~utf8::doSecondSurrogatePair);
  263. utf8::DecodeUnitsInto(pch, start, end, m_decodeOptions);
  264. }
  265. public:
  266. void Clear()
  267. {
  268. m_cMultiUnits = 0;
  269. m_decodeOptions = utf8::doAllowThreeByteSurrogates;
  270. }
  271. // If we get UTF8 source buffer, turn off doAllowThreeByteSurrogates but allow invalid WCHARs without replacing them with replacement 'g_chUnknown'.
  272. void SetIsUtf8(bool isUtf8)
  273. {
  274. if (isUtf8)
  275. {
  276. m_decodeOptions = (utf8::DecodeOptions)(m_decodeOptions & ~utf8::doAllowThreeByteSurrogates | utf8::doAllowInvalidWCHARs);
  277. }
  278. else
  279. {
  280. m_decodeOptions = (utf8::DecodeOptions)(m_decodeOptions & ~utf8::doAllowInvalidWCHARs | utf8::doAllowThreeByteSurrogates);
  281. }
  282. }
  283. bool IsUtf8() const { return (m_decodeOptions & utf8::doAllowThreeByteSurrogates) == 0; }
  284. };
  285. typedef UTF8EncodingPolicyBase<false> NotNullTerminatedUTF8EncodingPolicy;
  286. interface IScanner
  287. {
  288. virtual void GetErrorLineInfo(__out int32& ichMin, __out int32& ichLim, __out int32& line, __out int32& ichMinLine) = 0;
  289. virtual HRESULT SysAllocErrorLine(int32 ichMinLine, __out BSTR* pbstrLine) = 0;
  290. };
  291. // Flags that can be provided to the Scan functions.
  292. // These can be bitwise OR'ed.
  293. enum ScanFlag
  294. {
  295. ScanFlagNone = 0,
  296. ScanFlagSuppressStrPid = 1, // Force strings to always have pid
  297. };
  298. typedef HRESULT (*CommentCallback)(void *data, OLECHAR firstChar, OLECHAR secondChar, bool containTypeDef, charcount_t min, charcount_t lim, bool adjacent, bool multiline, charcount_t startLine, charcount_t endLine);
  299. // Restore point defined using a relative offset rather than a pointer.
  300. struct RestorePoint
  301. {
  302. Field(charcount_t) m_ichMinTok;
  303. Field(charcount_t) m_ichMinLine;
  304. Field(size_t) m_cMinTokMultiUnits;
  305. Field(size_t) m_cMinLineMultiUnits;
  306. Field(charcount_t) m_line;
  307. Field(uint) functionIdIncrement;
  308. Field(size_t) lengthDecr;
  309. Field(BOOL) m_fHadEol;
  310. #ifdef DEBUG
  311. Field(size_t) m_cMultiUnits;
  312. #endif
  313. RestorePoint()
  314. : m_ichMinTok((charcount_t)-1),
  315. m_ichMinLine((charcount_t)-1),
  316. m_cMinTokMultiUnits((size_t)-1),
  317. m_cMinLineMultiUnits((size_t)-1),
  318. m_line((charcount_t)-1),
  319. functionIdIncrement(0),
  320. lengthDecr(0),
  321. m_fHadEol(FALSE)
  322. #ifdef DEBUG
  323. , m_cMultiUnits((size_t)-1)
  324. #endif
  325. {
  326. };
  327. };
  328. template <typename EncodingPolicy>
  329. class Scanner : public IScanner, public EncodingPolicy
  330. {
  331. friend Parser;
  332. typedef typename EncodingPolicy::EncodedChar EncodedChar;
  333. typedef typename EncodingPolicy::EncodedCharPtr EncodedCharPtr;
  334. public:
  335. Scanner(Parser* parser, Token *ptoken, Js::ScriptContext *scriptContext);
  336. ~Scanner(void);
  337. tokens Scan();
  338. tokens ScanNoKeywords();
  339. tokens ScanForcingPid();
  340. void SetText(EncodedCharPtr psz, size_t offset, size_t length, charcount_t characterOffset, bool isUtf8, ULONG grfscr, ULONG lineNumber = 0);
  341. #if ENABLE_BACKGROUND_PARSING
  342. void PrepareForBackgroundParse(Js::ScriptContext *scriptContext);
  343. #endif
  344. enum ScanState
  345. {
  346. ScanStateNormal = 0,
  347. ScanStateStringTemplateMiddleOrEnd = 1,
  348. };
  349. ScanState GetScanState() { return m_scanState; }
  350. void SetScanState(ScanState state) { m_scanState = state; }
  351. bool SetYieldIsKeywordRegion(bool fYieldIsKeywordRegion)
  352. {
  353. bool fPrevYieldIsKeywordRegion = m_fYieldIsKeywordRegion;
  354. m_fYieldIsKeywordRegion = fYieldIsKeywordRegion;
  355. return fPrevYieldIsKeywordRegion;
  356. }
  357. bool YieldIsKeywordRegion()
  358. {
  359. return m_fYieldIsKeywordRegion;
  360. }
  361. bool YieldIsKeyword()
  362. {
  363. return YieldIsKeywordRegion() || this->IsStrictMode();
  364. }
  365. bool SetAwaitIsKeywordRegion(bool fAwaitIsKeywordRegion)
  366. {
  367. bool fPrevAwaitIsKeywordRegion = m_fAwaitIsKeywordRegion;
  368. m_fAwaitIsKeywordRegion = fAwaitIsKeywordRegion;
  369. return fPrevAwaitIsKeywordRegion;
  370. }
  371. bool AwaitIsKeywordRegion()
  372. {
  373. return m_fAwaitIsKeywordRegion;
  374. }
  375. bool AwaitIsKeyword()
  376. {
  377. return AwaitIsKeywordRegion() || this->m_fIsModuleCode;
  378. }
  379. tokens TryRescanRegExp();
  380. tokens RescanRegExp();
  381. tokens RescanRegExpNoAST();
  382. tokens RescanRegExpTokenizer();
  383. BOOL FHadNewLine(void)
  384. {
  385. return m_fHadEol;
  386. }
  387. IdentPtr PidFromLong(int32 lw);
  388. IdentPtr PidFromDbl(double dbl);
  389. LPCOLESTR StringFromLong(int32 lw);
  390. LPCOLESTR StringFromDbl(double dbl);
  391. IdentPtr GetSecondaryBufferAsPid();
  392. BYTE SetDeferredParse(BOOL defer)
  393. {
  394. BYTE fOld = m_DeferredParseFlags;
  395. if (defer)
  396. {
  397. m_DeferredParseFlags |= ScanFlagSuppressStrPid;
  398. }
  399. else
  400. {
  401. m_DeferredParseFlags = ScanFlagNone;
  402. }
  403. return fOld;
  404. }
  405. void SetDeferredParseFlags(BYTE flags)
  406. {
  407. m_DeferredParseFlags = flags;
  408. }
  409. // the functions IsDoubleQuoteOnLastTkStrCon() and IsHexOrOctOnLastTKNumber() works only with a scanner without lookahead
  410. // Both functions are used to get more info on the last token for specific diffs necessary for JSON parsing.
  411. //Single quotes are not legal in JSON strings. Make distinction between single quote string constant and single quote string
  412. BOOL IsDoubleQuoteOnLastTkStrCon()
  413. {
  414. return m_doubleQuoteOnLastTkStrCon;
  415. }
  416. // True if all chars of last string constant are ascii
  417. BOOL IsEscapeOnLastTkStrCon()
  418. {
  419. return m_EscapeOnLastTkStrCon;
  420. }
  421. bool IsOctOrLeadingZeroOnLastTKNumber()
  422. {
  423. return m_OctOrLeadingZeroOnLastTKNumber;
  424. }
  425. // Returns the character offset of the first token. The character offset is the offset the first character of the token would
  426. // have if the entire file was converted to Unicode (UTF16-LE).
  427. charcount_t IchMinTok(void) const
  428. {
  429. Assert(m_pchMinTok - m_pchBase >= 0);
  430. Assert(m_pchMinTok - m_pchBase <= LONG_MAX);
  431. Assert(static_cast<charcount_t>(m_pchMinTok - m_pchBase) >= m_cMinTokMultiUnits);
  432. return static_cast<charcount_t>(m_pchMinTok - m_pchBase - m_cMinTokMultiUnits);
  433. }
  434. // Returns the character offset of the character immediately following the token. The character offset is the offset the first
  435. // character of the token would have if the entire file was converted to Unicode (UTF16-LE).
  436. charcount_t IchLimTok(void) const
  437. {
  438. Assert(m_currentCharacter - m_pchBase >= 0);
  439. Assert(m_currentCharacter - m_pchBase <= LONG_MAX);
  440. Assert(static_cast<charcount_t>(m_currentCharacter - m_pchBase) >= this->m_cMultiUnits);
  441. return static_cast<charcount_t>(m_currentCharacter - m_pchBase - this->m_cMultiUnits);
  442. }
  443. void SetErrorPosition(charcount_t ichMinError, charcount_t ichLimError)
  444. {
  445. Assert(ichLimError > 0 || ichMinError == 0);
  446. m_ichMinError = ichMinError;
  447. m_ichLimError = ichLimError;
  448. }
  449. charcount_t IchMinError(void) const
  450. {
  451. return m_ichLimError ? m_ichMinError : IchMinTok();
  452. }
  453. charcount_t IchLimError(void) const
  454. {
  455. return m_ichLimError ? m_ichLimError : IchLimTok();
  456. }
  457. // Returns the encoded unit offset of first character of the token. For example, in a UTF-8 encoding this is the offset into
  458. // the UTF-8 buffer. In Unicode this is the same as IchMinTok().
  459. size_t IecpMinTok(void) const
  460. {
  461. return static_cast< size_t >(m_pchMinTok - m_pchBase);
  462. }
  463. // Returns the encoded unit offset of the character immediately following the token. For example, in a UTF-8 encoding this is
  464. // the offset into the UTF-8 buffer. In Unicode this is the same as IchLimTok().
  465. size_t IecpLimTok(void) const
  466. {
  467. return static_cast< size_t >(m_currentCharacter - m_pchBase);
  468. }
  469. size_t IecpLimTokPrevious() const
  470. {
  471. AssertMsg(m_iecpLimTokPrevious != (size_t)-1, "IecpLimTokPrevious() cannot be called before scanning a token");
  472. return m_iecpLimTokPrevious;
  473. }
  474. charcount_t IchLimTokPrevious() const
  475. {
  476. AssertMsg(m_ichLimTokPrevious != (charcount_t)-1, "IchLimTokPrevious() cannot be called before scanning a token");
  477. return m_ichLimTokPrevious;
  478. }
  479. IdentPtr PidAt(size_t iecpMin, size_t iecpLim);
  480. // Returns the character offset within the stream of the first character on the current line.
  481. charcount_t IchMinLine(void) const
  482. {
  483. Assert(m_pchMinLine - m_pchBase >= 0);
  484. Assert(m_pchMinLine - m_pchBase <= LONG_MAX);
  485. Assert(static_cast<charcount_t>(m_pchMinLine - m_pchBase) >= m_cMinLineMultiUnits);
  486. return static_cast<charcount_t>(m_pchMinLine - m_pchBase - m_cMinLineMultiUnits);
  487. }
  488. // Returns the current line number
  489. charcount_t LineCur(void) const { return m_line; }
  490. void SetCurrentCharacter(charcount_t offset, ULONG lineNumber = 0)
  491. {
  492. DebugOnly(m_iecpLimTokPrevious = (size_t)-1);
  493. DebugOnly(m_ichLimTokPrevious = (charcount_t)-1);
  494. size_t length = m_pchLast - m_pchBase;
  495. if (offset > length) offset = static_cast< charcount_t >(length);
  496. size_t ibOffset = this->CharacterOffsetToUnitOffset(m_pchBase, m_currentCharacter, m_pchLast, offset);
  497. m_currentCharacter = m_pchBase + ibOffset;
  498. Assert(ibOffset >= offset);
  499. this->RestoreMultiUnits(ibOffset - offset);
  500. m_line = lineNumber;
  501. }
  502. // IScanner methods
  503. virtual void GetErrorLineInfo(__out int32& ichMin, __out int32& ichLim, __out int32& line, __out int32& ichMinLine)
  504. {
  505. ichMin = this->IchMinError();
  506. ichLim = this->IchLimError();
  507. line = this->LineCur();
  508. ichMinLine = this->IchMinLine();
  509. if (m_ichLimError && m_ichMinError < (charcount_t)ichMinLine)
  510. {
  511. line = m_startLine;
  512. ichMinLine = UpdateLine(line, m_pchStartLine, m_pchLast, 0, ichMin);
  513. }
  514. }
  515. virtual HRESULT SysAllocErrorLine(int32 ichMinLine, __out BSTR* pbstrLine);
  516. class TemporaryBuffer
  517. {
  518. friend Scanner<EncodingPolicy>;
  519. private:
  520. // Keep a reference to the scanner.
  521. // We will use it to signal an error if we fail to allocate the buffer.
  522. Scanner<EncodingPolicy>* m_pscanner;
  523. uint32 m_cchMax;
  524. uint32 m_ichCur;
  525. __field_ecount(m_cchMax) OLECHAR *m_prgch;
  526. byte m_rgbInit[256];
  527. public:
  528. TemporaryBuffer()
  529. {
  530. m_pscanner = nullptr;
  531. m_prgch = (OLECHAR*)m_rgbInit;
  532. m_cchMax = _countof(m_rgbInit) / sizeof(OLECHAR);
  533. m_ichCur = 0;
  534. }
  535. ~TemporaryBuffer()
  536. {
  537. if (m_prgch != (OLECHAR*)m_rgbInit)
  538. {
  539. free(m_prgch);
  540. }
  541. }
  542. void Reset()
  543. {
  544. m_ichCur = 0;
  545. }
  546. void Clear()
  547. {
  548. if (m_prgch != (OLECHAR*)m_rgbInit)
  549. {
  550. free(m_prgch);
  551. m_prgch = (OLECHAR*)m_rgbInit;
  552. m_cchMax = _countof(m_rgbInit) / sizeof(OLECHAR);
  553. }
  554. Reset();
  555. }
  556. void AppendCh(uint ch)
  557. {
  558. return AppendCh<true>(ch);
  559. }
  560. template<bool performAppend> void AppendCh(uint ch)
  561. {
  562. if (performAppend)
  563. {
  564. if (m_ichCur >= m_cchMax)
  565. {
  566. Grow();
  567. }
  568. Assert(m_ichCur < m_cchMax);
  569. __analysis_assume(m_ichCur < m_cchMax);
  570. m_prgch[m_ichCur++] = static_cast<OLECHAR>(ch);
  571. }
  572. }
  573. private:
  574. void Grow()
  575. {
  576. Assert(m_pscanner != nullptr);
  577. byte *prgbNew;
  578. byte *prgbOld = (byte *)m_prgch;
  579. ULONG cbNew;
  580. if (FAILED(ULongMult(m_cchMax, sizeof(OLECHAR) * 2, &cbNew)))
  581. {
  582. m_pscanner->Error(ERRnoMemory);
  583. }
  584. if (prgbOld == m_rgbInit)
  585. {
  586. if (nullptr == (prgbNew = static_cast<byte*>(malloc(cbNew))))
  587. m_pscanner->Error(ERRnoMemory);
  588. js_memcpy_s(prgbNew, cbNew, prgbOld, m_ichCur * sizeof(OLECHAR));
  589. }
  590. else if (nullptr == (prgbNew = static_cast<byte*>(realloc(prgbOld, cbNew))))
  591. {
  592. m_pscanner->Error(ERRnoMemory);
  593. }
  594. m_prgch = (OLECHAR*)prgbNew;
  595. m_cchMax = cbNew / sizeof(OLECHAR);
  596. }
  597. };
  598. void Capture(_Out_ RestorePoint* restorePoint);
  599. void SeekTo(const RestorePoint& restorePoint);
  600. void SeekToForcingPid(const RestorePoint& restorePoint);
  601. void Capture(_Out_ RestorePoint* restorePoint, uint functionIdIncrement, size_t lengthDecr);
  602. void SeekTo(const RestorePoint& restorePoint, uint *nextFunctionId);
  603. void Clear();
  604. HashTbl * GetHashTbl() { return &m_htbl; }
  605. private:
  606. Parser *m_parser;
  607. HashTbl m_htbl;
  608. Token *m_ptoken;
  609. EncodedCharPtr m_pchBase; // beginning of source
  610. EncodedCharPtr m_pchLast; // The end of source
  611. EncodedCharPtr m_pchMinLine; // beginning of current line
  612. EncodedCharPtr m_pchMinTok; // beginning of current token
  613. EncodedCharPtr m_currentCharacter; // current character
  614. EncodedCharPtr m_pchPrevLine; // beginning of previous line
  615. size_t m_cMinTokMultiUnits; // number of multi-unit characters previous to m_pchMinTok
  616. size_t m_cMinLineMultiUnits; // number of multi-unit characters previous to m_pchMinLine
  617. uint16 m_fStringTemplateDepth; // we should treat } as string template middle starting character (depth instead of flag)
  618. BOOL m_fHadEol;
  619. BOOL m_fIsModuleCode : 1;
  620. BOOL m_doubleQuoteOnLastTkStrCon :1;
  621. bool m_OctOrLeadingZeroOnLastTKNumber :1;
  622. bool m_EscapeOnLastTkStrCon:1;
  623. BOOL m_fNextStringTemplateIsTagged:1; // the next string template scanned has a tag (must create raw strings)
  624. BYTE m_DeferredParseFlags:2; // suppressStrPid and suppressIdPid
  625. bool es6UnicodeMode; // True if ES6Unicode Extensions are enabled.
  626. bool m_fYieldIsKeywordRegion; // Whether to treat 'yield' as an identifier or keyword
  627. bool m_fAwaitIsKeywordRegion; // Whether to treat 'await' as an identifier or keyword
  628. // Temporary buffer.
  629. TemporaryBuffer m_tempChBuf;
  630. TemporaryBuffer m_tempChBufSecondary;
  631. charcount_t m_line;
  632. ScanState m_scanState;
  633. charcount_t m_ichMinError;
  634. charcount_t m_ichLimError;
  635. charcount_t m_startLine;
  636. EncodedCharPtr m_pchStartLine;
  637. Js::ScriptContext* m_scriptContext;
  638. const Js::CharClassifier *charClassifier;
  639. tokens m_tkPrevious;
  640. size_t m_iecpLimTokPrevious;
  641. charcount_t m_ichLimTokPrevious;
  642. void ClearStates();
  643. template <bool forcePid>
  644. void SeekAndScan(const RestorePoint& restorePoint);
  645. tokens ScanCore(bool identifyKwds);
  646. tokens ScanAhead();
  647. tokens ScanError(EncodedCharPtr pchCur, tokens errorToken)
  648. {
  649. m_currentCharacter = pchCur;
  650. return m_ptoken->tk = tkScanError;
  651. }
  652. __declspec(noreturn) void Error(HRESULT hr)
  653. {
  654. m_pchMinTok = m_currentCharacter;
  655. m_cMinTokMultiUnits = this->m_cMultiUnits;
  656. throw ParseExceptionObject(hr);
  657. }
  658. const EncodedCharPtr PchBase(void) const
  659. {
  660. return m_pchBase;
  661. }
  662. const EncodedCharPtr PchMinTok(void)
  663. {
  664. return m_pchMinTok;
  665. }
  666. template<bool stringTemplateMode, bool createRawString> tokens ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp);
  667. tokens ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp);
  668. tokens ScanStringTemplateBegin(EncodedCharPtr *pp);
  669. tokens ScanStringTemplateMiddleOrEnd(EncodedCharPtr *pp);
  670. void ScanNewLine(uint ch);
  671. void NotifyScannedNewLine();
  672. charcount_t LineLength(EncodedCharPtr first, EncodedCharPtr last, size_t* cb);
  673. tokens ScanIdentifier(bool identifyKwds, EncodedCharPtr *pp);
  674. BOOL FastIdentifierContinue(EncodedCharPtr&p, EncodedCharPtr last);
  675. tokens ScanIdentifierContinue(bool identifyKwds, bool fHasEscape, bool fHasMultiChar, EncodedCharPtr pchMin, EncodedCharPtr p, EncodedCharPtr *pp);
  676. tokens SkipComment(EncodedCharPtr *pp, /* out */ bool* containTypeDef);
  677. tokens ScanRegExpConstant(ArenaAllocator* alloc);
  678. tokens ScanRegExpConstantNoAST(ArenaAllocator* alloc);
  679. EncodedCharPtr FScanNumber(EncodedCharPtr p, double *pdbl, bool& likelyInt);
  680. IdentPtr PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last, bool fHadEscape, bool fHasMultiChar);
  681. IdentPtr PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last);
  682. uint32 UnescapeToTempBuf(EncodedCharPtr p, EncodedCharPtr last);
  683. void SaveSrcPos(void)
  684. {
  685. m_pchMinTok = m_currentCharacter;
  686. }
  687. OLECHAR PeekNextChar(void)
  688. {
  689. return this->PeekFull(m_currentCharacter, m_pchLast);
  690. }
  691. OLECHAR ReadNextChar(void)
  692. {
  693. return this->template ReadFull<true>(m_currentCharacter, m_pchLast);
  694. }
  695. EncodedCharPtr AdjustedLast() const
  696. {
  697. return m_pchLast;
  698. }
  699. size_t AdjustedLength() const
  700. {
  701. return AdjustedLast() - m_pchBase;
  702. }
  703. bool IsStrictMode() const
  704. {
  705. return this->m_parser != NULL && this->m_parser->IsStrictMode();
  706. }
  707. // This function expects the first character to be a 'u'
  708. // It will attempt to return a codepoint represented by a single escape point (either of the form \uXXXX or \u{any number of hex characters, s.t. value < 0x110000}
  709. bool TryReadEscape(EncodedCharPtr &startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar = nullptr);
  710. template <bool bScan>
  711. bool TryReadCodePointRest(codepoint_t lower, EncodedCharPtr &startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *outContainsMultiUnitChar);
  712. template <bool bScan>
  713. inline bool TryReadCodePoint(EncodedCharPtr &startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *hasEscape, bool *outContainsMultiUnitChar);
  714. inline BOOL IsIdContinueNext(EncodedCharPtr startingLocation, EncodedCharPtr endOfSource)
  715. {
  716. codepoint_t nextCodepoint;
  717. bool ignore;
  718. if (TryReadCodePoint<false>(startingLocation, endOfSource, &nextCodepoint, &ignore, &ignore))
  719. {
  720. return charClassifier->IsIdContinue(nextCodepoint);
  721. }
  722. return false;
  723. }
  724. charcount_t UpdateLine(int32 &line, EncodedCharPtr start, EncodedCharPtr last, charcount_t ichStart, charcount_t ichEnd);
  725. };