Scan.h 28 KB

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