JavascriptParser.cs 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using Jint.Parser.Ast;
  8. namespace Jint.Parser
  9. {
  10. public class JavaScriptParser
  11. {
  12. private static readonly object[] Keywords =
  13. {
  14. "if", "in", "do", "var", "for", "new", "try", "let",
  15. "this", "else", "case", "void", "with", "enum",
  16. "while", "break", "catch", "throw", "const", "yield",
  17. "class", "super", "return", "typeof", "delete",
  18. "switch", "export", "import", "default", "finally", "extends",
  19. "function", "continue", "debugger", "instanceof"
  20. };
  21. private static readonly object[] StrictModeReservedWords =
  22. {
  23. "implements",
  24. "interface",
  25. "package",
  26. "private",
  27. "protected",
  28. "public",
  29. "static",
  30. "yield",
  31. "let"
  32. };
  33. private static readonly object[] FutureReservedWords =
  34. {
  35. "class",
  36. "enum",
  37. "export",
  38. "extends",
  39. "import",
  40. "super"
  41. };
  42. private Extra _extra;
  43. private int _index; // position in the stream
  44. private int _length; // length of the stream
  45. private int _lineNumber;
  46. private int _lineStart;
  47. private Location _location;
  48. private Token _lookahead;
  49. private string _source;
  50. private State _state;
  51. private bool _strict;
  52. private readonly Stack<IVariableScope> _variableScopes = new Stack<IVariableScope>();
  53. private readonly Stack<IFunctionScope> _functionScopes = new Stack<IFunctionScope>();
  54. public JavaScriptParser()
  55. {
  56. }
  57. public JavaScriptParser(bool strict)
  58. {
  59. _strict = strict;
  60. }
  61. private static bool IsDecimalDigit(char ch)
  62. {
  63. return (ch >= '0' && ch <= '9');
  64. }
  65. private static bool IsHexDigit(char ch)
  66. {
  67. return
  68. ch >= '0' && ch <= '9' ||
  69. ch >= 'a' && ch <= 'f' ||
  70. ch >= 'A' && ch <= 'F'
  71. ;
  72. }
  73. private static bool IsOctalDigit(char ch)
  74. {
  75. return ch >= '0' && ch <= '7';
  76. }
  77. // 7.2 White Space
  78. private static bool IsWhiteSpace(char ch)
  79. {
  80. return (ch == 32) || // space
  81. (ch == 9) || // tab
  82. (ch == 0xB) ||
  83. (ch == 0xC) ||
  84. (ch == 0xA0) ||
  85. (ch >= 0x1680 && (
  86. ch == 0x1680 ||
  87. ch == 0x180E ||
  88. (ch >= 0x2000 && ch <= 0x200A) ||
  89. ch == 0x202F ||
  90. ch == 0x205F ||
  91. ch == 0x3000 ||
  92. ch == 0xFEFF));
  93. }
  94. // 7.3 Line Terminators
  95. private static bool IsLineTerminator(char ch)
  96. {
  97. return (ch == 10)
  98. || (ch == 13)
  99. || (ch == 0x2028) // line separator
  100. || (ch == 0x2029) // paragraph separator
  101. ;
  102. }
  103. // 7.6 Identifier Names and Identifiers
  104. private static bool IsIdentifierStart(char ch)
  105. {
  106. return (ch == '$') || (ch == '_') ||
  107. (ch >= 'A' && ch <= 'Z') ||
  108. (ch >= 'a' && ch <= 'z') ||
  109. (ch == '\\') ||
  110. ((ch >= 0x80) && Regexes.NonAsciiIdentifierStart.IsMatch(ch.ToString()));
  111. }
  112. private static bool IsIdentifierPart(char ch)
  113. {
  114. return (ch == '$') || (ch == '_') ||
  115. (ch >= 'A' && ch <= 'Z') ||
  116. (ch >= 'a' && ch <= 'z') ||
  117. (ch >= '0' && ch <= '9') ||
  118. (ch == '\\') ||
  119. ((ch >= 0x80) && Regexes.NonAsciiIdentifierPart.IsMatch(ch.ToString()));
  120. }
  121. // 7.6.1.2 Future Reserved Words
  122. private static bool IsFutureReservedWord(string id)
  123. {
  124. return Array.IndexOf(FutureReservedWords, id) >= 0;
  125. }
  126. private static bool IsStrictModeReservedWord(string id)
  127. {
  128. return Array.IndexOf(StrictModeReservedWords, id) >= 0;
  129. }
  130. private static bool IsRestrictedWord(string id)
  131. {
  132. return "eval".Equals(id) || "arguments".Equals(id);
  133. }
  134. // 7.6.1.1 Keywords
  135. private bool IsKeyword(string id)
  136. {
  137. if (_strict && IsStrictModeReservedWord(id))
  138. {
  139. return true;
  140. }
  141. // 'const' is specialized as Keyword in V8.
  142. // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next.
  143. // Some others are from future reserved words.
  144. return Array.IndexOf(Keywords, id) >= 0;
  145. }
  146. // 7.4 Comments
  147. private void AddComment(string type, string value, int start, int end, Location location)
  148. {
  149. // Because the way the actual token is scanned, often the comments
  150. // (if any) are skipped twice during the lexical analysis.
  151. // Thus, we need to skip adding a comment if the comment array already
  152. // handled it.
  153. if (_state.LastCommentStart >= start)
  154. {
  155. return;
  156. }
  157. _state.LastCommentStart = start;
  158. var comment = new Comment
  159. {
  160. Type = type,
  161. Value = value
  162. };
  163. if (_extra.Range != null)
  164. {
  165. comment.Range = new[] {start, end};
  166. }
  167. if (_extra.Loc.HasValue)
  168. {
  169. comment.Location = location;
  170. }
  171. _extra.Comments.Add(comment);
  172. }
  173. private void SkipSingleLineComment()
  174. {
  175. //var start, loc, ch, comment;
  176. int start = _index - 2;
  177. _location = new Location
  178. {
  179. Start = new Position
  180. {
  181. Line = _lineNumber,
  182. Column = _index - _lineStart - 2
  183. }
  184. };
  185. while (_index < _length)
  186. {
  187. char ch = _source.CharCodeAt(_index);
  188. ++_index;
  189. if (IsLineTerminator(ch))
  190. {
  191. if (_extra.Comments != null)
  192. {
  193. var comment = _source.Slice(start + 2, _index - 1);
  194. _location.End = new Position
  195. {
  196. Line = _lineNumber,
  197. Column = _index - _lineStart - 1
  198. };
  199. AddComment("Line", comment, start, _index - 1, _location);
  200. }
  201. if (ch == 13 && _source.CharCodeAt(_index) == 10)
  202. {
  203. ++_index;
  204. }
  205. ++_lineNumber;
  206. _lineStart = _index;
  207. return;
  208. }
  209. }
  210. if (_extra.Comments != null)
  211. {
  212. var comment = _source.Slice(start + 2, _index);
  213. _location.End = new Position
  214. {
  215. Line = _lineNumber,
  216. Column = _index - _lineStart
  217. };
  218. AddComment("Line", comment, start, _index, _location);
  219. }
  220. }
  221. private void SkipMultiLineComment()
  222. {
  223. //var start, loc, ch, comment;
  224. int start = 0;
  225. if (_extra.Comments != null)
  226. {
  227. start = _index - 2;
  228. _location = new Location
  229. {
  230. Start = new Position
  231. {
  232. Line = _lineNumber,
  233. Column = _index - _lineStart - 2
  234. }
  235. };
  236. }
  237. while (_index < _length)
  238. {
  239. char ch = _source.CharCodeAt(_index);
  240. if (IsLineTerminator(ch))
  241. {
  242. if (ch == 13 && _source.CharCodeAt(_index + 1) == 10)
  243. {
  244. ++_index;
  245. }
  246. ++_lineNumber;
  247. ++_index;
  248. _lineStart = _index;
  249. if (_index >= _length)
  250. {
  251. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  252. }
  253. }
  254. else if (ch == 42)
  255. {
  256. // Block comment ends with '*/' (char #42, char #47).
  257. if (_source.CharCodeAt(_index + 1) == 47)
  258. {
  259. ++_index;
  260. ++_index;
  261. if (_extra.Comments != null)
  262. {
  263. string comment = _source.Slice(start + 2, _index - 2);
  264. _location.End = new Position
  265. {
  266. Line = _lineNumber,
  267. Column = _index - _lineStart
  268. };
  269. AddComment("Block", comment, start, _index, _location);
  270. }
  271. return;
  272. }
  273. ++_index;
  274. }
  275. else
  276. {
  277. ++_index;
  278. }
  279. }
  280. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  281. }
  282. private void SkipComment()
  283. {
  284. while (_index < _length)
  285. {
  286. char ch = _source.CharCodeAt(_index);
  287. if (IsWhiteSpace(ch))
  288. {
  289. ++_index;
  290. }
  291. else if (IsLineTerminator(ch))
  292. {
  293. ++_index;
  294. if (ch == 13 && _source.CharCodeAt(_index) == 10)
  295. {
  296. ++_index;
  297. }
  298. ++_lineNumber;
  299. _lineStart = _index;
  300. }
  301. else if (ch == 47)
  302. {
  303. // 47 is '/'
  304. ch = _source.CharCodeAt(_index + 1);
  305. if (ch == 47)
  306. {
  307. ++_index;
  308. ++_index;
  309. SkipSingleLineComment();
  310. }
  311. else if (ch == 42)
  312. {
  313. // 42 is '*'
  314. ++_index;
  315. ++_index;
  316. SkipMultiLineComment();
  317. }
  318. else
  319. {
  320. break;
  321. }
  322. }
  323. else
  324. {
  325. break;
  326. }
  327. }
  328. }
  329. private bool ScanHexEscape(char prefix, out char result)
  330. {
  331. int code = char.MinValue;
  332. int len = (prefix == 'u') ? 4 : 2;
  333. for (int i = 0; i < len; ++i)
  334. {
  335. if (_index < _length && IsHexDigit(_source.CharCodeAt(_index)))
  336. {
  337. char ch = _source.CharCodeAt(_index++);
  338. code = code*16 +
  339. "0123456789abcdef".IndexOf(ch.ToString(),
  340. StringComparison.OrdinalIgnoreCase);
  341. }
  342. else
  343. {
  344. result = char.MinValue;
  345. return false;
  346. }
  347. }
  348. result = (char) code;
  349. return true;
  350. }
  351. private string GetEscapedIdentifier()
  352. {
  353. char ch = _source.CharCodeAt(_index++);
  354. var id = new StringBuilder(ch.ToString());
  355. // '\u' (char #92, char #117) denotes an escaped character.
  356. if (ch == 92)
  357. {
  358. if (_source.CharCodeAt(_index) != 117)
  359. {
  360. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  361. }
  362. ++_index;
  363. if (!ScanHexEscape('u', out ch) || ch == '\\' || !IsIdentifierStart(ch))
  364. {
  365. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  366. }
  367. id = new StringBuilder(ch.ToString());
  368. }
  369. while (_index < _length)
  370. {
  371. ch = _source.CharCodeAt(_index);
  372. if (!IsIdentifierPart(ch))
  373. {
  374. break;
  375. }
  376. ++_index;
  377. // '\u' (char #92, char #117) denotes an escaped character.
  378. if (ch == 92)
  379. {
  380. if (_source.CharCodeAt(_index) != 117)
  381. {
  382. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  383. }
  384. ++_index;
  385. if (!ScanHexEscape('u', out ch) || ch == '\\' || !IsIdentifierPart(ch))
  386. {
  387. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  388. }
  389. id.Append(ch);
  390. }
  391. else
  392. {
  393. id.Append(ch);
  394. }
  395. }
  396. return id.ToString();
  397. }
  398. private string GetIdentifier()
  399. {
  400. int start = _index++;
  401. while (_index < _length)
  402. {
  403. char ch = _source.CharCodeAt(_index);
  404. if (ch == 92)
  405. {
  406. // Blackslash (char #92) marks Unicode escape sequence.
  407. _index = start;
  408. return GetEscapedIdentifier();
  409. }
  410. if (IsIdentifierPart(ch))
  411. {
  412. ++_index;
  413. }
  414. else
  415. {
  416. break;
  417. }
  418. }
  419. return _source.Slice(start, _index);
  420. }
  421. private Token ScanIdentifier()
  422. {
  423. int start = _index;
  424. Tokens type;
  425. // Backslash (char #92) starts an escaped character.
  426. string id = (_source.CharCodeAt(_index) == 92) ? GetEscapedIdentifier() : GetIdentifier();
  427. // There is no keyword or literal with only one character.
  428. // Thus, it must be an identifier.
  429. if (id.Length == 1)
  430. {
  431. type = Tokens.Identifier;
  432. }
  433. else if (IsKeyword(id))
  434. {
  435. type = Tokens.Keyword;
  436. }
  437. else if ("null".Equals(id))
  438. {
  439. type = Tokens.NullLiteral;
  440. }
  441. else if ("true".Equals(id) || "false".Equals(id))
  442. {
  443. type = Tokens.BooleanLiteral;
  444. }
  445. else
  446. {
  447. type = Tokens.Identifier;
  448. }
  449. return new Token
  450. {
  451. Type = type,
  452. Value = id,
  453. LineNumber = _lineNumber,
  454. LineStart = _lineStart,
  455. Range = new[] {start, _index}
  456. };
  457. }
  458. // 7.7 Punctuators
  459. private Token ScanPunctuator()
  460. {
  461. int start = _index;
  462. char code = _source.CharCodeAt(_index);
  463. char ch1 = _source.CharCodeAt(_index);
  464. switch ((int) code)
  465. {
  466. // Check for most common single-character punctuators.
  467. case 46: // . dot
  468. case 40: // ( open bracket
  469. case 41: // ) close bracket
  470. case 59: // ; semicolon
  471. case 44: // , comma
  472. case 123: // { open curly brace
  473. case 125: // } close curly brace
  474. case 91: // [
  475. case 93: // ]
  476. case 58: // :
  477. case 63: // ?
  478. case 126: // ~
  479. ++_index;
  480. return new Token
  481. {
  482. Type = Tokens.Punctuator,
  483. Value = code.ToString(),
  484. LineNumber = _lineNumber,
  485. LineStart = _lineStart,
  486. Range = new[] {start, _index}
  487. };
  488. default:
  489. char code2 = _source.CharCodeAt(_index + 1);
  490. // '=' (char #61) marks an assignment or comparison operator.
  491. if (code2 == 61)
  492. {
  493. switch ((int) code)
  494. {
  495. case 37: // %
  496. case 38: // &
  497. case 42: // *:
  498. case 43: // +
  499. case 45: // -
  500. case 47: // /
  501. case 60: // <
  502. case 62: // >
  503. case 94: // ^
  504. case 124: // |
  505. _index += 2;
  506. return new Token
  507. {
  508. Type = Tokens.Punctuator,
  509. Value =
  510. code.ToString() +
  511. code2.ToString(),
  512. LineNumber = _lineNumber,
  513. LineStart = _lineStart,
  514. Range = new[] {start, _index}
  515. };
  516. case 33: // !
  517. case 61: // =
  518. _index += 2;
  519. // !== and ===
  520. if (_source.CharCodeAt(_index) == 61)
  521. {
  522. ++_index;
  523. }
  524. return new Token
  525. {
  526. Type = Tokens.Punctuator,
  527. Value = _source.Slice(start, _index),
  528. LineNumber = _lineNumber,
  529. LineStart = _lineStart,
  530. Range = new[] {start, _index}
  531. };
  532. }
  533. }
  534. break;
  535. }
  536. // Peek more characters.
  537. char ch2 = _source.CharCodeAt(_index + 1);
  538. char ch3 = _source.CharCodeAt(_index + 2);
  539. char ch4 = _source.CharCodeAt(_index + 3);
  540. // 4-character punctuator: >>>=
  541. if (ch1 == '>' && ch2 == '>' && ch3 == '>')
  542. {
  543. if (ch4 == '=')
  544. {
  545. _index += 4;
  546. return new Token
  547. {
  548. Type = Tokens.Punctuator,
  549. Value = ">>>=",
  550. LineNumber = _lineNumber,
  551. LineStart = _lineStart,
  552. Range = new[] {start, _index}
  553. };
  554. }
  555. }
  556. // 3-character punctuators: == !== >>> <<= >>=
  557. if (ch1 == '>' && ch2 == '>' && ch3 == '>')
  558. {
  559. _index += 3;
  560. return new Token
  561. {
  562. Type = Tokens.Punctuator,
  563. Value = ">>>",
  564. LineNumber = _lineNumber,
  565. LineStart = _lineStart,
  566. Range = new[] {start, _index}
  567. };
  568. }
  569. if (ch1 == '<' && ch2 == '<' && ch3 == '=')
  570. {
  571. _index += 3;
  572. return new Token
  573. {
  574. Type = Tokens.Punctuator,
  575. Value = "<<=",
  576. LineNumber = _lineNumber,
  577. LineStart = _lineStart,
  578. Range = new[] {start, _index}
  579. };
  580. }
  581. if (ch1 == '>' && ch2 == '>' && ch3 == '=')
  582. {
  583. _index += 3;
  584. return new Token
  585. {
  586. Type = Tokens.Punctuator,
  587. Value = ">>=",
  588. LineNumber = _lineNumber,
  589. LineStart = _lineStart,
  590. Range = new[] {start, _index}
  591. };
  592. }
  593. // Other 2-character punctuators: ++ -- << >> && ||
  594. if (ch1 == ch2 && ("+-<>&|".IndexOf(ch1) >= 0))
  595. {
  596. _index += 2;
  597. return new Token
  598. {
  599. Type = Tokens.Punctuator,
  600. Value = ch1.ToString() + ch2.ToString(),
  601. LineNumber = _lineNumber,
  602. LineStart = _lineStart,
  603. Range = new[] {start, _index}
  604. };
  605. }
  606. if ("<>=!+-*%&|^/".IndexOf(ch1) >= 0)
  607. {
  608. ++_index;
  609. return new Token
  610. {
  611. Type = Tokens.Punctuator,
  612. Value = ch1.ToString(),
  613. LineNumber = _lineNumber,
  614. LineStart = _lineStart,
  615. Range = new[] {start, _index}
  616. };
  617. }
  618. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  619. return null;
  620. }
  621. // 7.8.3 Numeric Literals
  622. private Token ScanHexLiteral(int start)
  623. {
  624. string number = "";
  625. while (_index < _length)
  626. {
  627. if (!IsHexDigit(_source.CharCodeAt(_index)))
  628. {
  629. break;
  630. }
  631. number += _source.CharCodeAt(_index++).ToString();
  632. }
  633. if (number.Length == 0)
  634. {
  635. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  636. }
  637. if (IsIdentifierStart(_source.CharCodeAt(_index)))
  638. {
  639. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  640. }
  641. return new Token
  642. {
  643. Type = Tokens.NumericLiteral,
  644. Value = Convert.ToInt32(number, 16),
  645. LineNumber = _lineNumber,
  646. LineStart = _lineStart,
  647. Range = new[] {start, _index}
  648. };
  649. }
  650. private Token ScanOctalLiteral(int start)
  651. {
  652. string number = "0" + _source.CharCodeAt(_index++);
  653. while (_index < _length)
  654. {
  655. if (!IsOctalDigit(_source.CharCodeAt(_index)))
  656. {
  657. break;
  658. }
  659. number += _source.CharCodeAt(_index++).ToString();
  660. }
  661. if (IsIdentifierStart(_source.CharCodeAt(_index)) || IsDecimalDigit(_source.CharCodeAt(_index)))
  662. {
  663. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  664. }
  665. return new Token
  666. {
  667. Type = Tokens.NumericLiteral,
  668. Value = Convert.ToInt32(number, 8),
  669. Octal = true,
  670. LineNumber = _lineNumber,
  671. LineStart = _lineStart,
  672. Range = new[] {start, _index}
  673. };
  674. }
  675. private Token ScanNumericLiteral()
  676. {
  677. char ch = _source.CharCodeAt(_index);
  678. int start = _index;
  679. string number = "";
  680. if (ch != '.')
  681. {
  682. number = _source.CharCodeAt(_index++).ToString();
  683. ch = _source.CharCodeAt(_index);
  684. // Hex number starts with '0x'.
  685. // Octal number starts with '0'.
  686. if (number == "0")
  687. {
  688. if (ch == 'x' || ch == 'X')
  689. {
  690. ++_index;
  691. return ScanHexLiteral(start);
  692. }
  693. if (IsOctalDigit(ch))
  694. {
  695. return ScanOctalLiteral(start);
  696. }
  697. // decimal number starts with '0' such as '09' is illegal.
  698. if (ch > 0 && IsDecimalDigit(ch))
  699. {
  700. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  701. }
  702. }
  703. while (IsDecimalDigit(_source.CharCodeAt(_index)))
  704. {
  705. number += _source.CharCodeAt(_index++).ToString();
  706. }
  707. ch = _source.CharCodeAt(_index);
  708. }
  709. if (ch == '.')
  710. {
  711. number += _source.CharCodeAt(_index++).ToString();
  712. while (IsDecimalDigit(_source.CharCodeAt(_index)))
  713. {
  714. number += _source.CharCodeAt(_index++).ToString();
  715. }
  716. ch = _source.CharCodeAt(_index);
  717. }
  718. if (ch == 'e' || ch == 'E')
  719. {
  720. number += _source.CharCodeAt(_index++).ToString();
  721. ch = _source.CharCodeAt(_index);
  722. if (ch == '+' || ch == '-')
  723. {
  724. number += _source.CharCodeAt(_index++).ToString();
  725. }
  726. if (IsDecimalDigit(_source.CharCodeAt(_index)))
  727. {
  728. while (IsDecimalDigit(_source.CharCodeAt(_index)))
  729. {
  730. number += _source.CharCodeAt(_index++).ToString();
  731. }
  732. }
  733. else
  734. {
  735. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  736. }
  737. }
  738. if (IsIdentifierStart(_source.CharCodeAt(_index)))
  739. {
  740. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  741. }
  742. double n;
  743. try
  744. {
  745. n = Double.Parse(number, NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent);
  746. if (n > double.MaxValue)
  747. {
  748. n = double.PositiveInfinity;
  749. }
  750. else if (n < -double.MaxValue)
  751. {
  752. n = double.NegativeInfinity;
  753. }
  754. }
  755. catch (OverflowException)
  756. {
  757. n = number.Trim().StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity;
  758. }
  759. catch (Exception)
  760. {
  761. n = double.NaN;
  762. }
  763. return new Token
  764. {
  765. Type = Tokens.NumericLiteral,
  766. Value = n,
  767. LineNumber = _lineNumber,
  768. LineStart = _lineStart,
  769. Range = new[] {start, _index}
  770. };
  771. }
  772. // 7.8.4 String Literals
  773. private Token ScanStringLiteral()
  774. {
  775. var str = new StringBuilder();
  776. bool octal = false;
  777. char quote = _source.CharCodeAt(_index);
  778. int start = _index;
  779. ++_index;
  780. while (_index < _length)
  781. {
  782. char ch = _source.CharCodeAt(_index++);
  783. if (ch == quote)
  784. {
  785. quote = char.MinValue;
  786. break;
  787. }
  788. if (ch == '\\')
  789. {
  790. ch = _source.CharCodeAt(_index++);
  791. if (ch == char.MinValue || !IsLineTerminator(ch))
  792. {
  793. switch (ch)
  794. {
  795. case 'n':
  796. str.Append('\n');
  797. break;
  798. case 'r':
  799. str.Append('\r');
  800. break;
  801. case 't':
  802. str.Append('\t');
  803. break;
  804. case 'u':
  805. case 'x':
  806. int restore = _index;
  807. char unescaped;
  808. if(ScanHexEscape(ch, out unescaped))
  809. {
  810. str.Append(unescaped);
  811. }
  812. else
  813. {
  814. _index = restore;
  815. str.Append(ch);
  816. }
  817. break;
  818. case 'b':
  819. str.Append("\b");
  820. break;
  821. case 'f':
  822. str.Append("\f");
  823. break;
  824. case 'v':
  825. str.Append("\x0B");
  826. break;
  827. default:
  828. if (IsOctalDigit(ch))
  829. {
  830. int code = "01234567".IndexOf(ch);
  831. // \0 is not octal escape sequence
  832. if (code != 0)
  833. {
  834. octal = true;
  835. }
  836. if (_index < _length && IsOctalDigit(_source.CharCodeAt(_index)))
  837. {
  838. octal = true;
  839. code = code * 8 + "01234567".IndexOf(_source.CharCodeAt(_index++));
  840. // 3 digits are only allowed when string starts
  841. // with 0, 1, 2, 3
  842. if ("0123".IndexOf(ch) >= 0 &&
  843. _index < _length &&
  844. IsOctalDigit(_source.CharCodeAt(_index)))
  845. {
  846. code = code * 8 + "01234567".IndexOf(_source.CharCodeAt(_index++));
  847. }
  848. }
  849. str.Append((char)code);
  850. }
  851. else
  852. {
  853. str.Append(ch);
  854. }
  855. break;
  856. }
  857. }
  858. else
  859. {
  860. ++_lineNumber;
  861. if (ch == '\r' && _source.CharCodeAt(_index) == '\n')
  862. {
  863. ++_index;
  864. }
  865. }
  866. }
  867. else if (IsLineTerminator(ch))
  868. {
  869. break;
  870. }
  871. else
  872. {
  873. str.Append(ch);
  874. }
  875. }
  876. if (quote != 0)
  877. {
  878. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  879. }
  880. return new Token
  881. {
  882. Type = Tokens.StringLiteral,
  883. Value = str.ToString(),
  884. Octal = octal,
  885. LineNumber = _lineNumber,
  886. LineStart = _lineStart,
  887. Range = new[] {start, _index}
  888. };
  889. }
  890. private Token ScanRegExp()
  891. {
  892. bool classMarker = false;
  893. bool terminated = false;
  894. SkipComment();
  895. int start = _index;
  896. char ch;
  897. var str = new StringBuilder(_source.CharCodeAt(_index++).ToString());
  898. while (_index < _length)
  899. {
  900. ch = _source.CharCodeAt(_index++);
  901. str.Append(ch);
  902. if (ch == '\\')
  903. {
  904. ch = _source.CharCodeAt(_index++);
  905. // ECMA-262 7.8.5
  906. if (IsLineTerminator(ch))
  907. {
  908. ThrowError(null, Messages.UnterminatedRegExp);
  909. }
  910. str.Append(ch);
  911. }
  912. else if (IsLineTerminator(ch))
  913. {
  914. ThrowError(null, Messages.UnterminatedRegExp);
  915. }
  916. else if (classMarker)
  917. {
  918. if (ch == ']')
  919. {
  920. classMarker = false;
  921. }
  922. }
  923. else
  924. {
  925. if (ch == '/')
  926. {
  927. terminated = true;
  928. break;
  929. }
  930. if (ch == '[')
  931. {
  932. classMarker = true;
  933. }
  934. }
  935. }
  936. if (!terminated)
  937. {
  938. ThrowError(null, Messages.UnterminatedRegExp);
  939. }
  940. // Exclude leading and trailing slash.
  941. string pattern = str.ToString().Substring(1, str.Length - 2);
  942. string flags = "";
  943. while (_index < _length)
  944. {
  945. ch = _source.CharCodeAt(_index);
  946. if (!IsIdentifierPart(ch))
  947. {
  948. break;
  949. }
  950. ++_index;
  951. if (ch == '\\' && _index < _length)
  952. {
  953. ch = _source.CharCodeAt(_index);
  954. if (ch == 'u')
  955. {
  956. ++_index;
  957. int restore = _index;
  958. if(ScanHexEscape('u', out ch))
  959. {
  960. flags += ch.ToString();
  961. for (str.Append("\\u"); restore < _index; ++restore)
  962. {
  963. str.Append(_source.CharCodeAt(restore).ToString());
  964. }
  965. }
  966. else
  967. {
  968. _index = restore;
  969. flags += "u";
  970. str.Append("\\u");
  971. }
  972. }
  973. else
  974. {
  975. str.Append("\\");
  976. }
  977. }
  978. else
  979. {
  980. flags += ch.ToString();
  981. str.Append(ch.ToString());
  982. }
  983. }
  984. Peek();
  985. return new Token
  986. {
  987. Type = Tokens.RegularExpression,
  988. Literal = str.ToString(),
  989. Value = pattern + flags,
  990. Range = new[] {start, _index}
  991. };
  992. }
  993. private Token CollectRegex()
  994. {
  995. SkipComment();
  996. int pos = _index;
  997. var loc = new Location
  998. {
  999. Start = new Position
  1000. {
  1001. Line = _lineNumber,
  1002. Column = _index - _lineStart
  1003. }
  1004. };
  1005. Token regex = ScanRegExp();
  1006. loc.End = new Position
  1007. {
  1008. Line = _lineNumber,
  1009. Column = _index - _lineStart
  1010. };
  1011. // Pop the previous token, which is likely '/' or '/='
  1012. if (_extra.Tokens != null)
  1013. {
  1014. Token token = _extra.Tokens[_extra.Tokens.Count - 1];
  1015. if (token.Range[0] == pos && token.Type == Tokens.Punctuator)
  1016. {
  1017. if ("/".Equals(token.Value) || "/=".Equals(token.Value))
  1018. {
  1019. _extra.Tokens.RemoveAt(_extra.Tokens.Count - 1);
  1020. }
  1021. }
  1022. _extra.Tokens.Add(new Token
  1023. {
  1024. Type = Tokens.RegularExpression,
  1025. Value = regex.Literal,
  1026. Range = new[] { pos, _index },
  1027. Location = loc
  1028. });
  1029. }
  1030. return regex;
  1031. }
  1032. private bool IsIdentifierName(Token token)
  1033. {
  1034. return token.Type == Tokens.Identifier ||
  1035. token.Type == Tokens.Keyword ||
  1036. token.Type == Tokens.BooleanLiteral ||
  1037. token.Type == Tokens.NullLiteral;
  1038. }
  1039. private Token Advance()
  1040. {
  1041. SkipComment();
  1042. if (_index >= _length)
  1043. {
  1044. return new Token
  1045. {
  1046. Type = Tokens.EOF,
  1047. LineNumber = _lineNumber,
  1048. LineStart = _lineStart,
  1049. Range = new[] {_index, _index}
  1050. };
  1051. }
  1052. char ch = _source.CharCodeAt(_index);
  1053. // Very common: ( and ) and ;
  1054. if (ch == 40 || ch == 41 || ch == 58)
  1055. {
  1056. return ScanPunctuator();
  1057. }
  1058. // String literal starts with single quote (#39) or double quote (#34).
  1059. if (ch == 39 || ch == 34)
  1060. {
  1061. return ScanStringLiteral();
  1062. }
  1063. if (IsIdentifierStart(ch))
  1064. {
  1065. return ScanIdentifier();
  1066. }
  1067. // Dot (.) char #46 can also start a floating-point number, hence the need
  1068. // to check the next character.
  1069. if (ch == 46)
  1070. {
  1071. if (IsDecimalDigit(_source.CharCodeAt(_index + 1)))
  1072. {
  1073. return ScanNumericLiteral();
  1074. }
  1075. return ScanPunctuator();
  1076. }
  1077. if (IsDecimalDigit(ch))
  1078. {
  1079. return ScanNumericLiteral();
  1080. }
  1081. return ScanPunctuator();
  1082. }
  1083. private Token CollectToken()
  1084. {
  1085. SkipComment();
  1086. _location = new Location
  1087. {
  1088. Start = new Position
  1089. {
  1090. Line = _lineNumber,
  1091. Column = _index - _lineStart
  1092. }
  1093. };
  1094. Token token = Advance();
  1095. _location.End = new Position
  1096. {
  1097. Line = _lineNumber,
  1098. Column = _index - _lineStart
  1099. };
  1100. if (token.Type != Tokens.EOF)
  1101. {
  1102. var range = new[] {token.Range[0], token.Range[1]};
  1103. string value = _source.Slice(token.Range[0], token.Range[1]);
  1104. _extra.Tokens.Add(new Token
  1105. {
  1106. Type = token.Type,
  1107. Value = value,
  1108. Range = range,
  1109. Location = _location
  1110. });
  1111. }
  1112. return token;
  1113. }
  1114. private Token Lex()
  1115. {
  1116. Token token = _lookahead;
  1117. _index = token.Range[1];
  1118. _lineNumber = token.LineNumber.HasValue ? token.LineNumber.Value : 0;
  1119. _lineStart = token.LineStart;
  1120. _lookahead = (_extra.Tokens != null) ? CollectToken() : Advance();
  1121. _index = token.Range[1];
  1122. _lineNumber = token.LineNumber.HasValue ? token.LineNumber.Value : 0;
  1123. _lineStart = token.LineStart;
  1124. return token;
  1125. }
  1126. private void Peek()
  1127. {
  1128. int pos = _index;
  1129. int line = _lineNumber;
  1130. int start = _lineStart;
  1131. _lookahead = (_extra.Tokens != null) ? CollectToken() : Advance();
  1132. _index = pos;
  1133. _lineNumber = line;
  1134. _lineStart = start;
  1135. }
  1136. private void MarkStart()
  1137. {
  1138. if (_extra.Loc.HasValue)
  1139. {
  1140. _state.MarkerStack.Push(_index - _lineStart);
  1141. _state.MarkerStack.Push(_lineNumber);
  1142. }
  1143. if (_extra.Range != null)
  1144. {
  1145. _state.MarkerStack.Push(_index);
  1146. }
  1147. }
  1148. private T MarkEnd<T>(T node) where T : SyntaxNode
  1149. {
  1150. if (_extra.Range != null)
  1151. {
  1152. node.Range = new[] {_state.MarkerStack.Pop(), _index};
  1153. }
  1154. if (_extra.Loc.HasValue)
  1155. {
  1156. node.Location = new Location
  1157. {
  1158. Start = new Position
  1159. {
  1160. Line = _state.MarkerStack.Pop(),
  1161. Column = _state.MarkerStack.Pop()
  1162. },
  1163. End = new Position
  1164. {
  1165. Line = _lineNumber,
  1166. Column = _index - _lineStart
  1167. }
  1168. };
  1169. PostProcess(node);
  1170. }
  1171. return node;
  1172. }
  1173. public T MarkEndIf<T>(T node) where T : SyntaxNode
  1174. {
  1175. if (node.Range != null || node.Location != null)
  1176. {
  1177. if (_extra.Loc.HasValue)
  1178. {
  1179. _state.MarkerStack.Pop();
  1180. _state.MarkerStack.Pop();
  1181. }
  1182. if (_extra.Range != null)
  1183. {
  1184. _state.MarkerStack.Pop();
  1185. }
  1186. }
  1187. else
  1188. {
  1189. MarkEnd(node);
  1190. }
  1191. return node;
  1192. }
  1193. public SyntaxNode PostProcess(SyntaxNode node)
  1194. {
  1195. if (_extra.Source != null)
  1196. {
  1197. node.Location.Source = _extra.Source;
  1198. }
  1199. return node;
  1200. }
  1201. public ArrayExpression CreateArrayExpression(IEnumerable<Expression> elements)
  1202. {
  1203. return new ArrayExpression
  1204. {
  1205. Type = SyntaxNodes.ArrayExpression,
  1206. Elements = elements
  1207. };
  1208. }
  1209. public AssignmentExpression CreateAssignmentExpression(string op, Expression left, Expression right)
  1210. {
  1211. return new AssignmentExpression
  1212. {
  1213. Type = SyntaxNodes.AssignmentExpression,
  1214. Operator = op,
  1215. Left = left,
  1216. Right = right
  1217. };
  1218. }
  1219. public BinaryExpression CreateBinaryExpression(string op, Expression left, Expression right)
  1220. {
  1221. return (op == "||" || op == "&&")
  1222. ? new LogicalExpression
  1223. {
  1224. Type = SyntaxNodes.LogicalExpression,
  1225. Operator = op,
  1226. Left = left,
  1227. Right = right
  1228. }
  1229. : new BinaryExpression
  1230. {
  1231. Type = SyntaxNodes.BinaryExpression,
  1232. Operator = op,
  1233. Left = left,
  1234. Right = right
  1235. };
  1236. }
  1237. public BlockStatement CreateBlockStatement(IEnumerable<Statement> body)
  1238. {
  1239. return new BlockStatement
  1240. {
  1241. Type = SyntaxNodes.BlockStatement,
  1242. Body = body
  1243. };
  1244. }
  1245. public BreakStatement CreateBreakStatement(Identifier label)
  1246. {
  1247. return new BreakStatement
  1248. {
  1249. Type = SyntaxNodes.BreakStatement,
  1250. Label = label
  1251. };
  1252. }
  1253. public CallExpression CreateCallExpression(Expression callee, IEnumerable<Expression> args)
  1254. {
  1255. return new CallExpression
  1256. {
  1257. Type = SyntaxNodes.CallExpression,
  1258. Callee = callee,
  1259. Arguments = args
  1260. };
  1261. }
  1262. public CatchClause CreateCatchClause(Identifier param, BlockStatement body)
  1263. {
  1264. return new CatchClause
  1265. {
  1266. Type = SyntaxNodes.CatchClause,
  1267. Param = param,
  1268. Body = body
  1269. };
  1270. }
  1271. public ConditionalExpression CreateConditionalExpression(Expression test, Expression consequent,
  1272. Expression alternate)
  1273. {
  1274. return new ConditionalExpression
  1275. {
  1276. Type = SyntaxNodes.ConditionalExpression,
  1277. Test = test,
  1278. Consequent = consequent,
  1279. Alternate = alternate
  1280. };
  1281. }
  1282. public ContinueStatement CreateContinueStatement(Identifier label)
  1283. {
  1284. return new ContinueStatement
  1285. {
  1286. Type = SyntaxNodes.ContinueStatement,
  1287. Label = label
  1288. };
  1289. }
  1290. public DebuggerStatement CreateDebuggerStatement()
  1291. {
  1292. return new DebuggerStatement
  1293. {
  1294. Type = SyntaxNodes.DebuggerStatement
  1295. };
  1296. }
  1297. public DoWhileStatement CreateDoWhileStatement(Statement body, Expression test)
  1298. {
  1299. return new DoWhileStatement
  1300. {
  1301. Type = SyntaxNodes.DoWhileStatement,
  1302. Body = body,
  1303. Test = test
  1304. };
  1305. }
  1306. public EmptyStatement CreateEmptyStatement()
  1307. {
  1308. return new EmptyStatement
  1309. {
  1310. Type = SyntaxNodes.EmptyStatement
  1311. };
  1312. }
  1313. public ExpressionStatement CreateExpressionStatement(Expression expression)
  1314. {
  1315. return new ExpressionStatement
  1316. {
  1317. Type = SyntaxNodes.ExpressionStatement,
  1318. Expression = expression
  1319. };
  1320. }
  1321. public ForStatement CreateForStatement(SyntaxNode init, Expression test, Expression update, Statement body)
  1322. {
  1323. return new ForStatement
  1324. {
  1325. Type = SyntaxNodes.ForStatement,
  1326. Init = init,
  1327. Test = test,
  1328. Update = update,
  1329. Body = body
  1330. };
  1331. }
  1332. public ForInStatement CreateForInStatement(SyntaxNode left, Expression right, Statement body)
  1333. {
  1334. return new ForInStatement
  1335. {
  1336. Type = SyntaxNodes.ForInStatement,
  1337. Left = left,
  1338. Right = right,
  1339. Body = body,
  1340. Each = false
  1341. };
  1342. }
  1343. public FunctionDeclaration CreateFunctionDeclaration(Identifier id, IEnumerable<Identifier> parameters,
  1344. IEnumerable<Expression> defaults, Statement body, bool strict)
  1345. {
  1346. var functionDeclaration = new FunctionDeclaration
  1347. {
  1348. Type = SyntaxNodes.FunctionDeclaration,
  1349. Id = id,
  1350. Parameters = parameters,
  1351. Defaults = defaults,
  1352. Body = body,
  1353. Strict = strict,
  1354. Rest = null,
  1355. Generator = false,
  1356. Expression = false,
  1357. VariableDeclarations = LeaveVariableScope(),
  1358. FunctionDeclarations = LeaveFunctionScope()
  1359. };
  1360. _functionScopes.Peek().FunctionDeclarations.Add(functionDeclaration);
  1361. return functionDeclaration;
  1362. }
  1363. public FunctionExpression CreateFunctionExpression(Identifier id, IEnumerable<Identifier> parameters,
  1364. IEnumerable<Expression> defaults, Statement body, bool strict)
  1365. {
  1366. return new FunctionExpression
  1367. {
  1368. Type = SyntaxNodes.FunctionExpression,
  1369. Id = id,
  1370. Parameters = parameters,
  1371. Defaults = defaults,
  1372. Body = body,
  1373. Strict = strict,
  1374. Rest = null,
  1375. Generator = false,
  1376. Expression = false,
  1377. VariableDeclarations = LeaveVariableScope(),
  1378. FunctionDeclarations = LeaveFunctionScope()
  1379. };
  1380. }
  1381. public Identifier CreateIdentifier(string name)
  1382. {
  1383. return new Identifier
  1384. {
  1385. Type = SyntaxNodes.Identifier,
  1386. Name = name
  1387. };
  1388. }
  1389. public IfStatement CreateIfStatement(Expression test, Statement consequent, Statement alternate)
  1390. {
  1391. return new IfStatement
  1392. {
  1393. Type = SyntaxNodes.IfStatement,
  1394. Test = test,
  1395. Consequent = consequent,
  1396. Alternate = alternate
  1397. };
  1398. }
  1399. public LabelledStatement CreateLabeledStatement(Identifier label, Statement body)
  1400. {
  1401. return new LabelledStatement
  1402. {
  1403. Type = SyntaxNodes.LabeledStatement,
  1404. Label = label,
  1405. Body = body
  1406. };
  1407. }
  1408. public Literal CreateLiteral(Token token)
  1409. {
  1410. if (token.Type == Tokens.RegularExpression)
  1411. {
  1412. return new Literal
  1413. {
  1414. Type = SyntaxNodes.RegularExpressionLiteral,
  1415. Value = token.Value,
  1416. Raw = _source.Slice(token.Range[0], token.Range[1])
  1417. };
  1418. }
  1419. return new Literal
  1420. {
  1421. Type = SyntaxNodes.Literal,
  1422. Value = token.Value,
  1423. Raw = _source.Slice(token.Range[0], token.Range[1])
  1424. };
  1425. }
  1426. public MemberExpression CreateMemberExpression(char accessor, Expression obj, Expression property)
  1427. {
  1428. return new MemberExpression
  1429. {
  1430. Type = SyntaxNodes.MemberExpression,
  1431. Computed = accessor == '[',
  1432. Object = obj,
  1433. Property = property
  1434. };
  1435. }
  1436. public NewExpression CreateNewExpression(Expression callee, IEnumerable<Expression> args)
  1437. {
  1438. return new NewExpression
  1439. {
  1440. Type = SyntaxNodes.NewExpression,
  1441. Callee = callee,
  1442. Arguments = args
  1443. };
  1444. }
  1445. public ObjectExpression CreateObjectExpression(IEnumerable<Property> properties)
  1446. {
  1447. return new ObjectExpression
  1448. {
  1449. Type = SyntaxNodes.ObjectExpression,
  1450. Properties = properties
  1451. };
  1452. }
  1453. public UpdateExpression CreatePostfixExpression(string op, Expression argument)
  1454. {
  1455. return new UpdateExpression
  1456. {
  1457. Type = SyntaxNodes.UpdateExpression,
  1458. Operator = op,
  1459. Argument = argument,
  1460. Prefix = false
  1461. };
  1462. }
  1463. public Program CreateProgram(ICollection<Statement> body, bool strict)
  1464. {
  1465. return new Program
  1466. {
  1467. Type = SyntaxNodes.Program,
  1468. Body = body,
  1469. Strict = strict,
  1470. VariableDeclarations = LeaveVariableScope(),
  1471. FunctionDeclarations = LeaveFunctionScope()
  1472. };
  1473. }
  1474. public Property CreateProperty(PropertyKind kind, IPropertyKeyExpression key, Expression value)
  1475. {
  1476. return new Property
  1477. {
  1478. Type = SyntaxNodes.Property,
  1479. Key = key,
  1480. Value = value,
  1481. Kind = kind
  1482. };
  1483. }
  1484. public ReturnStatement CreateReturnStatement(Expression argument)
  1485. {
  1486. return new ReturnStatement
  1487. {
  1488. Type = SyntaxNodes.ReturnStatement,
  1489. Argument = argument
  1490. };
  1491. }
  1492. public SequenceExpression CreateSequenceExpression(IList<Expression> expressions)
  1493. {
  1494. return new SequenceExpression
  1495. {
  1496. Type = SyntaxNodes.SequenceExpression,
  1497. Expressions = expressions
  1498. };
  1499. }
  1500. public SwitchCase CreateSwitchCase(Expression test, IEnumerable<Statement> consequent)
  1501. {
  1502. return new SwitchCase
  1503. {
  1504. Type = SyntaxNodes.SwitchCase,
  1505. Test = test,
  1506. Consequent = consequent
  1507. };
  1508. }
  1509. public SwitchStatement CreateSwitchStatement(Expression discriminant, IEnumerable<SwitchCase> cases)
  1510. {
  1511. return new SwitchStatement
  1512. {
  1513. Type = SyntaxNodes.SwitchStatement,
  1514. Discriminant = discriminant,
  1515. Cases = cases
  1516. };
  1517. }
  1518. public ThisExpression CreateThisExpression()
  1519. {
  1520. return new ThisExpression
  1521. {
  1522. Type = SyntaxNodes.ThisExpression
  1523. };
  1524. }
  1525. public ThrowStatement CreateThrowStatement(Expression argument)
  1526. {
  1527. return new ThrowStatement
  1528. {
  1529. Type = SyntaxNodes.ThrowStatement,
  1530. Argument = argument
  1531. };
  1532. }
  1533. public TryStatement CreateTryStatement(Statement block, IEnumerable<Statement> guardedHandlers,
  1534. IEnumerable<CatchClause> handlers, Statement finalizer)
  1535. {
  1536. return new TryStatement
  1537. {
  1538. Type = SyntaxNodes.TryStatement,
  1539. Block = block,
  1540. GuardedHandlers = guardedHandlers,
  1541. Handlers = handlers,
  1542. Finalizer = finalizer
  1543. };
  1544. }
  1545. public UnaryExpression CreateUnaryExpression(string op, Expression argument)
  1546. {
  1547. if (op == "++" || op == "--")
  1548. {
  1549. return new UpdateExpression
  1550. {
  1551. Type = SyntaxNodes.UpdateExpression,
  1552. Operator = op,
  1553. Argument = argument,
  1554. Prefix = true
  1555. };
  1556. }
  1557. return new UnaryExpression
  1558. {
  1559. Type = SyntaxNodes.UnaryExpression,
  1560. Operator = op,
  1561. Argument = argument,
  1562. Prefix = true
  1563. };
  1564. }
  1565. public VariableDeclaration CreateVariableDeclaration(IEnumerable<VariableDeclarator> declarations, string kind)
  1566. {
  1567. var variableDeclaration = new VariableDeclaration
  1568. {
  1569. Type = SyntaxNodes.VariableDeclaration,
  1570. Declarations = declarations,
  1571. Kind = kind
  1572. };
  1573. _variableScopes.Peek().VariableDeclarations.Add(variableDeclaration);
  1574. return variableDeclaration;
  1575. }
  1576. public VariableDeclarator CreateVariableDeclarator(Identifier id, Expression init)
  1577. {
  1578. return new VariableDeclarator
  1579. {
  1580. Type = SyntaxNodes.VariableDeclarator,
  1581. Id = id,
  1582. Init = init
  1583. };
  1584. }
  1585. public WhileStatement CreateWhileStatement(Expression test, Statement body)
  1586. {
  1587. return new WhileStatement
  1588. {
  1589. Type = SyntaxNodes.WhileStatement,
  1590. Test = test,
  1591. Body = body
  1592. };
  1593. }
  1594. public WithStatement CreateWithStatement(Expression obj, Statement body)
  1595. {
  1596. return new WithStatement
  1597. {
  1598. Type = SyntaxNodes.WithStatement,
  1599. Object = obj,
  1600. Body = body
  1601. };
  1602. }
  1603. // Return true if there is a line terminator before the next token.
  1604. private bool PeekLineTerminator()
  1605. {
  1606. int pos = _index;
  1607. int line = _lineNumber;
  1608. int start = _lineStart;
  1609. SkipComment();
  1610. bool found = _lineNumber != line;
  1611. _index = pos;
  1612. _lineNumber = line;
  1613. _lineStart = start;
  1614. return found;
  1615. }
  1616. // Throw an exception
  1617. private void ThrowError(Token token, string messageFormat, params object[] arguments)
  1618. {
  1619. ParserError error;
  1620. string msg = String.Format(messageFormat, arguments);
  1621. if (token != null && token.LineNumber.HasValue)
  1622. {
  1623. error = new ParserError("Line " + token.LineNumber + ": " + msg)
  1624. {
  1625. Index = token.Range[0],
  1626. LineNumber = token.LineNumber.Value,
  1627. Column = token.Range[0] - _lineStart + 1
  1628. };
  1629. }
  1630. else
  1631. {
  1632. error = new ParserError("Line " + _lineNumber + ": " + msg)
  1633. {
  1634. Index = _index,
  1635. LineNumber = _lineNumber,
  1636. Column = _index - _lineStart + 1
  1637. };
  1638. }
  1639. error.Description = msg;
  1640. throw error;
  1641. }
  1642. private void ThrowErrorTolerant(Token token, string messageFormat, params object[] arguments)
  1643. {
  1644. try
  1645. {
  1646. ThrowError(token, messageFormat, arguments);
  1647. }
  1648. catch (Exception e)
  1649. {
  1650. if (_extra.Errors != null)
  1651. {
  1652. _extra.Errors.Add(new ParserError(e.Message));
  1653. }
  1654. else
  1655. {
  1656. throw;
  1657. }
  1658. }
  1659. }
  1660. // Throw an exception because of the token.
  1661. private void ThrowUnexpected(Token token)
  1662. {
  1663. if (token.Type == Tokens.EOF)
  1664. {
  1665. ThrowError(token, Messages.UnexpectedEOS);
  1666. }
  1667. if (token.Type == Tokens.NumericLiteral)
  1668. {
  1669. ThrowError(token, Messages.UnexpectedNumber);
  1670. }
  1671. if (token.Type == Tokens.StringLiteral)
  1672. {
  1673. ThrowError(token, Messages.UnexpectedString);
  1674. }
  1675. if (token.Type == Tokens.Identifier)
  1676. {
  1677. ThrowError(token, Messages.UnexpectedIdentifier);
  1678. }
  1679. if (token.Type == Tokens.Keyword)
  1680. {
  1681. if (IsFutureReservedWord(token.Value as string))
  1682. {
  1683. ThrowError(token, Messages.UnexpectedReserved);
  1684. }
  1685. else if (_strict && IsStrictModeReservedWord(token.Value as string))
  1686. {
  1687. ThrowErrorTolerant(token, Messages.StrictReservedWord);
  1688. return;
  1689. }
  1690. ThrowError(token, Messages.UnexpectedToken, token.Value as string);
  1691. }
  1692. // BooleanLiteral, NullLiteral, or Punctuator.
  1693. ThrowError(token, Messages.UnexpectedToken, token.Value as string);
  1694. }
  1695. // Expect the next token to match the specified punctuator.
  1696. // If not, an exception will be thrown.
  1697. private void Expect(string value)
  1698. {
  1699. Token token = Lex();
  1700. if (token.Type != Tokens.Punctuator || !value.Equals(token.Value))
  1701. {
  1702. ThrowUnexpected(token);
  1703. }
  1704. }
  1705. // Expect the next token to match the specified keyword.
  1706. // If not, an exception will be thrown.
  1707. private void ExpectKeyword(string keyword)
  1708. {
  1709. Token token = Lex();
  1710. if (token.Type != Tokens.Keyword || !keyword.Equals(token.Value))
  1711. {
  1712. ThrowUnexpected(token);
  1713. }
  1714. }
  1715. // Return true if the next token matches the specified punctuator.
  1716. private bool Match(string value)
  1717. {
  1718. return _lookahead.Type == Tokens.Punctuator && value.Equals(_lookahead.Value);
  1719. }
  1720. // Return true if the next token matches the specified keyword
  1721. private bool MatchKeyword(object keyword)
  1722. {
  1723. return _lookahead.Type == Tokens.Keyword && keyword.Equals(_lookahead.Value);
  1724. }
  1725. // Return true if the next token is an assignment operator
  1726. private bool MatchAssign()
  1727. {
  1728. if (_lookahead.Type != Tokens.Punctuator)
  1729. {
  1730. return false;
  1731. }
  1732. var op = _lookahead.Value as string;
  1733. return op == "=" ||
  1734. op == "*=" ||
  1735. op == "/=" ||
  1736. op == "%=" ||
  1737. op == "+=" ||
  1738. op == "-=" ||
  1739. op == "<<=" ||
  1740. op == ">>=" ||
  1741. op == ">>>=" ||
  1742. op == "&=" ||
  1743. op == "^=" ||
  1744. op == "|=";
  1745. }
  1746. private void ConsumeSemicolon()
  1747. {
  1748. // Catch the very common case first: immediately a semicolon (char #59).
  1749. if (_source.CharCodeAt(_index) == 59)
  1750. {
  1751. Lex();
  1752. return;
  1753. }
  1754. int line = _lineNumber;
  1755. SkipComment();
  1756. if (_lineNumber != line)
  1757. {
  1758. return;
  1759. }
  1760. if (Match(";"))
  1761. {
  1762. Lex();
  1763. return;
  1764. }
  1765. if (_lookahead.Type != Tokens.EOF && !Match("}"))
  1766. {
  1767. ThrowUnexpected(_lookahead);
  1768. }
  1769. }
  1770. // Return true if provided expression is LeftHandSideExpression
  1771. private bool isLeftHandSide(Expression expr)
  1772. {
  1773. return expr.Type == SyntaxNodes.Identifier || expr.Type == SyntaxNodes.MemberExpression;
  1774. }
  1775. // 11.1.4 Array Initialiser
  1776. private ArrayExpression ParseArrayInitialiser()
  1777. {
  1778. var elements = new List<Expression>();
  1779. Expect("[");
  1780. while (!Match("]"))
  1781. {
  1782. if (Match(","))
  1783. {
  1784. Lex();
  1785. elements.Add(null);
  1786. }
  1787. else
  1788. {
  1789. elements.Add(ParseAssignmentExpression());
  1790. if (!Match("]"))
  1791. {
  1792. Expect(",");
  1793. }
  1794. }
  1795. }
  1796. Expect("]");
  1797. return CreateArrayExpression(elements);
  1798. }
  1799. // 11.1.5 Object Initialiser
  1800. private FunctionExpression ParsePropertyFunction(Identifier[] parameters, Token first = null)
  1801. {
  1802. EnterVariableScope();
  1803. EnterFunctionScope();
  1804. bool previousStrict = _strict;
  1805. SkipComment();
  1806. MarkStart();
  1807. Statement body = ParseFunctionSourceElements();
  1808. if (first != null && _strict && IsRestrictedWord(parameters[0].Name))
  1809. {
  1810. ThrowErrorTolerant(first, Messages.StrictParamName);
  1811. }
  1812. bool functionStrict = _strict;
  1813. _strict = previousStrict;
  1814. return MarkEnd(CreateFunctionExpression(null, parameters, new Expression[0], body, functionStrict));
  1815. }
  1816. private IPropertyKeyExpression ParseObjectPropertyKey()
  1817. {
  1818. SkipComment();
  1819. MarkStart();
  1820. Token token = Lex();
  1821. // Note: This function is called only from parseObjectProperty(), where
  1822. // EOF and Punctuator tokens are already filtered out.
  1823. if (token.Type == Tokens.StringLiteral || token.Type == Tokens.NumericLiteral)
  1824. {
  1825. if (_strict && token.Octal)
  1826. {
  1827. ThrowErrorTolerant(token, Messages.StrictOctalLiteral);
  1828. }
  1829. return MarkEnd(CreateLiteral(token));
  1830. }
  1831. return MarkEnd(CreateIdentifier((string) token.Value));
  1832. }
  1833. private Property ParseObjectProperty()
  1834. {
  1835. Expression value;
  1836. Token token = _lookahead;
  1837. SkipComment();
  1838. MarkStart();
  1839. if (token.Type == Tokens.Identifier)
  1840. {
  1841. IPropertyKeyExpression id = ParseObjectPropertyKey();
  1842. // Property Assignment: Getter and Setter.
  1843. if ("get".Equals(token.Value) && !Match(":"))
  1844. {
  1845. var key = ParseObjectPropertyKey();
  1846. Expect("(");
  1847. Expect(")");
  1848. value = ParsePropertyFunction(new Identifier[0]);
  1849. return MarkEnd(CreateProperty(PropertyKind.Get, key, value));
  1850. }
  1851. if ("set".Equals(token.Value) && !Match(":"))
  1852. {
  1853. var key = ParseObjectPropertyKey();
  1854. Expect("(");
  1855. token = _lookahead;
  1856. if (token.Type != Tokens.Identifier)
  1857. {
  1858. Expect(")");
  1859. ThrowErrorTolerant(token, Messages.UnexpectedToken, (string) token.Value);
  1860. value = ParsePropertyFunction(new Identifier[0]);
  1861. }
  1862. else
  1863. {
  1864. var param = new[] {ParseVariableIdentifier()};
  1865. Expect(")");
  1866. value = ParsePropertyFunction(param, token);
  1867. }
  1868. return MarkEnd(CreateProperty(PropertyKind.Set, key, value));
  1869. }
  1870. Expect(":");
  1871. value = ParseAssignmentExpression();
  1872. return MarkEnd(CreateProperty(PropertyKind.Data, id, value));
  1873. }
  1874. if (token.Type == Tokens.EOF || token.Type == Tokens.Punctuator)
  1875. {
  1876. ThrowUnexpected(token);
  1877. return null; // can't be reached
  1878. }
  1879. else
  1880. {
  1881. IPropertyKeyExpression key = ParseObjectPropertyKey();
  1882. Expect(":");
  1883. value = ParseAssignmentExpression();
  1884. return MarkEnd(CreateProperty(PropertyKind.Data, key, value));
  1885. }
  1886. }
  1887. private ObjectExpression ParseObjectInitialiser()
  1888. {
  1889. var properties = new List<Property>();
  1890. var map = new Dictionary<string, PropertyKind>();
  1891. Expect("{");
  1892. while (!Match("}"))
  1893. {
  1894. Property property = ParseObjectProperty();
  1895. string name = property.Key.GetKey();
  1896. PropertyKind kind = property.Kind;
  1897. string key = "$" + name;
  1898. if (map.ContainsKey(key))
  1899. {
  1900. if (map[key] == PropertyKind.Data)
  1901. {
  1902. if (_strict && kind == PropertyKind.Data)
  1903. {
  1904. ThrowErrorTolerant(Token.Empty, Messages.StrictDuplicateProperty);
  1905. }
  1906. else if (kind != PropertyKind.Data)
  1907. {
  1908. ThrowErrorTolerant(Token.Empty, Messages.AccessorDataProperty);
  1909. }
  1910. }
  1911. else
  1912. {
  1913. if (kind == PropertyKind.Data)
  1914. {
  1915. ThrowErrorTolerant(Token.Empty, Messages.AccessorDataProperty);
  1916. }
  1917. else if ((map[key] & kind) == kind)
  1918. {
  1919. ThrowErrorTolerant(Token.Empty, Messages.AccessorGetSet);
  1920. }
  1921. }
  1922. map[key] |= kind;
  1923. }
  1924. else
  1925. {
  1926. map[key] = kind;
  1927. }
  1928. properties.Add(property);
  1929. if (!Match("}"))
  1930. {
  1931. Expect(",");
  1932. }
  1933. }
  1934. Expect("}");
  1935. return CreateObjectExpression(properties);
  1936. }
  1937. // 11.1.6 The Grouping Operator
  1938. private Expression ParseGroupExpression()
  1939. {
  1940. Expect("(");
  1941. Expression expr = ParseExpression();
  1942. Expect(")");
  1943. return expr;
  1944. }
  1945. // 11.1 Primary Expressions
  1946. private Expression ParsePrimaryExpression()
  1947. {
  1948. Expression expr = null;
  1949. if (Match("("))
  1950. {
  1951. return ParseGroupExpression();
  1952. }
  1953. Tokens type = _lookahead.Type;
  1954. MarkStart();
  1955. if (type == Tokens.Identifier)
  1956. {
  1957. expr = CreateIdentifier((string) Lex().Value);
  1958. }
  1959. else if (type == Tokens.StringLiteral || type == Tokens.NumericLiteral)
  1960. {
  1961. if (_strict && _lookahead.Octal)
  1962. {
  1963. ThrowErrorTolerant(_lookahead, Messages.StrictOctalLiteral);
  1964. }
  1965. expr = CreateLiteral(Lex());
  1966. }
  1967. else if (type == Tokens.Keyword)
  1968. {
  1969. if (MatchKeyword("this"))
  1970. {
  1971. Lex();
  1972. expr = CreateThisExpression();
  1973. }
  1974. else if (MatchKeyword("function"))
  1975. {
  1976. expr = ParseFunctionExpression();
  1977. }
  1978. }
  1979. else if (type == Tokens.BooleanLiteral)
  1980. {
  1981. Token token = Lex();
  1982. token.Value = ("true".Equals(token.Value));
  1983. expr = CreateLiteral(token);
  1984. }
  1985. else if (type == Tokens.NullLiteral)
  1986. {
  1987. Token token = Lex();
  1988. token.Value = null;
  1989. expr = CreateLiteral(token);
  1990. }
  1991. else if (Match("["))
  1992. {
  1993. expr = ParseArrayInitialiser();
  1994. }
  1995. else if (Match("{"))
  1996. {
  1997. expr = ParseObjectInitialiser();
  1998. }
  1999. else if (Match("/") || Match("/="))
  2000. {
  2001. expr = CreateLiteral(_extra.Tokens != null ? CollectRegex() : ScanRegExp());
  2002. }
  2003. if (expr != null)
  2004. {
  2005. return MarkEnd(expr);
  2006. }
  2007. ThrowUnexpected(Lex());
  2008. return null; // can't be reached
  2009. }
  2010. // 11.2 Left-Hand-Side Expressions
  2011. private IEnumerable<Expression> ParseArguments()
  2012. {
  2013. var args = new List<Expression>();
  2014. Expect("(");
  2015. if (!Match(")"))
  2016. {
  2017. while (_index < _length)
  2018. {
  2019. args.Add(ParseAssignmentExpression());
  2020. if (Match(")"))
  2021. {
  2022. break;
  2023. }
  2024. Expect(",");
  2025. }
  2026. }
  2027. Expect(")");
  2028. return args;
  2029. }
  2030. private Identifier ParseNonComputedProperty()
  2031. {
  2032. MarkStart();
  2033. Token token = Lex();
  2034. if (!IsIdentifierName(token))
  2035. {
  2036. ThrowUnexpected(token);
  2037. }
  2038. return MarkEnd(CreateIdentifier((string) token.Value));
  2039. }
  2040. private Identifier ParseNonComputedMember()
  2041. {
  2042. Expect(".");
  2043. return ParseNonComputedProperty();
  2044. }
  2045. private Expression ParseComputedMember()
  2046. {
  2047. Expect("[");
  2048. Expression expr = ParseExpression();
  2049. Expect("]");
  2050. return expr;
  2051. }
  2052. private NewExpression ParseNewExpression()
  2053. {
  2054. MarkStart();
  2055. ExpectKeyword("new");
  2056. Expression callee = ParseLeftHandSideExpression();
  2057. IEnumerable<Expression> args = Match("(") ? ParseArguments() : new AssignmentExpression[0];
  2058. return MarkEnd(CreateNewExpression(callee, args));
  2059. }
  2060. private Expression ParseLeftHandSideExpressionAllowCall()
  2061. {
  2062. LocationMarker marker = CreateLocationMarker();
  2063. var previousAllowIn = _state.AllowIn;
  2064. _state.AllowIn = true;
  2065. Expression expr = MatchKeyword("new") ? ParseNewExpression() : ParsePrimaryExpression();
  2066. _state.AllowIn = previousAllowIn;
  2067. while (Match(".") || Match("[") || Match("("))
  2068. {
  2069. if (Match("("))
  2070. {
  2071. IEnumerable<Expression> args = ParseArguments();
  2072. expr = CreateCallExpression(expr, args);
  2073. }
  2074. else if (Match("["))
  2075. {
  2076. Expression property = ParseComputedMember();
  2077. expr = CreateMemberExpression('[', expr, property);
  2078. }
  2079. else
  2080. {
  2081. Identifier property = ParseNonComputedMember();
  2082. expr = CreateMemberExpression('.', expr, property);
  2083. }
  2084. if (marker != null)
  2085. {
  2086. marker.End(_index, _lineNumber, _lineStart);
  2087. marker.Apply(expr, _extra, PostProcess);
  2088. }
  2089. }
  2090. return expr;
  2091. }
  2092. private Expression ParseLeftHandSideExpression()
  2093. {
  2094. LocationMarker marker = CreateLocationMarker();
  2095. var previousAllowIn = _state.AllowIn;
  2096. Expression expr = MatchKeyword("new") ? ParseNewExpression() : ParsePrimaryExpression();
  2097. _state.AllowIn = previousAllowIn;
  2098. while (Match(".") || Match("["))
  2099. {
  2100. if (Match("["))
  2101. {
  2102. Expression property = ParseComputedMember();
  2103. expr = CreateMemberExpression('[', expr, property);
  2104. }
  2105. else
  2106. {
  2107. Identifier property = ParseNonComputedMember();
  2108. expr = CreateMemberExpression('.', expr, property);
  2109. }
  2110. if (marker != null)
  2111. {
  2112. marker.End(_index, _lineNumber, _lineStart);
  2113. marker.Apply(expr, _extra, PostProcess);
  2114. }
  2115. }
  2116. return expr;
  2117. }
  2118. // 11.3 Postfix Expressions
  2119. private Expression ParsePostfixExpression()
  2120. {
  2121. MarkStart();
  2122. Expression expr = ParseLeftHandSideExpressionAllowCall();
  2123. if (_lookahead.Type == Tokens.Punctuator)
  2124. {
  2125. if ((Match("++") || Match("--")) && !PeekLineTerminator())
  2126. {
  2127. // 11.3.1, 11.3.2
  2128. if (_strict && expr.Type == SyntaxNodes.Identifier && IsRestrictedWord(((Identifier) expr).Name))
  2129. {
  2130. ThrowErrorTolerant(Token.Empty, Messages.StrictLHSPostfix);
  2131. }
  2132. if (!isLeftHandSide(expr))
  2133. {
  2134. ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInAssignment);
  2135. }
  2136. Token token = Lex();
  2137. expr = CreatePostfixExpression((string) token.Value, expr);
  2138. }
  2139. }
  2140. return MarkEndIf(expr);
  2141. }
  2142. // 11.4 Unary Operators
  2143. private Expression ParseUnaryExpression()
  2144. {
  2145. Expression expr;
  2146. MarkStart();
  2147. if (_lookahead.Type != Tokens.Punctuator && _lookahead.Type != Tokens.Keyword)
  2148. {
  2149. expr = ParsePostfixExpression();
  2150. }
  2151. else if (Match("++") || Match("--"))
  2152. {
  2153. Token token = Lex();
  2154. expr = ParseUnaryExpression();
  2155. // 11.4.4, 11.4.5
  2156. if (_strict && expr.Type == SyntaxNodes.Identifier && IsRestrictedWord(((Identifier) expr).Name))
  2157. {
  2158. ThrowErrorTolerant(Token.Empty, Messages.StrictLHSPrefix);
  2159. }
  2160. if (!isLeftHandSide(expr))
  2161. {
  2162. ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInAssignment);
  2163. }
  2164. expr = CreateUnaryExpression((string) token.Value, expr);
  2165. }
  2166. else if (Match("+") || Match("-") || Match("~") || Match("!"))
  2167. {
  2168. Token token = Lex();
  2169. expr = ParseUnaryExpression();
  2170. expr = CreateUnaryExpression((string) token.Value, expr);
  2171. }
  2172. else if (MatchKeyword("delete") || MatchKeyword("void") || MatchKeyword("typeof"))
  2173. {
  2174. Token token = Lex();
  2175. expr = ParseUnaryExpression();
  2176. UnaryExpression unaryExpr = CreateUnaryExpression((string) token.Value, expr);
  2177. if (_strict && unaryExpr.Operator == "delete" && unaryExpr.Argument.Type == SyntaxNodes.Identifier)
  2178. {
  2179. ThrowErrorTolerant(Token.Empty, Messages.StrictDelete);
  2180. }
  2181. expr = unaryExpr;
  2182. }
  2183. else
  2184. {
  2185. expr = ParsePostfixExpression();
  2186. }
  2187. return MarkEndIf(expr);
  2188. }
  2189. private int binaryPrecedence(Token token, bool allowIn)
  2190. {
  2191. int prec = 0;
  2192. if (token.Type != Tokens.Punctuator && token.Type != Tokens.Keyword)
  2193. {
  2194. return 0;
  2195. }
  2196. switch ((string) token.Value)
  2197. {
  2198. case "||":
  2199. prec = 1;
  2200. break;
  2201. case "&&":
  2202. prec = 2;
  2203. break;
  2204. case "|":
  2205. prec = 3;
  2206. break;
  2207. case "^":
  2208. prec = 4;
  2209. break;
  2210. case "&":
  2211. prec = 5;
  2212. break;
  2213. case "==":
  2214. case "!=":
  2215. case "===":
  2216. case "!==":
  2217. prec = 6;
  2218. break;
  2219. case "<":
  2220. case ">":
  2221. case "<=":
  2222. case ">=":
  2223. case "instanceof":
  2224. prec = 7;
  2225. break;
  2226. case "in":
  2227. prec = allowIn ? 7 : 0;
  2228. break;
  2229. case "<<":
  2230. case ">>":
  2231. case ">>>":
  2232. prec = 8;
  2233. break;
  2234. case "+":
  2235. case "-":
  2236. prec = 9;
  2237. break;
  2238. case "*":
  2239. case "/":
  2240. case "%":
  2241. prec = 11;
  2242. break;
  2243. }
  2244. return prec;
  2245. }
  2246. // 11.5 Multiplicative Operators
  2247. // 11.6 Additive Operators
  2248. // 11.7 Bitwise Shift Operators
  2249. // 11.8 Relational Operators
  2250. // 11.9 Equality Operators
  2251. // 11.10 Binary Bitwise Operators
  2252. // 11.11 Binary Logical Operators
  2253. private Expression ParseBinaryExpression()
  2254. {
  2255. Expression expr;
  2256. LocationMarker marker = CreateLocationMarker();
  2257. Expression left = ParseUnaryExpression();
  2258. Token token = _lookahead;
  2259. int prec = binaryPrecedence(token, _state.AllowIn);
  2260. if (prec == 0)
  2261. {
  2262. return left;
  2263. }
  2264. token.Precedence = prec;
  2265. Lex();
  2266. var markers = new Stack<LocationMarker>( new [] {marker, CreateLocationMarker()});
  2267. Expression right = ParseUnaryExpression();
  2268. var stack = new List<object>( new object[] {left, token, right});
  2269. while ((prec = binaryPrecedence(_lookahead, _state.AllowIn)) > 0)
  2270. {
  2271. // Reduce: make a binary expression from the three topmost entries.
  2272. while ((stack.Count > 2) && (prec <= ((Token) stack[stack.Count - 2]).Precedence))
  2273. {
  2274. right = (Expression) stack.Pop();
  2275. var op = (string) ((Token) stack.Pop()).Value;
  2276. left = (Expression) stack.Pop();
  2277. expr = CreateBinaryExpression(op, left, right);
  2278. markers.Pop();
  2279. marker = markers.Pop();
  2280. if (marker != null)
  2281. {
  2282. marker.End(_index, _lineNumber, _lineStart);
  2283. marker.Apply(expr, _extra, PostProcess);
  2284. }
  2285. stack.Push(expr);
  2286. markers.Push(marker);
  2287. }
  2288. // Shift.
  2289. token = Lex();
  2290. token.Precedence = prec;
  2291. stack.Push(token);
  2292. markers.Push(CreateLocationMarker());
  2293. expr = ParseUnaryExpression();
  2294. stack.Push(expr);
  2295. }
  2296. // Final reduce to clean-up the stack.
  2297. int i = stack.Count - 1;
  2298. expr = (Expression) stack[i];
  2299. markers.Pop();
  2300. while (i > 1)
  2301. {
  2302. expr = CreateBinaryExpression((string) ((Token) stack[i - 1]).Value, (Expression) stack[i - 2], expr);
  2303. i -= 2;
  2304. marker = markers.Pop();
  2305. if (marker != null)
  2306. {
  2307. marker.End(_index, _lineNumber, _lineStart);
  2308. marker.Apply(expr, _extra, PostProcess);
  2309. }
  2310. }
  2311. return expr;
  2312. }
  2313. // 11.12 Conditional Operator
  2314. private Expression ParseConditionalExpression()
  2315. {
  2316. MarkStart();
  2317. Expression expr = ParseBinaryExpression();
  2318. if (Match("?"))
  2319. {
  2320. Lex();
  2321. bool previousAllowIn = _state.AllowIn;
  2322. _state.AllowIn = true;
  2323. Expression consequent = ParseAssignmentExpression();
  2324. _state.AllowIn = previousAllowIn;
  2325. Expect(":");
  2326. Expression alternate = ParseAssignmentExpression();
  2327. expr = MarkEnd(CreateConditionalExpression(expr, consequent, alternate));
  2328. }
  2329. else
  2330. {
  2331. MarkEnd(new SyntaxNode());
  2332. }
  2333. return expr;
  2334. }
  2335. // 11.13 Assignment Operators
  2336. private Expression ParseAssignmentExpression()
  2337. {
  2338. Expression left;
  2339. Token token = _lookahead;
  2340. MarkStart();
  2341. Expression expr = left = ParseConditionalExpression();
  2342. if (MatchAssign())
  2343. {
  2344. // LeftHandSideExpression
  2345. // Ignore issue as it needs to throw a ReferenceError instead of a SyntaxError
  2346. //if (!isLeftHandSide(left))
  2347. //{
  2348. // ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInAssignment);
  2349. //}
  2350. // 11.13.1
  2351. if (_strict && left.Type == SyntaxNodes.Identifier && IsRestrictedWord(((Identifier) left).Name))
  2352. {
  2353. ThrowErrorTolerant(token, Messages.StrictLHSAssignment);
  2354. }
  2355. token = Lex();
  2356. Expression right = ParseAssignmentExpression();
  2357. expr = CreateAssignmentExpression((string) token.Value, left, right);
  2358. }
  2359. return MarkEndIf(expr);
  2360. }
  2361. // 11.14 Comma Operator
  2362. private Expression ParseExpression()
  2363. {
  2364. MarkStart();
  2365. Expression expr = ParseAssignmentExpression();
  2366. if (Match(","))
  2367. {
  2368. expr = CreateSequenceExpression(new List<Expression> {expr});
  2369. while (_index < _length)
  2370. {
  2371. if (!Match(","))
  2372. {
  2373. break;
  2374. }
  2375. Lex();
  2376. ((SequenceExpression) expr).Expressions.Add(ParseAssignmentExpression());
  2377. }
  2378. }
  2379. return MarkEndIf(expr);
  2380. }
  2381. // 12.1 Block
  2382. private IEnumerable<Statement> ParseStatementList()
  2383. {
  2384. var list = new List<Statement>();
  2385. while (_index < _length)
  2386. {
  2387. if (Match("}"))
  2388. {
  2389. break;
  2390. }
  2391. Statement statement = ParseSourceElement();
  2392. if (statement == null)
  2393. {
  2394. break;
  2395. }
  2396. list.Add(statement);
  2397. }
  2398. return list;
  2399. }
  2400. private BlockStatement ParseBlock()
  2401. {
  2402. SkipComment();
  2403. MarkStart();
  2404. Expect("{");
  2405. IEnumerable<Statement> block = ParseStatementList();
  2406. Expect("}");
  2407. return MarkEnd(CreateBlockStatement(block));
  2408. }
  2409. // 12.2 Variable Statement
  2410. private Identifier ParseVariableIdentifier()
  2411. {
  2412. SkipComment();
  2413. MarkStart();
  2414. Token token = Lex();
  2415. if (token.Type != Tokens.Identifier)
  2416. {
  2417. ThrowUnexpected(token);
  2418. }
  2419. return MarkEnd(CreateIdentifier((string) token.Value));
  2420. }
  2421. private VariableDeclarator ParseVariableDeclaration(string kind)
  2422. {
  2423. Expression init = null;
  2424. SkipComment();
  2425. MarkStart();
  2426. Identifier id = ParseVariableIdentifier();
  2427. // 12.2.1
  2428. if (_strict && IsRestrictedWord(id.Name))
  2429. {
  2430. ThrowErrorTolerant(Token.Empty, Messages.StrictVarName);
  2431. }
  2432. if ("const".Equals(kind))
  2433. {
  2434. Expect("=");
  2435. init = ParseAssignmentExpression();
  2436. }
  2437. else if (Match("="))
  2438. {
  2439. Lex();
  2440. init = ParseAssignmentExpression();
  2441. }
  2442. return MarkEnd(CreateVariableDeclarator(id, init));
  2443. }
  2444. private IEnumerable<VariableDeclarator> ParseVariableDeclarationList(string kind)
  2445. {
  2446. var list = new List<VariableDeclarator>();
  2447. do
  2448. {
  2449. list.Add(ParseVariableDeclaration(kind));
  2450. if (!Match(","))
  2451. {
  2452. break;
  2453. }
  2454. Lex();
  2455. } while (_index < _length);
  2456. return list;
  2457. }
  2458. private VariableDeclaration ParseVariableStatement()
  2459. {
  2460. ExpectKeyword("var");
  2461. IEnumerable<VariableDeclarator> declarations = ParseVariableDeclarationList(null);
  2462. ConsumeSemicolon();
  2463. return CreateVariableDeclaration(declarations, "var");
  2464. }
  2465. // kind may be `const` or `let`
  2466. // Both are experimental and not in the specification yet.
  2467. // see http://wiki.ecmascript.org/doku.php?id=harmony:const
  2468. // and http://wiki.ecmascript.org/doku.php?id=harmony:let
  2469. private VariableDeclaration ParseConstLetDeclaration(string kind)
  2470. {
  2471. SkipComment();
  2472. MarkStart();
  2473. ExpectKeyword(kind);
  2474. IEnumerable<VariableDeclarator> declarations = ParseVariableDeclarationList(kind);
  2475. ConsumeSemicolon();
  2476. return MarkEnd(CreateVariableDeclaration(declarations, kind));
  2477. }
  2478. // 12.3 Empty Statement
  2479. private EmptyStatement ParseEmptyStatement()
  2480. {
  2481. Expect(";");
  2482. return CreateEmptyStatement();
  2483. }
  2484. // 12.4 Expression Statement
  2485. private ExpressionStatement ParseExpressionStatement()
  2486. {
  2487. Expression expr = ParseExpression();
  2488. ConsumeSemicolon();
  2489. return CreateExpressionStatement(expr);
  2490. }
  2491. // 12.5 If statement
  2492. private IfStatement ParseIfStatement()
  2493. {
  2494. Statement alternate;
  2495. ExpectKeyword("if");
  2496. Expect("(");
  2497. Expression test = ParseExpression();
  2498. Expect(")");
  2499. Statement consequent = ParseStatement();
  2500. if (MatchKeyword("else"))
  2501. {
  2502. Lex();
  2503. alternate = ParseStatement();
  2504. }
  2505. else
  2506. {
  2507. alternate = null;
  2508. }
  2509. return CreateIfStatement(test, consequent, alternate);
  2510. }
  2511. // 12.6 Iteration Statements
  2512. private DoWhileStatement ParseDoWhileStatement()
  2513. {
  2514. ExpectKeyword("do");
  2515. bool oldInIteration = _state.InIteration;
  2516. _state.InIteration = true;
  2517. Statement body = ParseStatement();
  2518. _state.InIteration = oldInIteration;
  2519. ExpectKeyword("while");
  2520. Expect("(");
  2521. Expression test = ParseExpression();
  2522. Expect(")");
  2523. if (Match(";"))
  2524. {
  2525. Lex();
  2526. }
  2527. return CreateDoWhileStatement(body, test);
  2528. }
  2529. private WhileStatement ParseWhileStatement()
  2530. {
  2531. ExpectKeyword("while");
  2532. Expect("(");
  2533. Expression test = ParseExpression();
  2534. Expect(")");
  2535. bool oldInIteration = _state.InIteration;
  2536. _state.InIteration = true;
  2537. Statement body = ParseStatement();
  2538. _state.InIteration = oldInIteration;
  2539. return CreateWhileStatement(test, body);
  2540. }
  2541. private VariableDeclaration ParseForVariableDeclaration()
  2542. {
  2543. MarkStart();
  2544. Token token = Lex();
  2545. IEnumerable<VariableDeclarator> declarations = ParseVariableDeclarationList(null);
  2546. return MarkEnd(CreateVariableDeclaration(declarations, (string) token.Value));
  2547. }
  2548. private Statement ParseForStatement()
  2549. {
  2550. SyntaxNode init = null, left = null;
  2551. Expression right = null;
  2552. Expression test = null, update = null;
  2553. ExpectKeyword("for");
  2554. Expect("(");
  2555. if (Match(";"))
  2556. {
  2557. Lex();
  2558. }
  2559. else
  2560. {
  2561. if (MatchKeyword("var") || MatchKeyword("let"))
  2562. {
  2563. _state.AllowIn = false;
  2564. init = ParseForVariableDeclaration();
  2565. _state.AllowIn = true;
  2566. if (init.As<VariableDeclaration>().Declarations.Count() == 1 && MatchKeyword("in"))
  2567. {
  2568. Lex();
  2569. left = init;
  2570. right = ParseExpression();
  2571. init = null;
  2572. }
  2573. }
  2574. else
  2575. {
  2576. _state.AllowIn = false;
  2577. init = ParseExpression();
  2578. _state.AllowIn = true;
  2579. if (MatchKeyword("in"))
  2580. {
  2581. // LeftHandSideExpression
  2582. if (!isLeftHandSide((Expression) init))
  2583. {
  2584. ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInForIn);
  2585. }
  2586. Lex();
  2587. left = init;
  2588. right = ParseExpression();
  2589. init = null;
  2590. }
  2591. }
  2592. if (left == null)
  2593. {
  2594. Expect(";");
  2595. }
  2596. }
  2597. if (left == null)
  2598. {
  2599. if (!Match(";"))
  2600. {
  2601. test = ParseExpression();
  2602. }
  2603. Expect(";");
  2604. if (!Match(")"))
  2605. {
  2606. update = ParseExpression();
  2607. }
  2608. }
  2609. Expect(")");
  2610. bool oldInIteration = _state.InIteration;
  2611. _state.InIteration = true;
  2612. Statement body = ParseStatement();
  2613. _state.InIteration = oldInIteration;
  2614. return (left == null)
  2615. ? (Statement) CreateForStatement(init, test, update, body)
  2616. : CreateForInStatement(left, right, body);
  2617. }
  2618. // 12.7 The continue statement
  2619. private Statement ParseContinueStatement()
  2620. {
  2621. Identifier label = null;
  2622. ExpectKeyword("continue");
  2623. // Optimize the most common form: 'continue;'.
  2624. if (_source.CharCodeAt(_index) == 59)
  2625. {
  2626. Lex();
  2627. if (!_state.InIteration)
  2628. {
  2629. ThrowError(Token.Empty, Messages.IllegalContinue);
  2630. }
  2631. return CreateContinueStatement(null);
  2632. }
  2633. if (PeekLineTerminator())
  2634. {
  2635. if (!_state.InIteration)
  2636. {
  2637. ThrowError(Token.Empty, Messages.IllegalContinue);
  2638. }
  2639. return CreateContinueStatement(null);
  2640. }
  2641. if (_lookahead.Type == Tokens.Identifier)
  2642. {
  2643. label = ParseVariableIdentifier();
  2644. string key = "$" + label.Name;
  2645. if (!_state.LabelSet.Contains(key))
  2646. {
  2647. ThrowError(Token.Empty, Messages.UnknownLabel, label.Name);
  2648. }
  2649. }
  2650. ConsumeSemicolon();
  2651. if (label == null && !_state.InIteration)
  2652. {
  2653. ThrowError(Token.Empty, Messages.IllegalContinue);
  2654. }
  2655. return CreateContinueStatement(label);
  2656. }
  2657. // 12.8 The break statement
  2658. private BreakStatement ParseBreakStatement()
  2659. {
  2660. Identifier label = null;
  2661. ExpectKeyword("break");
  2662. // Catch the very common case first: immediately a semicolon (char #59).
  2663. if (_source.CharCodeAt(_index) == 59)
  2664. {
  2665. Lex();
  2666. if (!(_state.InIteration || _state.InSwitch))
  2667. {
  2668. ThrowError(Token.Empty, Messages.IllegalBreak);
  2669. }
  2670. return CreateBreakStatement(null);
  2671. }
  2672. if (PeekLineTerminator())
  2673. {
  2674. if (!(_state.InIteration || _state.InSwitch))
  2675. {
  2676. ThrowError(Token.Empty, Messages.IllegalBreak);
  2677. }
  2678. return CreateBreakStatement(null);
  2679. }
  2680. if (_lookahead.Type == Tokens.Identifier)
  2681. {
  2682. label = ParseVariableIdentifier();
  2683. string key = "$" + label.Name;
  2684. if (!_state.LabelSet.Contains(key))
  2685. {
  2686. ThrowError(Token.Empty, Messages.UnknownLabel, label.Name);
  2687. }
  2688. }
  2689. ConsumeSemicolon();
  2690. if (label == null && !(_state.InIteration || _state.InSwitch))
  2691. {
  2692. ThrowError(Token.Empty, Messages.IllegalBreak);
  2693. }
  2694. return CreateBreakStatement(label);
  2695. }
  2696. // 12.9 The return statement
  2697. private ReturnStatement ParseReturnStatement()
  2698. {
  2699. Expression argument = null;
  2700. ExpectKeyword("return");
  2701. if (!_state.InFunctionBody)
  2702. {
  2703. ThrowErrorTolerant(Token.Empty, Messages.IllegalReturn);
  2704. }
  2705. // 'return' followed by a space and an identifier is very common.
  2706. if (_source.CharCodeAt(_index) == 32)
  2707. {
  2708. if (IsIdentifierStart(_source.CharCodeAt(_index + 1)))
  2709. {
  2710. argument = ParseExpression();
  2711. ConsumeSemicolon();
  2712. return CreateReturnStatement(argument);
  2713. }
  2714. }
  2715. if (PeekLineTerminator())
  2716. {
  2717. return CreateReturnStatement(null);
  2718. }
  2719. if (!Match(";"))
  2720. {
  2721. if (!Match("}") && _lookahead.Type != Tokens.EOF)
  2722. {
  2723. argument = ParseExpression();
  2724. }
  2725. }
  2726. ConsumeSemicolon();
  2727. return CreateReturnStatement(argument);
  2728. }
  2729. // 12.10 The with statement
  2730. private WithStatement ParseWithStatement()
  2731. {
  2732. if (_strict)
  2733. {
  2734. ThrowErrorTolerant(Token.Empty, Messages.StrictModeWith);
  2735. }
  2736. ExpectKeyword("with");
  2737. Expect("(");
  2738. Expression obj = ParseExpression();
  2739. Expect(")");
  2740. Statement body = ParseStatement();
  2741. return CreateWithStatement(obj, body);
  2742. }
  2743. // 12.10 The swith statement
  2744. private SwitchCase ParseSwitchCase()
  2745. {
  2746. Expression test;
  2747. var consequent = new List<Statement>();
  2748. SkipComment();
  2749. MarkStart();
  2750. if (MatchKeyword("default"))
  2751. {
  2752. Lex();
  2753. test = null;
  2754. }
  2755. else
  2756. {
  2757. ExpectKeyword("case");
  2758. test = ParseExpression();
  2759. }
  2760. Expect(":");
  2761. while (_index < _length)
  2762. {
  2763. if (Match("}") || MatchKeyword("default") || MatchKeyword("case"))
  2764. {
  2765. break;
  2766. }
  2767. Statement statement = ParseStatement();
  2768. consequent.Add(statement);
  2769. }
  2770. return MarkEnd(CreateSwitchCase(test, consequent));
  2771. }
  2772. private SwitchStatement ParseSwitchStatement()
  2773. {
  2774. ExpectKeyword("switch");
  2775. Expect("(");
  2776. Expression discriminant = ParseExpression();
  2777. Expect(")");
  2778. Expect("{");
  2779. var cases = new List<SwitchCase>();
  2780. if (Match("}"))
  2781. {
  2782. Lex();
  2783. return CreateSwitchStatement(discriminant, cases);
  2784. }
  2785. bool oldInSwitch = _state.InSwitch;
  2786. _state.InSwitch = true;
  2787. bool defaultFound = false;
  2788. while (_index < _length)
  2789. {
  2790. if (Match("}"))
  2791. {
  2792. break;
  2793. }
  2794. SwitchCase clause = ParseSwitchCase();
  2795. if (clause.Test == null)
  2796. {
  2797. if (defaultFound)
  2798. {
  2799. ThrowError(Token.Empty, Messages.MultipleDefaultsInSwitch);
  2800. }
  2801. defaultFound = true;
  2802. }
  2803. cases.Add(clause);
  2804. }
  2805. _state.InSwitch = oldInSwitch;
  2806. Expect("}");
  2807. return CreateSwitchStatement(discriminant, cases);
  2808. }
  2809. // 12.13 The throw statement
  2810. private ThrowStatement ParseThrowStatement()
  2811. {
  2812. ExpectKeyword("throw");
  2813. if (PeekLineTerminator())
  2814. {
  2815. ThrowError(Token.Empty, Messages.NewlineAfterThrow);
  2816. }
  2817. Expression argument = ParseExpression();
  2818. ConsumeSemicolon();
  2819. return CreateThrowStatement(argument);
  2820. }
  2821. // 12.14 The try statement
  2822. private CatchClause ParseCatchClause()
  2823. {
  2824. SkipComment();
  2825. MarkStart();
  2826. ExpectKeyword("catch");
  2827. Expect("(");
  2828. if (Match(")"))
  2829. {
  2830. ThrowUnexpected(_lookahead);
  2831. }
  2832. Identifier param = ParseVariableIdentifier();
  2833. // 12.14.1
  2834. if (_strict && IsRestrictedWord(param.Name))
  2835. {
  2836. ThrowErrorTolerant(Token.Empty, Messages.StrictCatchVariable);
  2837. }
  2838. Expect(")");
  2839. BlockStatement body = ParseBlock();
  2840. return MarkEnd(CreateCatchClause(param, body));
  2841. }
  2842. private TryStatement ParseTryStatement()
  2843. {
  2844. var handlers = new List<CatchClause>();
  2845. Statement finalizer = null;
  2846. ExpectKeyword("try");
  2847. BlockStatement block = ParseBlock();
  2848. if (MatchKeyword("catch"))
  2849. {
  2850. handlers.Add(ParseCatchClause());
  2851. }
  2852. if (MatchKeyword("finally"))
  2853. {
  2854. Lex();
  2855. finalizer = ParseBlock();
  2856. }
  2857. if (handlers.Count == 0 && finalizer == null)
  2858. {
  2859. ThrowError(Token.Empty, Messages.NoCatchOrFinally);
  2860. }
  2861. return CreateTryStatement(block, new Statement[0], handlers, finalizer);
  2862. }
  2863. // 12.15 The debugger statement
  2864. private DebuggerStatement ParseDebuggerStatement()
  2865. {
  2866. ExpectKeyword("debugger");
  2867. ConsumeSemicolon();
  2868. return CreateDebuggerStatement();
  2869. }
  2870. // 12 Statements
  2871. private Statement ParseStatement()
  2872. {
  2873. Tokens type = _lookahead.Type;
  2874. if (type == Tokens.EOF)
  2875. {
  2876. ThrowUnexpected(_lookahead);
  2877. }
  2878. SkipComment();
  2879. MarkStart();
  2880. if (type == Tokens.Punctuator)
  2881. {
  2882. switch ((string) _lookahead.Value)
  2883. {
  2884. case ";":
  2885. return MarkEnd(ParseEmptyStatement());
  2886. case "{":
  2887. return MarkEnd(ParseBlock());
  2888. case "(":
  2889. return MarkEnd(ParseExpressionStatement());
  2890. }
  2891. }
  2892. if (type == Tokens.Keyword)
  2893. {
  2894. switch ((string) _lookahead.Value)
  2895. {
  2896. case "break":
  2897. return MarkEnd(ParseBreakStatement());
  2898. case "continue":
  2899. return MarkEnd(ParseContinueStatement());
  2900. case "debugger":
  2901. return MarkEnd(ParseDebuggerStatement());
  2902. case "do":
  2903. return MarkEnd(ParseDoWhileStatement());
  2904. case "for":
  2905. return MarkEnd(ParseForStatement());
  2906. case "function":
  2907. return MarkEnd(ParseFunctionDeclaration());
  2908. case "if":
  2909. return MarkEnd(ParseIfStatement());
  2910. case "return":
  2911. return MarkEnd(ParseReturnStatement());
  2912. case "switch":
  2913. return MarkEnd(ParseSwitchStatement());
  2914. case "throw":
  2915. return MarkEnd(ParseThrowStatement());
  2916. case "try":
  2917. return MarkEnd(ParseTryStatement());
  2918. case "var":
  2919. return MarkEnd(ParseVariableStatement());
  2920. case "while":
  2921. return MarkEnd(ParseWhileStatement());
  2922. case "with":
  2923. return MarkEnd(ParseWithStatement());
  2924. }
  2925. }
  2926. Expression expr = ParseExpression();
  2927. // 12.12 Labelled Statements
  2928. if ((expr.Type == SyntaxNodes.Identifier) && Match(":"))
  2929. {
  2930. Lex();
  2931. string key = "$" + ((Identifier) expr).Name;
  2932. if (_state.LabelSet.Contains(key))
  2933. {
  2934. ThrowError(Token.Empty, Messages.Redeclaration, "Label", ((Identifier) expr).Name);
  2935. }
  2936. _state.LabelSet.Add(key);
  2937. Statement labeledBody = ParseStatement();
  2938. _state.LabelSet.Remove(key);
  2939. return MarkEnd(CreateLabeledStatement((Identifier) expr, labeledBody));
  2940. }
  2941. ConsumeSemicolon();
  2942. return MarkEnd(CreateExpressionStatement(expr));
  2943. }
  2944. // 13 Function Definition
  2945. private Statement ParseFunctionSourceElements()
  2946. {
  2947. Token firstRestricted = Token.Empty;
  2948. var sourceElements = new List<Statement>();
  2949. SkipComment();
  2950. MarkStart();
  2951. Expect("{");
  2952. while (_index < _length)
  2953. {
  2954. if (_lookahead.Type != Tokens.StringLiteral)
  2955. {
  2956. break;
  2957. }
  2958. Token token = _lookahead;
  2959. Statement sourceElement = ParseSourceElement();
  2960. sourceElements.Add(sourceElement);
  2961. if (((ExpressionStatement) sourceElement).Expression.Type != SyntaxNodes.Literal)
  2962. {
  2963. // this is not directive
  2964. break;
  2965. }
  2966. string directive = _source.Slice(token.Range[0] + 1, token.Range[1] - 1);
  2967. if (directive == "use strict")
  2968. {
  2969. _strict = true;
  2970. if (firstRestricted != Token.Empty)
  2971. {
  2972. ThrowErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  2973. }
  2974. }
  2975. else
  2976. {
  2977. if (firstRestricted == Token.Empty && token.Octal)
  2978. {
  2979. firstRestricted = token;
  2980. }
  2981. }
  2982. }
  2983. HashSet<string> oldLabelSet = _state.LabelSet;
  2984. bool oldInIteration = _state.InIteration;
  2985. bool oldInSwitch = _state.InSwitch;
  2986. bool oldInFunctionBody = _state.InFunctionBody;
  2987. _state.LabelSet = new HashSet<string>();
  2988. _state.InIteration = false;
  2989. _state.InSwitch = false;
  2990. _state.InFunctionBody = true;
  2991. while (_index < _length)
  2992. {
  2993. if (Match("}"))
  2994. {
  2995. break;
  2996. }
  2997. Statement sourceElement = ParseSourceElement();
  2998. if (sourceElement == null)
  2999. {
  3000. break;
  3001. }
  3002. sourceElements.Add(sourceElement);
  3003. }
  3004. Expect("}");
  3005. _state.LabelSet = oldLabelSet;
  3006. _state.InIteration = oldInIteration;
  3007. _state.InSwitch = oldInSwitch;
  3008. _state.InFunctionBody = oldInFunctionBody;
  3009. return MarkEnd(CreateBlockStatement(sourceElements));
  3010. }
  3011. private ParsedParameters ParseParams(Token firstRestricted)
  3012. {
  3013. string message = null;
  3014. Token stricted = Token.Empty;
  3015. var parameters = new List<Identifier>();
  3016. Expect("(");
  3017. if (!Match(")"))
  3018. {
  3019. var paramSet = new HashSet<string>();
  3020. while (_index < _length)
  3021. {
  3022. Token token = _lookahead;
  3023. Identifier param = ParseVariableIdentifier();
  3024. string key = '$' + (string) token.Value;
  3025. if (_strict)
  3026. {
  3027. if (IsRestrictedWord((string) token.Value))
  3028. {
  3029. stricted = token;
  3030. message = Messages.StrictParamName;
  3031. }
  3032. if (paramSet.Contains(key))
  3033. {
  3034. stricted = token;
  3035. message = Messages.StrictParamDupe;
  3036. }
  3037. }
  3038. else if (firstRestricted == Token.Empty)
  3039. {
  3040. if (IsRestrictedWord((string) token.Value))
  3041. {
  3042. firstRestricted = token;
  3043. message = Messages.StrictParamName;
  3044. }
  3045. else if (IsStrictModeReservedWord((string) token.Value))
  3046. {
  3047. firstRestricted = token;
  3048. message = Messages.StrictReservedWord;
  3049. }
  3050. else if (paramSet.Contains(key))
  3051. {
  3052. firstRestricted = token;
  3053. message = Messages.StrictParamDupe;
  3054. }
  3055. }
  3056. parameters.Add(param);
  3057. paramSet.Add(key);
  3058. if (Match(")"))
  3059. {
  3060. break;
  3061. }
  3062. Expect(",");
  3063. }
  3064. }
  3065. Expect(")");
  3066. return new ParsedParameters
  3067. {
  3068. Parameters = parameters,
  3069. Stricted = stricted,
  3070. FirstRestricted = firstRestricted,
  3071. Message = message
  3072. };
  3073. }
  3074. private Statement ParseFunctionDeclaration()
  3075. {
  3076. EnterVariableScope();
  3077. EnterFunctionScope();
  3078. Token firstRestricted = Token.Empty;
  3079. string message = null;
  3080. SkipComment();
  3081. MarkStart();
  3082. ExpectKeyword("function");
  3083. Token token = _lookahead;
  3084. Identifier id = ParseVariableIdentifier();
  3085. if (_strict)
  3086. {
  3087. if (IsRestrictedWord((string) token.Value))
  3088. {
  3089. ThrowErrorTolerant(token, Messages.StrictFunctionName);
  3090. }
  3091. }
  3092. else
  3093. {
  3094. if (IsRestrictedWord((string) token.Value))
  3095. {
  3096. firstRestricted = token;
  3097. message = Messages.StrictFunctionName;
  3098. }
  3099. else if (IsStrictModeReservedWord((string) token.Value))
  3100. {
  3101. firstRestricted = token;
  3102. message = Messages.StrictReservedWord;
  3103. }
  3104. }
  3105. ParsedParameters tmp = ParseParams(firstRestricted);
  3106. IEnumerable<Identifier> parameters = tmp.Parameters;
  3107. Token stricted = tmp.Stricted;
  3108. firstRestricted = tmp.FirstRestricted;
  3109. if (tmp.Message != null)
  3110. {
  3111. message = tmp.Message;
  3112. }
  3113. bool previousStrict = _strict;
  3114. Statement body = ParseFunctionSourceElements();
  3115. if (_strict && firstRestricted != Token.Empty)
  3116. {
  3117. ThrowError(firstRestricted, message);
  3118. }
  3119. if (_strict && stricted != Token.Empty)
  3120. {
  3121. ThrowErrorTolerant(stricted, message);
  3122. }
  3123. bool functionStrict = _strict;
  3124. _strict = previousStrict;
  3125. return MarkEnd(CreateFunctionDeclaration(id, parameters, new Expression[0], body, functionStrict));
  3126. }
  3127. private void EnterVariableScope()
  3128. {
  3129. _variableScopes.Push(new VariableScope());
  3130. }
  3131. private IList<VariableDeclaration> LeaveVariableScope()
  3132. {
  3133. return _variableScopes.Pop().VariableDeclarations;
  3134. }
  3135. private void EnterFunctionScope()
  3136. {
  3137. _functionScopes.Push(new FunctionScope());
  3138. }
  3139. private IList<FunctionDeclaration> LeaveFunctionScope()
  3140. {
  3141. return _functionScopes.Pop().FunctionDeclarations;
  3142. }
  3143. private FunctionExpression ParseFunctionExpression()
  3144. {
  3145. EnterVariableScope();
  3146. EnterFunctionScope();
  3147. Token firstRestricted = Token.Empty;
  3148. string message = null;
  3149. Identifier id = null;
  3150. MarkStart();
  3151. ExpectKeyword("function");
  3152. if (!Match("("))
  3153. {
  3154. Token token = _lookahead;
  3155. id = ParseVariableIdentifier();
  3156. if (_strict)
  3157. {
  3158. if (IsRestrictedWord((string) token.Value))
  3159. {
  3160. ThrowErrorTolerant(token, Messages.StrictFunctionName);
  3161. }
  3162. }
  3163. else
  3164. {
  3165. if (IsRestrictedWord((string) token.Value))
  3166. {
  3167. firstRestricted = token;
  3168. message = Messages.StrictFunctionName;
  3169. }
  3170. else if (IsStrictModeReservedWord((string) token.Value))
  3171. {
  3172. firstRestricted = token;
  3173. message = Messages.StrictReservedWord;
  3174. }
  3175. }
  3176. }
  3177. ParsedParameters tmp = ParseParams(firstRestricted);
  3178. IEnumerable<Identifier> parameters = tmp.Parameters;
  3179. Token stricted = tmp.Stricted;
  3180. firstRestricted = tmp.FirstRestricted;
  3181. if (tmp.Message != null)
  3182. {
  3183. message = tmp.Message;
  3184. }
  3185. bool previousStrict = _strict;
  3186. Statement body = ParseFunctionSourceElements();
  3187. if (_strict && firstRestricted != Token.Empty)
  3188. {
  3189. ThrowError(firstRestricted, message);
  3190. }
  3191. if (_strict && stricted != Token.Empty)
  3192. {
  3193. ThrowErrorTolerant(stricted, message);
  3194. }
  3195. bool functionStrict = _strict;
  3196. _strict = previousStrict;
  3197. return MarkEnd(CreateFunctionExpression(id, parameters, new Expression[0], body, functionStrict));
  3198. }
  3199. // 14 Program
  3200. private Statement ParseSourceElement()
  3201. {
  3202. if (_lookahead.Type == Tokens.Keyword)
  3203. {
  3204. switch ((string) _lookahead.Value)
  3205. {
  3206. case "const":
  3207. case "let":
  3208. return ParseConstLetDeclaration((string) _lookahead.Value);
  3209. case "function":
  3210. return ParseFunctionDeclaration();
  3211. default:
  3212. return ParseStatement();
  3213. }
  3214. }
  3215. if (_lookahead.Type != Tokens.EOF)
  3216. {
  3217. return ParseStatement();
  3218. }
  3219. return null;
  3220. }
  3221. private ICollection<Statement> ParseSourceElements()
  3222. {
  3223. var sourceElements = new List<Statement>();
  3224. Token firstRestricted = Token.Empty;
  3225. Statement sourceElement;
  3226. while (_index < _length)
  3227. {
  3228. Token token = _lookahead;
  3229. if (token.Type != Tokens.StringLiteral)
  3230. {
  3231. break;
  3232. }
  3233. sourceElement = ParseSourceElement();
  3234. sourceElements.Add(sourceElement);
  3235. if (((ExpressionStatement) sourceElement).Expression.Type != SyntaxNodes.Literal)
  3236. {
  3237. // this is not directive
  3238. break;
  3239. }
  3240. string directive = _source.Slice(token.Range[0] + 1, token.Range[1] - 1);
  3241. if (directive == "use strict")
  3242. {
  3243. _strict = true;
  3244. if (firstRestricted != Token.Empty)
  3245. {
  3246. ThrowErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  3247. }
  3248. }
  3249. else
  3250. {
  3251. if (firstRestricted == Token.Empty && token.Octal)
  3252. {
  3253. firstRestricted = token;
  3254. }
  3255. }
  3256. }
  3257. while (_index < _length)
  3258. {
  3259. sourceElement = ParseSourceElement();
  3260. if (sourceElement == null)
  3261. {
  3262. break;
  3263. }
  3264. sourceElements.Add(sourceElement);
  3265. }
  3266. return sourceElements;
  3267. }
  3268. private Program ParseProgram()
  3269. {
  3270. EnterVariableScope();
  3271. EnterFunctionScope();
  3272. SkipComment();
  3273. MarkStart();
  3274. Peek();
  3275. ICollection<Statement> body = ParseSourceElements();
  3276. return MarkEnd(CreateProgram(body, _strict));
  3277. }
  3278. private LocationMarker CreateLocationMarker()
  3279. {
  3280. if (!_extra.Loc.HasValue && _extra.Range.Length == 0)
  3281. {
  3282. return null;
  3283. }
  3284. SkipComment();
  3285. return new LocationMarker(_index, _lineNumber, _lineStart);
  3286. }
  3287. public Program Parse(string code)
  3288. {
  3289. return Parse(code, null);
  3290. }
  3291. public Program Parse(string code, ParserOptions options)
  3292. {
  3293. Program program;
  3294. _source = code;
  3295. _index = 0;
  3296. _lineNumber = (_source.Length > 0) ? 1 : 0;
  3297. _lineStart = 0;
  3298. _length = _source.Length;
  3299. _lookahead = null;
  3300. _state = new State
  3301. {
  3302. AllowIn = true,
  3303. LabelSet = new HashSet<string>(),
  3304. InFunctionBody = false,
  3305. InIteration = false,
  3306. InSwitch = false,
  3307. LastCommentStart = -1,
  3308. MarkerStack = new Stack<int>()
  3309. };
  3310. _extra = new Extra
  3311. {
  3312. Range = new int[0],
  3313. Loc = 0,
  3314. };
  3315. if (options != null)
  3316. {
  3317. if (!String.IsNullOrEmpty(options.Source))
  3318. {
  3319. _extra.Source = options.Source;
  3320. }
  3321. if (options.Tokens)
  3322. {
  3323. _extra.Tokens = new List<Token>();
  3324. }
  3325. if (options.Comment)
  3326. {
  3327. _extra.Comments = new List<Comment>();
  3328. }
  3329. if (options.Tolerant)
  3330. {
  3331. _extra.Errors = new List<ParserError>();
  3332. }
  3333. }
  3334. try
  3335. {
  3336. program = ParseProgram();
  3337. if (_extra.Comments != null)
  3338. {
  3339. program.Comments = _extra.Comments;
  3340. }
  3341. if (_extra.Tokens != null)
  3342. {
  3343. program.Tokens = _extra.Tokens;
  3344. }
  3345. if (_extra.Errors != null)
  3346. {
  3347. program.Errors = _extra.Errors;
  3348. }
  3349. }
  3350. finally
  3351. {
  3352. _extra = new Extra();
  3353. }
  3354. return program;
  3355. }
  3356. public FunctionExpression ParseFunctionExpression(string functionExpression)
  3357. {
  3358. _source = functionExpression;
  3359. _index = 0;
  3360. _lineNumber = (_source.Length > 0) ? 1 : 0;
  3361. _lineStart = 0;
  3362. _length = _source.Length;
  3363. _lookahead = null;
  3364. _state = new State
  3365. {
  3366. AllowIn = true,
  3367. LabelSet = new HashSet<string>(),
  3368. InFunctionBody = true,
  3369. InIteration = false,
  3370. InSwitch = false,
  3371. LastCommentStart = -1,
  3372. MarkerStack = new Stack<int>()
  3373. };
  3374. _extra = new Extra
  3375. {
  3376. Range = new int[0],
  3377. Loc = 0,
  3378. };
  3379. _strict = false;
  3380. Peek();
  3381. return ParseFunctionExpression();
  3382. }
  3383. private class Extra
  3384. {
  3385. public int? Loc;
  3386. public int[] Range;
  3387. public string Source;
  3388. public List<Comment> Comments;
  3389. public List<Token> Tokens;
  3390. public List<ParserError> Errors;
  3391. }
  3392. private class LocationMarker
  3393. {
  3394. private readonly int[] _marker;
  3395. public LocationMarker(int index, int lineNumber, int lineStart)
  3396. {
  3397. _marker = new[] {index, lineNumber, index - lineStart, 0, 0, 0};
  3398. }
  3399. public void End(int index, int lineNumber, int lineStart)
  3400. {
  3401. _marker[3] = index;
  3402. _marker[4] = lineNumber;
  3403. _marker[5] = index - lineStart;
  3404. }
  3405. public void Apply(SyntaxNode node, Extra extra, Func<SyntaxNode, SyntaxNode> postProcess)
  3406. {
  3407. if (extra.Range.Length > 0)
  3408. {
  3409. node.Range = new[] {_marker[0], _marker[3]};
  3410. }
  3411. if (extra.Loc.HasValue)
  3412. {
  3413. node.Location = new Location
  3414. {
  3415. Start = new Position
  3416. {
  3417. Line = _marker[1],
  3418. Column = _marker[2]
  3419. },
  3420. End = new Position
  3421. {
  3422. Line = _marker[4],
  3423. Column = _marker[5]
  3424. }
  3425. };
  3426. }
  3427. node = postProcess(node);
  3428. }
  3429. };
  3430. private struct ParsedParameters
  3431. {
  3432. public Token FirstRestricted;
  3433. public string Message;
  3434. public IEnumerable<Identifier> Parameters;
  3435. public Token Stricted;
  3436. }
  3437. private static class Regexes
  3438. {
  3439. public static readonly Regex NonAsciiIdentifierStart = new Regex("[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]");
  3440. public static readonly Regex NonAsciiIdentifierPart = new Regex("[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]");
  3441. };
  3442. }
  3443. }