JavascriptParser.cs 131 KB

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