Scan.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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. if (bScan)
  209. {
  210. s = p;
  211. }
  212. OLECHAR result = utf8::DecodeTail(ch, p, last, m_decodeOptions);
  213. if (bScan)
  214. {
  215. // If we are scanning, update m_cMultiUnits counter.
  216. m_cMultiUnits += p - s;
  217. }
  218. return result;
  219. }
  220. void RestoreMultiUnits(size_t multiUnits) { m_cMultiUnits = multiUnits; }
  221. size_t CharacterOffsetToUnitOffset(EncodedCharPtr start, EncodedCharPtr current, EncodedCharPtr last, charcount_t offset)
  222. {
  223. // Note: current may be before or after last. If last is the null terminator, current should be within [start, last].
  224. // But if we excluded HTMLCommentSuffix for the source, last is before "// -->\0". Scanner may stop at null
  225. // terminator past last, then current is after last.
  226. Assert(current >= start);
  227. size_t currentUnitOffset = current - start;
  228. Assert(currentUnitOffset > m_cMultiUnits);
  229. Assert(currentUnitOffset - m_cMultiUnits < LONG_MAX);
  230. charcount_t currentCharacterOffset = charcount_t(currentUnitOffset - m_cMultiUnits);
  231. // If the offset is the current character offset then just return the current unit offset.
  232. if (currentCharacterOffset == offset) return currentUnitOffset;
  233. // If we have not encountered any multi-unit characters and we are moving backward the
  234. // character index and unit index are 1:1 so just return offset
  235. if (m_cMultiUnits == 0 && offset <= currentCharacterOffset) return offset;
  236. // Use local decode options
  237. utf8::DecodeOptions decodeOptions = IsUtf8() ? utf8::doDefault : utf8::doAllowThreeByteSurrogates;
  238. if (offset > currentCharacterOffset)
  239. {
  240. // If we are looking for an offset past current, current must be within [start, last]. We don't expect seeking
  241. // scanner position past last.
  242. Assert(current <= last);
  243. // If offset > currentOffset we already know the current character offset. The unit offset is the
  244. // unit index of offset - currentOffset characters from current.
  245. charcount_t charsLeft = offset - currentCharacterOffset;
  246. return currentUnitOffset + utf8::CharacterIndexToByteIndex(current, last - current, charsLeft, decodeOptions);
  247. }
  248. // If all else fails calculate the index from the start of the buffer.
  249. return utf8::CharacterIndexToByteIndex(start, currentUnitOffset, offset, decodeOptions);
  250. }
  251. void ConvertToUnicode(__out_ecount_full(cch) LPOLESTR pch, charcount_t cch, EncodedCharPtr start, EncodedCharPtr end)
  252. {
  253. m_decodeOptions = (utf8::DecodeOptions)(m_decodeOptions & ~utf8::doSecondSurrogatePair);
  254. utf8::DecodeUnitsInto(pch, start, end, m_decodeOptions);
  255. }
  256. public:
  257. void Clear()
  258. {
  259. m_cMultiUnits = 0;
  260. m_decodeOptions = utf8::doAllowThreeByteSurrogates;
  261. }
  262. // If we get UTF8 source buffer, turn off doAllowThreeByteSurrogates but allow invalid WCHARs without replacing them with replacement 'g_chUnknown'.
  263. void SetIsUtf8(bool isUtf8)
  264. {
  265. if (isUtf8)
  266. {
  267. m_decodeOptions = (utf8::DecodeOptions)(m_decodeOptions & ~utf8::doAllowThreeByteSurrogates | utf8::doAllowInvalidWCHARs);
  268. }
  269. else
  270. {
  271. m_decodeOptions = (utf8::DecodeOptions)(m_decodeOptions & ~utf8::doAllowInvalidWCHARs | utf8::doAllowThreeByteSurrogates);
  272. }
  273. }
  274. bool IsUtf8() const { return (m_decodeOptions & utf8::doAllowThreeByteSurrogates) == 0; }
  275. };
  276. typedef UTF8EncodingPolicyBase<false> NotNullTerminatedUTF8EncodingPolicy;
  277. interface IScanner
  278. {
  279. virtual void GetErrorLineInfo(__out int32& ichMin, __out int32& ichLim, __out int32& line, __out int32& ichMinLine) = 0;
  280. virtual HRESULT SysAllocErrorLine(int32 ichMinLine, __out BSTR* pbstrLine) = 0;
  281. };
  282. // Flags that can be provided to the Scan functions.
  283. // These can be bitwise OR'ed.
  284. enum ScanFlag
  285. {
  286. ScanFlagNone = 0,
  287. ScanFlagSuppressStrPid = 1, // Force strings to always have pid
  288. };
  289. 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);
  290. // Restore point defined using a relative offset rather than a pointer.
  291. struct RestorePoint
  292. {
  293. Field(charcount_t) m_ichMinTok;
  294. Field(charcount_t) m_ichMinLine;
  295. Field(size_t) m_cMinTokMultiUnits;
  296. Field(size_t) m_cMinLineMultiUnits;
  297. Field(charcount_t) m_line;
  298. Field(uint) functionIdIncrement;
  299. Field(size_t) lengthDecr;
  300. Field(BOOL) m_fHadEol;
  301. #ifdef DEBUG
  302. Field(size_t) m_cMultiUnits;
  303. #endif
  304. RestorePoint()
  305. : m_ichMinTok((charcount_t)-1),
  306. m_ichMinLine((charcount_t)-1),
  307. m_cMinTokMultiUnits((size_t)-1),
  308. m_cMinLineMultiUnits((size_t)-1),
  309. m_line((charcount_t)-1),
  310. functionIdIncrement(0),
  311. lengthDecr(0),
  312. m_fHadEol(FALSE)
  313. #ifdef DEBUG
  314. , m_cMultiUnits((size_t)-1)
  315. #endif
  316. {
  317. };
  318. };
  319. template <typename EncodingPolicy>
  320. class Scanner : public IScanner, public EncodingPolicy
  321. {
  322. friend Parser;
  323. typedef typename EncodingPolicy::EncodedChar EncodedChar;
  324. typedef typename EncodingPolicy::EncodedCharPtr EncodedCharPtr;
  325. public:
  326. Scanner(Parser* parser, Token *ptoken, Js::ScriptContext *scriptContext);
  327. ~Scanner(void);
  328. tokens Scan();
  329. tokens ScanNoKeywords();
  330. tokens ScanForcingPid();
  331. void SetText(EncodedCharPtr psz, size_t offset, size_t length, charcount_t characterOffset, bool isUtf8, ULONG grfscr, ULONG lineNumber = 0);
  332. #if ENABLE_BACKGROUND_PARSING
  333. void PrepareForBackgroundParse(Js::ScriptContext *scriptContext);
  334. #endif
  335. enum ScanState
  336. {
  337. ScanStateNormal = 0,
  338. ScanStateStringTemplateMiddleOrEnd = 1,
  339. };
  340. ScanState GetScanState() { return m_scanState; }
  341. void SetScanState(ScanState state) { m_scanState = state; }
  342. bool SetYieldIsKeywordRegion(bool fYieldIsKeywordRegion)
  343. {
  344. bool fPrevYieldIsKeywordRegion = m_fYieldIsKeywordRegion;
  345. m_fYieldIsKeywordRegion = fYieldIsKeywordRegion;
  346. return fPrevYieldIsKeywordRegion;
  347. }
  348. bool YieldIsKeywordRegion()
  349. {
  350. return m_fYieldIsKeywordRegion;
  351. }
  352. bool YieldIsKeyword()
  353. {
  354. return YieldIsKeywordRegion() || this->IsStrictMode();
  355. }
  356. bool SetAwaitIsKeywordRegion(bool fAwaitIsKeywordRegion)
  357. {
  358. bool fPrevAwaitIsKeywordRegion = m_fAwaitIsKeywordRegion;
  359. m_fAwaitIsKeywordRegion = fAwaitIsKeywordRegion;
  360. return fPrevAwaitIsKeywordRegion;
  361. }
  362. bool AwaitIsKeywordRegion()
  363. {
  364. return m_fAwaitIsKeywordRegion;
  365. }
  366. bool AwaitIsKeyword()
  367. {
  368. return AwaitIsKeywordRegion() || this->m_fIsModuleCode;
  369. }
  370. tokens TryRescanRegExp();
  371. tokens RescanRegExp();
  372. tokens RescanRegExpNoAST();
  373. tokens RescanRegExpTokenizer();
  374. BOOL FHadNewLine(void)
  375. {
  376. return m_fHadEol;
  377. }
  378. IdentPtr PidFromLong(int32 lw);
  379. IdentPtr PidFromDbl(double dbl);
  380. LPCOLESTR StringFromLong(int32 lw);
  381. LPCOLESTR StringFromDbl(double dbl);
  382. IdentPtr GetSecondaryBufferAsPid();
  383. BYTE SetDeferredParse(BOOL defer)
  384. {
  385. BYTE fOld = m_DeferredParseFlags;
  386. if (defer)
  387. {
  388. m_DeferredParseFlags |= ScanFlagSuppressStrPid;
  389. }
  390. else
  391. {
  392. m_DeferredParseFlags = ScanFlagNone;
  393. }
  394. return fOld;
  395. }
  396. void SetDeferredParseFlags(BYTE flags)
  397. {
  398. m_DeferredParseFlags = flags;
  399. }
  400. // the functions IsDoubleQuoteOnLastTkStrCon() and IsHexOrOctOnLastTKNumber() works only with a scanner without lookahead
  401. // Both functions are used to get more info on the last token for specific diffs necessary for JSON parsing.
  402. //Single quotes are not legal in JSON strings. Make distinction between single quote string constant and single quote string
  403. BOOL IsDoubleQuoteOnLastTkStrCon()
  404. {
  405. return m_doubleQuoteOnLastTkStrCon;
  406. }
  407. // True if all chars of last string constant are ascii
  408. BOOL IsEscapeOnLastTkStrCon()
  409. {
  410. return m_EscapeOnLastTkStrCon;
  411. }
  412. bool IsOctOrLeadingZeroOnLastTKNumber()
  413. {
  414. return m_OctOrLeadingZeroOnLastTKNumber;
  415. }
  416. // Returns the character offset of the first token. The character offset is the offset the first character of the token would
  417. // have if the entire file was converted to Unicode (UTF16-LE).
  418. charcount_t IchMinTok(void) const
  419. {
  420. Assert(m_pchMinTok - m_pchBase >= 0);
  421. Assert(m_pchMinTok - m_pchBase <= LONG_MAX);
  422. Assert(static_cast<charcount_t>(m_pchMinTok - m_pchBase) >= m_cMinTokMultiUnits);
  423. return static_cast<charcount_t>(m_pchMinTok - m_pchBase - m_cMinTokMultiUnits);
  424. }
  425. // Returns the character offset of the character immediately following the token. The character offset is the offset the first
  426. // character of the token would have if the entire file was converted to Unicode (UTF16-LE).
  427. charcount_t IchLimTok(void) const
  428. {
  429. Assert(m_currentCharacter - m_pchBase >= 0);
  430. Assert(m_currentCharacter - m_pchBase <= LONG_MAX);
  431. Assert(static_cast<charcount_t>(m_currentCharacter - m_pchBase) >= this->m_cMultiUnits);
  432. return static_cast<charcount_t>(m_currentCharacter - m_pchBase - this->m_cMultiUnits);
  433. }
  434. void SetErrorPosition(charcount_t ichMinError, charcount_t ichLimError)
  435. {
  436. Assert(ichLimError > 0 || ichMinError == 0);
  437. m_ichMinError = ichMinError;
  438. m_ichLimError = ichLimError;
  439. }
  440. charcount_t IchMinError(void) const
  441. {
  442. return m_ichLimError ? m_ichMinError : IchMinTok();
  443. }
  444. charcount_t IchLimError(void) const
  445. {
  446. return m_ichLimError ? m_ichLimError : IchLimTok();
  447. }
  448. // Returns the encoded unit offset of first character of the token. For example, in a UTF-8 encoding this is the offset into
  449. // the UTF-8 buffer. In Unicode this is the same as IchMinTok().
  450. size_t IecpMinTok(void) const
  451. {
  452. return static_cast< size_t >(m_pchMinTok - m_pchBase);
  453. }
  454. // Returns the encoded unit offset of the character immediately following the token. For example, in a UTF-8 encoding this is
  455. // the offset into the UTF-8 buffer. In Unicode this is the same as IchLimTok().
  456. size_t IecpLimTok(void) const
  457. {
  458. return static_cast< size_t >(m_currentCharacter - m_pchBase);
  459. }
  460. size_t IecpLimTokPrevious() const
  461. {
  462. AssertMsg(m_iecpLimTokPrevious != (size_t)-1, "IecpLimTokPrevious() cannot be called before scanning a token");
  463. return m_iecpLimTokPrevious;
  464. }
  465. charcount_t IchLimTokPrevious() const
  466. {
  467. AssertMsg(m_ichLimTokPrevious != (charcount_t)-1, "IchLimTokPrevious() cannot be called before scanning a token");
  468. return m_ichLimTokPrevious;
  469. }
  470. IdentPtr PidAt(size_t iecpMin, size_t iecpLim);
  471. // Returns the character offset within the stream of the first character on the current line.
  472. charcount_t IchMinLine(void) const
  473. {
  474. Assert(m_pchMinLine - m_pchBase >= 0);
  475. Assert(m_pchMinLine - m_pchBase <= LONG_MAX);
  476. Assert(static_cast<charcount_t>(m_pchMinLine - m_pchBase) >= m_cMinLineMultiUnits);
  477. return static_cast<charcount_t>(m_pchMinLine - m_pchBase - m_cMinLineMultiUnits);
  478. }
  479. // Returns the current line number
  480. charcount_t LineCur(void) const { return m_line; }
  481. void SetCurrentCharacter(charcount_t offset, ULONG lineNumber = 0)
  482. {
  483. DebugOnly(m_iecpLimTokPrevious = (size_t)-1);
  484. DebugOnly(m_ichLimTokPrevious = (charcount_t)-1);
  485. size_t length = m_pchLast - m_pchBase;
  486. if (offset > length) offset = static_cast< charcount_t >(length);
  487. size_t ibOffset = this->CharacterOffsetToUnitOffset(m_pchBase, m_currentCharacter, m_pchLast, offset);
  488. m_currentCharacter = m_pchBase + ibOffset;
  489. Assert(ibOffset >= offset);
  490. this->RestoreMultiUnits(ibOffset - offset);
  491. m_line = lineNumber;
  492. }
  493. // IScanner methods
  494. virtual void GetErrorLineInfo(__out int32& ichMin, __out int32& ichLim, __out int32& line, __out int32& ichMinLine)
  495. {
  496. ichMin = this->IchMinError();
  497. ichLim = this->IchLimError();
  498. line = this->LineCur();
  499. ichMinLine = this->IchMinLine();
  500. if (m_ichLimError && m_ichMinError < (charcount_t)ichMinLine)
  501. {
  502. line = m_startLine;
  503. ichMinLine = UpdateLine(line, m_pchStartLine, m_pchLast, 0, ichMin);
  504. }
  505. }
  506. virtual HRESULT SysAllocErrorLine(int32 ichMinLine, __out BSTR* pbstrLine);
  507. class TemporaryBuffer
  508. {
  509. friend Scanner<EncodingPolicy>;
  510. private:
  511. // Keep a reference to the scanner.
  512. // We will use it to signal an error if we fail to allocate the buffer.
  513. Scanner<EncodingPolicy>* m_pscanner;
  514. uint32 m_cchMax;
  515. uint32 m_ichCur;
  516. __field_ecount(m_cchMax) OLECHAR *m_prgch;
  517. byte m_rgbInit[256];
  518. public:
  519. TemporaryBuffer()
  520. {
  521. m_pscanner = nullptr;
  522. m_prgch = (OLECHAR*)m_rgbInit;
  523. m_cchMax = _countof(m_rgbInit) / sizeof(OLECHAR);
  524. m_ichCur = 0;
  525. }
  526. ~TemporaryBuffer()
  527. {
  528. if (m_prgch != (OLECHAR*)m_rgbInit)
  529. {
  530. free(m_prgch);
  531. }
  532. }
  533. void Reset()
  534. {
  535. m_ichCur = 0;
  536. }
  537. void Clear()
  538. {
  539. if (m_prgch != (OLECHAR*)m_rgbInit)
  540. {
  541. free(m_prgch);
  542. m_prgch = (OLECHAR*)m_rgbInit;
  543. m_cchMax = _countof(m_rgbInit) / sizeof(OLECHAR);
  544. }
  545. Reset();
  546. }
  547. void AppendCh(uint ch)
  548. {
  549. return AppendCh<true>(ch);
  550. }
  551. template<bool performAppend> void AppendCh(uint ch)
  552. {
  553. if (performAppend)
  554. {
  555. if (m_ichCur >= m_cchMax)
  556. {
  557. Grow();
  558. }
  559. Assert(m_ichCur < m_cchMax);
  560. __analysis_assume(m_ichCur < m_cchMax);
  561. m_prgch[m_ichCur++] = static_cast<OLECHAR>(ch);
  562. }
  563. }
  564. private:
  565. void Grow()
  566. {
  567. Assert(m_pscanner != nullptr);
  568. byte *prgbNew;
  569. byte *prgbOld = (byte *)m_prgch;
  570. ULONG cbNew;
  571. if (FAILED(ULongMult(m_cchMax, sizeof(OLECHAR) * 2, &cbNew)))
  572. {
  573. m_pscanner->Error(ERRnoMemory);
  574. }
  575. if (prgbOld == m_rgbInit)
  576. {
  577. if (nullptr == (prgbNew = static_cast<byte*>(malloc(cbNew))))
  578. m_pscanner->Error(ERRnoMemory);
  579. js_memcpy_s(prgbNew, cbNew, prgbOld, m_ichCur * sizeof(OLECHAR));
  580. }
  581. else if (nullptr == (prgbNew = static_cast<byte*>(realloc(prgbOld, cbNew))))
  582. {
  583. m_pscanner->Error(ERRnoMemory);
  584. }
  585. m_prgch = (OLECHAR*)prgbNew;
  586. m_cchMax = cbNew / sizeof(OLECHAR);
  587. }
  588. };
  589. tokens GetPrevious() { return m_tkPrevious; }
  590. void Capture(_Out_ RestorePoint* restorePoint);
  591. void SeekTo(const RestorePoint& restorePoint);
  592. void SeekToForcingPid(const RestorePoint& restorePoint);
  593. void Capture(_Out_ RestorePoint* restorePoint, uint functionIdIncrement, size_t lengthDecr);
  594. void SeekTo(const RestorePoint& restorePoint, uint *nextFunctionId);
  595. void Clear();
  596. HashTbl * GetHashTbl() { return &m_htbl; }
  597. private:
  598. Parser *m_parser;
  599. HashTbl m_htbl;
  600. Token *m_ptoken;
  601. EncodedCharPtr m_pchBase; // beginning of source
  602. EncodedCharPtr m_pchLast; // The end of source
  603. EncodedCharPtr m_pchMinLine; // beginning of current line
  604. EncodedCharPtr m_pchMinTok; // beginning of current token
  605. EncodedCharPtr m_currentCharacter; // current character
  606. EncodedCharPtr m_pchPrevLine; // beginning of previous line
  607. size_t m_cMinTokMultiUnits; // number of multi-unit characters previous to m_pchMinTok
  608. size_t m_cMinLineMultiUnits; // number of multi-unit characters previous to m_pchMinLine
  609. uint16 m_fStringTemplateDepth; // we should treat } as string template middle starting character (depth instead of flag)
  610. BOOL m_fHadEol;
  611. BOOL m_fIsModuleCode : 1;
  612. BOOL m_doubleQuoteOnLastTkStrCon :1;
  613. bool m_OctOrLeadingZeroOnLastTKNumber :1;
  614. bool m_EscapeOnLastTkStrCon:1;
  615. BOOL m_fNextStringTemplateIsTagged:1; // the next string template scanned has a tag (must create raw strings)
  616. BYTE m_DeferredParseFlags:2; // suppressStrPid and suppressIdPid
  617. bool es6UnicodeMode; // True if ES6Unicode Extensions are enabled.
  618. bool m_fYieldIsKeywordRegion; // Whether to treat 'yield' as an identifier or keyword
  619. bool m_fAwaitIsKeywordRegion; // Whether to treat 'await' as an identifier or keyword
  620. // Temporary buffer.
  621. TemporaryBuffer m_tempChBuf;
  622. TemporaryBuffer m_tempChBufSecondary;
  623. charcount_t m_line;
  624. ScanState m_scanState;
  625. charcount_t m_ichMinError;
  626. charcount_t m_ichLimError;
  627. charcount_t m_startLine;
  628. EncodedCharPtr m_pchStartLine;
  629. Js::ScriptContext* m_scriptContext;
  630. const Js::CharClassifier *charClassifier;
  631. tokens m_tkPrevious;
  632. size_t m_iecpLimTokPrevious;
  633. charcount_t m_ichLimTokPrevious;
  634. void ClearStates();
  635. template <bool forcePid>
  636. void SeekAndScan(const RestorePoint& restorePoint);
  637. tokens ScanCore(bool identifyKwds);
  638. tokens ScanAhead();
  639. tokens ScanError(EncodedCharPtr pchCur, tokens errorToken)
  640. {
  641. m_currentCharacter = pchCur;
  642. return m_ptoken->tk = tkScanError;
  643. }
  644. __declspec(noreturn) void Error(HRESULT hr)
  645. {
  646. m_pchMinTok = m_currentCharacter;
  647. m_cMinTokMultiUnits = this->m_cMultiUnits;
  648. throw ParseExceptionObject(hr);
  649. }
  650. const EncodedCharPtr PchBase(void) const
  651. {
  652. return m_pchBase;
  653. }
  654. const EncodedCharPtr PchMinTok(void)
  655. {
  656. return m_pchMinTok;
  657. }
  658. template<bool stringTemplateMode, bool createRawString> tokens ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp);
  659. tokens ScanStringConstant(OLECHAR delim, EncodedCharPtr *pp);
  660. tokens ScanStringTemplateBegin(EncodedCharPtr *pp);
  661. tokens ScanStringTemplateMiddleOrEnd(EncodedCharPtr *pp);
  662. void ScanNewLine(uint ch);
  663. void NotifyScannedNewLine();
  664. charcount_t LineLength(EncodedCharPtr first, EncodedCharPtr last);
  665. tokens ScanIdentifier(bool identifyKwds, EncodedCharPtr *pp);
  666. BOOL FastIdentifierContinue(EncodedCharPtr&p, EncodedCharPtr last);
  667. tokens ScanIdentifierContinue(bool identifyKwds, bool fHasEscape, bool fHasMultiChar, EncodedCharPtr pchMin, EncodedCharPtr p, EncodedCharPtr *pp);
  668. tokens SkipComment(EncodedCharPtr *pp, /* out */ bool* containTypeDef);
  669. tokens ScanRegExpConstant(ArenaAllocator* alloc);
  670. tokens ScanRegExpConstantNoAST(ArenaAllocator* alloc);
  671. EncodedCharPtr FScanNumber(EncodedCharPtr p, double *pdbl, bool& likelyInt, size_t savedMultiUnits);
  672. IdentPtr PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last, bool fHadEscape, bool fHasMultiChar);
  673. IdentPtr PidOfIdentiferAt(EncodedCharPtr p, EncodedCharPtr last);
  674. uint32 UnescapeToTempBuf(EncodedCharPtr p, EncodedCharPtr last);
  675. void SaveSrcPos(void)
  676. {
  677. m_pchMinTok = m_currentCharacter;
  678. }
  679. OLECHAR PeekNextChar(void)
  680. {
  681. return this->PeekFull(m_currentCharacter, m_pchLast);
  682. }
  683. OLECHAR ReadNextChar(void)
  684. {
  685. return this->template ReadFull<true>(m_currentCharacter, m_pchLast);
  686. }
  687. EncodedCharPtr AdjustedLast() const
  688. {
  689. return m_pchLast;
  690. }
  691. size_t AdjustedLength() const
  692. {
  693. return AdjustedLast() - m_pchBase;
  694. }
  695. bool IsStrictMode() const
  696. {
  697. return this->m_parser != NULL && this->m_parser->IsStrictMode();
  698. }
  699. // This function expects the first character to be a 'u'
  700. // 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}
  701. bool TryReadEscape(EncodedCharPtr &startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar = nullptr);
  702. template <bool bScan>
  703. bool TryReadCodePointRest(codepoint_t lower, EncodedCharPtr &startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *outContainsMultiUnitChar);
  704. template <bool bScan>
  705. inline bool TryReadCodePoint(EncodedCharPtr &startingLocation, EncodedCharPtr endOfSource, codepoint_t *outChar, bool *hasEscape, bool *outContainsMultiUnitChar);
  706. inline BOOL IsIdContinueNext(EncodedCharPtr startingLocation, EncodedCharPtr endOfSource)
  707. {
  708. codepoint_t nextCodepoint;
  709. bool ignore;
  710. if (TryReadCodePoint<false>(startingLocation, endOfSource, &nextCodepoint, &ignore, &ignore))
  711. {
  712. return charClassifier->IsIdContinue(nextCodepoint);
  713. }
  714. return false;
  715. }
  716. charcount_t UpdateLine(int32 &line, EncodedCharPtr start, EncodedCharPtr last, charcount_t ichStart, charcount_t ichEnd);
  717. };