Scan.h 27 KB

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