JavascriptParser.cs 131 KB

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