JavascriptParser.cs 133 KB

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