JavascriptParser.cs 133 KB

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