JavascriptParser.cs 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using Jint.Parser.Ast;
  8. namespace Jint.Parser
  9. {
  10. public class JavaScriptParser
  11. {
  12. private static readonly HashSet<string> Keywords = new HashSet<string>
  13. {
  14. "if", "in", "do", "var", "for", "new", "try", "let",
  15. "this", "else", "case", "void", "with", "enum",
  16. "while", "break", "catch", "throw", "const", "yield",
  17. "class", "super", "return", "typeof", "delete",
  18. "switch", "export", "import", "default", "finally", "extends",
  19. "function", "continue", "debugger", "instanceof"
  20. };
  21. private static readonly HashSet<string> StrictModeReservedWords = new HashSet<string>
  22. {
  23. "implements",
  24. "interface",
  25. "package",
  26. "private",
  27. "protected",
  28. "public",
  29. "static",
  30. "yield",
  31. "let"
  32. };
  33. private static readonly HashSet<string> FutureReservedWords = new HashSet<string>
  34. {
  35. "class",
  36. "enum",
  37. "export",
  38. "extends",
  39. "import",
  40. "super"
  41. };
  42. private Extra _extra;
  43. private int _index; // position in the stream
  44. private int _length; // length of the stream
  45. private int _lineNumber;
  46. private int _lineStart;
  47. private Location _location;
  48. private Token _lookahead;
  49. private string _source;
  50. private State _state;
  51. private bool _strict;
  52. private readonly Stack<IVariableScope> _variableScopes = new Stack<IVariableScope>();
  53. private readonly Stack<IFunctionScope> _functionScopes = new Stack<IFunctionScope>();
  54. public JavaScriptParser()
  55. {
  56. }
  57. public JavaScriptParser(bool strict)
  58. {
  59. _strict = strict;
  60. }
  61. private static bool IsDecimalDigit(char ch)
  62. {
  63. return (ch >= '0' && ch <= '9');
  64. }
  65. private static bool IsHexDigit(char ch)
  66. {
  67. return
  68. ch >= '0' && ch <= '9' ||
  69. ch >= 'a' && ch <= 'f' ||
  70. ch >= 'A' && ch <= 'F'
  71. ;
  72. }
  73. private static bool IsOctalDigit(char ch)
  74. {
  75. return ch >= '0' && ch <= '7';
  76. }
  77. // 7.2 White Space
  78. 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 FutureReservedWords.Contains(id);
  125. }
  126. private static bool IsStrictModeReservedWord(string id)
  127. {
  128. return StrictModeReservedWords.Contains(id);
  129. }
  130. private static bool IsRestrictedWord(string id)
  131. {
  132. return "eval".Equals(id) || "arguments".Equals(id);
  133. }
  134. // 7.6.1.1 Keywords
  135. private bool IsKeyword(string id)
  136. {
  137. if (_strict && IsStrictModeReservedWord(id))
  138. {
  139. return true;
  140. }
  141. // 'const' is specialized as Keyword in V8.
  142. // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next.
  143. // Some others are from future reserved words.
  144. return Keywords.Contains(id);
  145. }
  146. // 7.4 Comments
  147. private void AddComment(string type, string value, int start, int end, Location location)
  148. {
  149. // Because the way the actual token is scanned, often the comments
  150. // (if any) are skipped twice during the lexical analysis.
  151. // Thus, we need to skip adding a comment if the comment array already
  152. // handled it.
  153. if (_state.LastCommentStart >= start)
  154. {
  155. return;
  156. }
  157. _state.LastCommentStart = start;
  158. var comment = new Comment
  159. {
  160. Type = type,
  161. Value = value
  162. };
  163. if (_extra.Range != null)
  164. {
  165. comment.Range = new[] {start, end};
  166. }
  167. if (_extra.Loc.HasValue)
  168. {
  169. comment.Location = location;
  170. }
  171. _extra.Comments.Add(comment);
  172. }
  173. private void SkipSingleLineComment()
  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.ToInt64(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, CultureInfo.InvariantCulture);
  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. SkipComment();
  1139. if (_extra.Loc.HasValue)
  1140. {
  1141. _state.MarkerStack.Push(_index - _lineStart);
  1142. _state.MarkerStack.Push(_lineNumber);
  1143. }
  1144. if (_extra.Range != null)
  1145. {
  1146. _state.MarkerStack.Push(_index);
  1147. }
  1148. }
  1149. private T MarkEnd<T>(T node) where T : SyntaxNode
  1150. {
  1151. if (_extra.Range != null)
  1152. {
  1153. node.Range = new[] {_state.MarkerStack.Pop(), _index};
  1154. }
  1155. if (_extra.Loc.HasValue)
  1156. {
  1157. node.Location = new Location
  1158. {
  1159. Start = new Position
  1160. {
  1161. Line = _state.MarkerStack.Pop(),
  1162. Column = _state.MarkerStack.Pop()
  1163. },
  1164. End = new Position
  1165. {
  1166. Line = _lineNumber,
  1167. Column = _index - _lineStart
  1168. }
  1169. };
  1170. PostProcess(node);
  1171. }
  1172. return node;
  1173. }
  1174. public T MarkEndIf<T>(T node) where T : SyntaxNode
  1175. {
  1176. if (node.Range != null || node.Location != null)
  1177. {
  1178. if (_extra.Loc.HasValue)
  1179. {
  1180. _state.MarkerStack.Pop();
  1181. _state.MarkerStack.Pop();
  1182. }
  1183. if (_extra.Range != null)
  1184. {
  1185. _state.MarkerStack.Pop();
  1186. }
  1187. }
  1188. else
  1189. {
  1190. MarkEnd(node);
  1191. }
  1192. return node;
  1193. }
  1194. public SyntaxNode PostProcess(SyntaxNode node)
  1195. {
  1196. if (_extra.Source != null)
  1197. {
  1198. node.Location.Source = _extra.Source;
  1199. }
  1200. return node;
  1201. }
  1202. public ArrayExpression CreateArrayExpression(IEnumerable<Expression> elements)
  1203. {
  1204. return new ArrayExpression
  1205. {
  1206. Type = SyntaxNodes.ArrayExpression,
  1207. Elements = elements
  1208. };
  1209. }
  1210. public AssignmentExpression CreateAssignmentExpression(string op, Expression left, Expression right)
  1211. {
  1212. return new AssignmentExpression
  1213. {
  1214. Type = SyntaxNodes.AssignmentExpression,
  1215. Operator = AssignmentExpression.ParseAssignmentOperator(op),
  1216. Left = left,
  1217. Right = right
  1218. };
  1219. }
  1220. public Expression CreateBinaryExpression(string op, Expression left, Expression right)
  1221. {
  1222. return (op == "||" || op == "&&")
  1223. ? (Expression)new LogicalExpression
  1224. {
  1225. Type = SyntaxNodes.LogicalExpression,
  1226. Operator = LogicalExpression.ParseLogicalOperator(op),
  1227. Left = left,
  1228. Right = right
  1229. }
  1230. : new BinaryExpression
  1231. {
  1232. Type = SyntaxNodes.BinaryExpression,
  1233. Operator = BinaryExpression.ParseBinaryOperator(op),
  1234. Left = left,
  1235. Right = right
  1236. };
  1237. }
  1238. public BlockStatement CreateBlockStatement(IEnumerable<Statement> body)
  1239. {
  1240. return new BlockStatement
  1241. {
  1242. Type = SyntaxNodes.BlockStatement,
  1243. Body = body
  1244. };
  1245. }
  1246. public BreakStatement CreateBreakStatement(Identifier label)
  1247. {
  1248. return new BreakStatement
  1249. {
  1250. Type = SyntaxNodes.BreakStatement,
  1251. Label = label
  1252. };
  1253. }
  1254. public CallExpression CreateCallExpression(Expression callee, IEnumerable<Expression> args)
  1255. {
  1256. return new CallExpression
  1257. {
  1258. Type = SyntaxNodes.CallExpression,
  1259. Callee = callee,
  1260. Arguments = args
  1261. };
  1262. }
  1263. public CatchClause CreateCatchClause(Identifier param, BlockStatement body)
  1264. {
  1265. return new CatchClause
  1266. {
  1267. Type = SyntaxNodes.CatchClause,
  1268. Param = param,
  1269. Body = body
  1270. };
  1271. }
  1272. public ConditionalExpression CreateConditionalExpression(Expression test, Expression consequent,
  1273. Expression alternate)
  1274. {
  1275. return new ConditionalExpression
  1276. {
  1277. Type = SyntaxNodes.ConditionalExpression,
  1278. Test = test,
  1279. Consequent = consequent,
  1280. Alternate = alternate
  1281. };
  1282. }
  1283. public ContinueStatement CreateContinueStatement(Identifier label)
  1284. {
  1285. return new ContinueStatement
  1286. {
  1287. Type = SyntaxNodes.ContinueStatement,
  1288. Label = label
  1289. };
  1290. }
  1291. public DebuggerStatement CreateDebuggerStatement()
  1292. {
  1293. return new DebuggerStatement
  1294. {
  1295. Type = SyntaxNodes.DebuggerStatement
  1296. };
  1297. }
  1298. public DoWhileStatement CreateDoWhileStatement(Statement body, Expression test)
  1299. {
  1300. return new DoWhileStatement
  1301. {
  1302. Type = SyntaxNodes.DoWhileStatement,
  1303. Body = body,
  1304. Test = test
  1305. };
  1306. }
  1307. public EmptyStatement CreateEmptyStatement()
  1308. {
  1309. return new EmptyStatement
  1310. {
  1311. Type = SyntaxNodes.EmptyStatement
  1312. };
  1313. }
  1314. public ExpressionStatement CreateExpressionStatement(Expression expression)
  1315. {
  1316. return new ExpressionStatement
  1317. {
  1318. Type = SyntaxNodes.ExpressionStatement,
  1319. Expression = expression
  1320. };
  1321. }
  1322. public ForStatement CreateForStatement(SyntaxNode init, Expression test, Expression update, Statement body)
  1323. {
  1324. return new ForStatement
  1325. {
  1326. Type = SyntaxNodes.ForStatement,
  1327. Init = init,
  1328. Test = test,
  1329. Update = update,
  1330. Body = body
  1331. };
  1332. }
  1333. public ForInStatement CreateForInStatement(SyntaxNode left, Expression right, Statement body)
  1334. {
  1335. return new ForInStatement
  1336. {
  1337. Type = SyntaxNodes.ForInStatement,
  1338. Left = left,
  1339. Right = right,
  1340. Body = body,
  1341. Each = false
  1342. };
  1343. }
  1344. public FunctionDeclaration CreateFunctionDeclaration(Identifier id, IEnumerable<Identifier> parameters,
  1345. IEnumerable<Expression> defaults, Statement body, bool strict)
  1346. {
  1347. var functionDeclaration = new FunctionDeclaration
  1348. {
  1349. Type = SyntaxNodes.FunctionDeclaration,
  1350. Id = id,
  1351. Parameters = parameters,
  1352. Defaults = defaults,
  1353. Body = body,
  1354. Strict = strict,
  1355. Rest = null,
  1356. Generator = false,
  1357. Expression = false,
  1358. VariableDeclarations = LeaveVariableScope(),
  1359. FunctionDeclarations = LeaveFunctionScope()
  1360. };
  1361. _functionScopes.Peek().FunctionDeclarations.Add(functionDeclaration);
  1362. return functionDeclaration;
  1363. }
  1364. public FunctionExpression CreateFunctionExpression(Identifier id, IEnumerable<Identifier> parameters,
  1365. IEnumerable<Expression> defaults, Statement body, bool strict)
  1366. {
  1367. return new FunctionExpression
  1368. {
  1369. Type = SyntaxNodes.FunctionExpression,
  1370. Id = id,
  1371. Parameters = parameters,
  1372. Defaults = defaults,
  1373. Body = body,
  1374. Strict = strict,
  1375. Rest = null,
  1376. Generator = false,
  1377. Expression = false,
  1378. VariableDeclarations = LeaveVariableScope(),
  1379. FunctionDeclarations = LeaveFunctionScope()
  1380. };
  1381. }
  1382. public Identifier CreateIdentifier(string name)
  1383. {
  1384. return new Identifier
  1385. {
  1386. Type = SyntaxNodes.Identifier,
  1387. Name = name
  1388. };
  1389. }
  1390. public IfStatement CreateIfStatement(Expression test, Statement consequent, Statement alternate)
  1391. {
  1392. return new IfStatement
  1393. {
  1394. Type = SyntaxNodes.IfStatement,
  1395. Test = test,
  1396. Consequent = consequent,
  1397. Alternate = alternate
  1398. };
  1399. }
  1400. public LabelledStatement CreateLabeledStatement(Identifier label, Statement body)
  1401. {
  1402. return new LabelledStatement
  1403. {
  1404. Type = SyntaxNodes.LabeledStatement,
  1405. Label = label,
  1406. Body = body
  1407. };
  1408. }
  1409. public Literal CreateLiteral(Token token)
  1410. {
  1411. if (token.Type == Tokens.RegularExpression)
  1412. {
  1413. return new Literal
  1414. {
  1415. Type = SyntaxNodes.RegularExpressionLiteral,
  1416. Value = token.Value,
  1417. Raw = _source.Slice(token.Range[0], token.Range[1])
  1418. };
  1419. }
  1420. return new Literal
  1421. {
  1422. Type = SyntaxNodes.Literal,
  1423. Value = token.Value,
  1424. Raw = _source.Slice(token.Range[0], token.Range[1])
  1425. };
  1426. }
  1427. public MemberExpression CreateMemberExpression(char accessor, Expression obj, Expression property)
  1428. {
  1429. return new MemberExpression
  1430. {
  1431. Type = SyntaxNodes.MemberExpression,
  1432. Computed = accessor == '[',
  1433. Object = obj,
  1434. Property = property
  1435. };
  1436. }
  1437. public NewExpression CreateNewExpression(Expression callee, IEnumerable<Expression> args)
  1438. {
  1439. return new NewExpression
  1440. {
  1441. Type = SyntaxNodes.NewExpression,
  1442. Callee = callee,
  1443. Arguments = args
  1444. };
  1445. }
  1446. public ObjectExpression CreateObjectExpression(IEnumerable<Property> properties)
  1447. {
  1448. return new ObjectExpression
  1449. {
  1450. Type = SyntaxNodes.ObjectExpression,
  1451. Properties = properties
  1452. };
  1453. }
  1454. public UpdateExpression CreatePostfixExpression(string op, Expression argument)
  1455. {
  1456. return new UpdateExpression
  1457. {
  1458. Type = SyntaxNodes.UpdateExpression,
  1459. Operator = UnaryExpression.ParseUnaryOperator(op),
  1460. Argument = argument,
  1461. Prefix = false
  1462. };
  1463. }
  1464. public Program CreateProgram(ICollection<Statement> body, bool strict)
  1465. {
  1466. return new Program
  1467. {
  1468. Type = SyntaxNodes.Program,
  1469. Body = body,
  1470. Strict = strict,
  1471. VariableDeclarations = LeaveVariableScope(),
  1472. FunctionDeclarations = LeaveFunctionScope()
  1473. };
  1474. }
  1475. public Property CreateProperty(PropertyKind kind, IPropertyKeyExpression key, Expression value)
  1476. {
  1477. return new Property
  1478. {
  1479. Type = SyntaxNodes.Property,
  1480. Key = key,
  1481. Value = value,
  1482. Kind = kind
  1483. };
  1484. }
  1485. public ReturnStatement CreateReturnStatement(Expression argument)
  1486. {
  1487. return new ReturnStatement
  1488. {
  1489. Type = SyntaxNodes.ReturnStatement,
  1490. Argument = argument
  1491. };
  1492. }
  1493. public SequenceExpression CreateSequenceExpression(IList<Expression> expressions)
  1494. {
  1495. return new SequenceExpression
  1496. {
  1497. Type = SyntaxNodes.SequenceExpression,
  1498. Expressions = expressions
  1499. };
  1500. }
  1501. public SwitchCase CreateSwitchCase(Expression test, IEnumerable<Statement> consequent)
  1502. {
  1503. return new SwitchCase
  1504. {
  1505. Type = SyntaxNodes.SwitchCase,
  1506. Test = test,
  1507. Consequent = consequent
  1508. };
  1509. }
  1510. public SwitchStatement CreateSwitchStatement(Expression discriminant, IEnumerable<SwitchCase> cases)
  1511. {
  1512. return new SwitchStatement
  1513. {
  1514. Type = SyntaxNodes.SwitchStatement,
  1515. Discriminant = discriminant,
  1516. Cases = cases
  1517. };
  1518. }
  1519. public ThisExpression CreateThisExpression()
  1520. {
  1521. return new ThisExpression
  1522. {
  1523. Type = SyntaxNodes.ThisExpression
  1524. };
  1525. }
  1526. public ThrowStatement CreateThrowStatement(Expression argument)
  1527. {
  1528. return new ThrowStatement
  1529. {
  1530. Type = SyntaxNodes.ThrowStatement,
  1531. Argument = argument
  1532. };
  1533. }
  1534. public TryStatement CreateTryStatement(Statement block, IEnumerable<Statement> guardedHandlers,
  1535. IEnumerable<CatchClause> handlers, Statement finalizer)
  1536. {
  1537. return new TryStatement
  1538. {
  1539. Type = SyntaxNodes.TryStatement,
  1540. Block = block,
  1541. GuardedHandlers = guardedHandlers,
  1542. Handlers = handlers,
  1543. Finalizer = finalizer
  1544. };
  1545. }
  1546. public UnaryExpression CreateUnaryExpression(string op, Expression argument)
  1547. {
  1548. if (op == "++" || op == "--")
  1549. {
  1550. return new UpdateExpression
  1551. {
  1552. Type = SyntaxNodes.UpdateExpression,
  1553. Operator = UnaryExpression.ParseUnaryOperator(op),
  1554. Argument = argument,
  1555. Prefix = true
  1556. };
  1557. }
  1558. return new UnaryExpression
  1559. {
  1560. Type = SyntaxNodes.UnaryExpression,
  1561. Operator = UnaryExpression.ParseUnaryOperator(op),
  1562. Argument = argument,
  1563. Prefix = true
  1564. };
  1565. }
  1566. public VariableDeclaration CreateVariableDeclaration(IEnumerable<VariableDeclarator> declarations, string kind)
  1567. {
  1568. var variableDeclaration = new VariableDeclaration
  1569. {
  1570. Type = SyntaxNodes.VariableDeclaration,
  1571. Declarations = declarations,
  1572. Kind = kind
  1573. };
  1574. _variableScopes.Peek().VariableDeclarations.Add(variableDeclaration);
  1575. return variableDeclaration;
  1576. }
  1577. public VariableDeclarator CreateVariableDeclarator(Identifier id, Expression init)
  1578. {
  1579. return new VariableDeclarator
  1580. {
  1581. Type = SyntaxNodes.VariableDeclarator,
  1582. Id = id,
  1583. Init = init
  1584. };
  1585. }
  1586. public WhileStatement CreateWhileStatement(Expression test, Statement body)
  1587. {
  1588. return new WhileStatement
  1589. {
  1590. Type = SyntaxNodes.WhileStatement,
  1591. Test = test,
  1592. Body = body
  1593. };
  1594. }
  1595. public WithStatement CreateWithStatement(Expression obj, Statement body)
  1596. {
  1597. return new WithStatement
  1598. {
  1599. Type = SyntaxNodes.WithStatement,
  1600. Object = obj,
  1601. Body = body
  1602. };
  1603. }
  1604. // Return true if there is a line terminator before the next token.
  1605. private bool PeekLineTerminator()
  1606. {
  1607. int pos = _index;
  1608. int line = _lineNumber;
  1609. int start = _lineStart;
  1610. SkipComment();
  1611. bool found = _lineNumber != line;
  1612. _index = pos;
  1613. _lineNumber = line;
  1614. _lineStart = start;
  1615. return found;
  1616. }
  1617. // Throw an exception
  1618. private void ThrowError(Token token, string messageFormat, params object[] arguments)
  1619. {
  1620. ParserException exception;
  1621. string msg = String.Format(messageFormat, arguments);
  1622. if (token != null && token.LineNumber.HasValue)
  1623. {
  1624. exception = new ParserException("Line " + token.LineNumber + ": " + msg)
  1625. {
  1626. Index = token.Range[0],
  1627. LineNumber = token.LineNumber.Value,
  1628. Column = token.Range[0] - _lineStart + 1,
  1629. Source = _extra.Source
  1630. };
  1631. }
  1632. else
  1633. {
  1634. exception = new ParserException("Line " + _lineNumber + ": " + msg)
  1635. {
  1636. Index = _index,
  1637. LineNumber = _lineNumber,
  1638. Column = _index - _lineStart + 1,
  1639. Source = _extra.Source
  1640. };
  1641. }
  1642. exception.Description = msg;
  1643. throw exception;
  1644. }
  1645. private void ThrowErrorTolerant(Token token, string messageFormat, params object[] arguments)
  1646. {
  1647. try
  1648. {
  1649. ThrowError(token, messageFormat, arguments);
  1650. }
  1651. catch (Exception e)
  1652. {
  1653. if (_extra.Errors != null)
  1654. {
  1655. _extra.Errors.Add(new ParserException(e.Message)
  1656. {
  1657. Source = _extra.Source
  1658. });
  1659. }
  1660. else
  1661. {
  1662. throw;
  1663. }
  1664. }
  1665. }
  1666. // Throw an exception because of the token.
  1667. private void ThrowUnexpected(Token token)
  1668. {
  1669. if (token.Type == Tokens.EOF)
  1670. {
  1671. ThrowError(token, Messages.UnexpectedEOS);
  1672. }
  1673. if (token.Type == Tokens.NumericLiteral)
  1674. {
  1675. ThrowError(token, Messages.UnexpectedNumber);
  1676. }
  1677. if (token.Type == Tokens.StringLiteral)
  1678. {
  1679. ThrowError(token, Messages.UnexpectedString);
  1680. }
  1681. if (token.Type == Tokens.Identifier)
  1682. {
  1683. ThrowError(token, Messages.UnexpectedIdentifier);
  1684. }
  1685. if (token.Type == Tokens.Keyword)
  1686. {
  1687. if (IsFutureReservedWord(token.Value as string))
  1688. {
  1689. ThrowError(token, Messages.UnexpectedReserved);
  1690. }
  1691. else if (_strict && IsStrictModeReservedWord(token.Value as string))
  1692. {
  1693. ThrowErrorTolerant(token, Messages.StrictReservedWord);
  1694. return;
  1695. }
  1696. ThrowError(token, Messages.UnexpectedToken, token.Value as string);
  1697. }
  1698. // BooleanLiteral, NullLiteral, or Punctuator.
  1699. ThrowError(token, Messages.UnexpectedToken, token.Value as string);
  1700. }
  1701. // Expect the next token to match the specified punctuator.
  1702. // If not, an exception will be thrown.
  1703. private void Expect(string value)
  1704. {
  1705. Token token = Lex();
  1706. if (token.Type != Tokens.Punctuator || !value.Equals(token.Value))
  1707. {
  1708. ThrowUnexpected(token);
  1709. }
  1710. }
  1711. // Expect the next token to match the specified keyword.
  1712. // If not, an exception will be thrown.
  1713. private void ExpectKeyword(string keyword)
  1714. {
  1715. Token token = Lex();
  1716. if (token.Type != Tokens.Keyword || !keyword.Equals(token.Value))
  1717. {
  1718. ThrowUnexpected(token);
  1719. }
  1720. }
  1721. // Return true if the next token matches the specified punctuator.
  1722. private bool Match(string value)
  1723. {
  1724. return _lookahead.Type == Tokens.Punctuator && value.Equals(_lookahead.Value);
  1725. }
  1726. // Return true if the next token matches the specified keyword
  1727. private bool MatchKeyword(object keyword)
  1728. {
  1729. return _lookahead.Type == Tokens.Keyword && keyword.Equals(_lookahead.Value);
  1730. }
  1731. // Return true if the next token is an assignment operator
  1732. private bool MatchAssign()
  1733. {
  1734. if (_lookahead.Type != Tokens.Punctuator)
  1735. {
  1736. return false;
  1737. }
  1738. var op = _lookahead.Value as string;
  1739. return op == "=" ||
  1740. op == "*=" ||
  1741. op == "/=" ||
  1742. op == "%=" ||
  1743. op == "+=" ||
  1744. op == "-=" ||
  1745. op == "<<=" ||
  1746. op == ">>=" ||
  1747. op == ">>>=" ||
  1748. op == "&=" ||
  1749. op == "^=" ||
  1750. op == "|=";
  1751. }
  1752. private void ConsumeSemicolon()
  1753. {
  1754. // Catch the very common case first: immediately a semicolon (char #59).
  1755. if (_source.CharCodeAt(_index) == 59)
  1756. {
  1757. Lex();
  1758. return;
  1759. }
  1760. int line = _lineNumber;
  1761. SkipComment();
  1762. if (_lineNumber != line)
  1763. {
  1764. return;
  1765. }
  1766. if (Match(";"))
  1767. {
  1768. Lex();
  1769. return;
  1770. }
  1771. if (_lookahead.Type != Tokens.EOF && !Match("}"))
  1772. {
  1773. ThrowUnexpected(_lookahead);
  1774. }
  1775. }
  1776. // Return true if provided expression is LeftHandSideExpression
  1777. private bool isLeftHandSide(Expression expr)
  1778. {
  1779. return expr.Type == SyntaxNodes.Identifier || expr.Type == SyntaxNodes.MemberExpression;
  1780. }
  1781. // 11.1.4 Array Initialiser
  1782. private ArrayExpression ParseArrayInitialiser()
  1783. {
  1784. var elements = new List<Expression>();
  1785. Expect("[");
  1786. while (!Match("]"))
  1787. {
  1788. if (Match(","))
  1789. {
  1790. Lex();
  1791. elements.Add(null);
  1792. }
  1793. else
  1794. {
  1795. elements.Add(ParseAssignmentExpression());
  1796. if (!Match("]"))
  1797. {
  1798. Expect(",");
  1799. }
  1800. }
  1801. }
  1802. Expect("]");
  1803. return CreateArrayExpression(elements);
  1804. }
  1805. // 11.1.5 Object Initialiser
  1806. private FunctionExpression ParsePropertyFunction(Identifier[] parameters, Token first = null)
  1807. {
  1808. EnterVariableScope();
  1809. EnterFunctionScope();
  1810. bool previousStrict = _strict;
  1811. MarkStart();
  1812. Statement body = ParseFunctionSourceElements();
  1813. if (first != null && _strict && IsRestrictedWord(parameters[0].Name))
  1814. {
  1815. ThrowErrorTolerant(first, Messages.StrictParamName);
  1816. }
  1817. bool functionStrict = _strict;
  1818. _strict = previousStrict;
  1819. return MarkEnd(CreateFunctionExpression(null, parameters, new Expression[0], body, functionStrict));
  1820. }
  1821. private IPropertyKeyExpression ParseObjectPropertyKey()
  1822. {
  1823. MarkStart();
  1824. Token token = Lex();
  1825. // Note: This function is called only from parseObjectProperty(), where
  1826. // EOF and Punctuator tokens are already filtered out.
  1827. if (token.Type == Tokens.StringLiteral || token.Type == Tokens.NumericLiteral)
  1828. {
  1829. if (_strict && token.Octal)
  1830. {
  1831. ThrowErrorTolerant(token, Messages.StrictOctalLiteral);
  1832. }
  1833. return MarkEnd(CreateLiteral(token));
  1834. }
  1835. return MarkEnd(CreateIdentifier((string) token.Value));
  1836. }
  1837. private Property ParseObjectProperty()
  1838. {
  1839. Expression value;
  1840. Token token = _lookahead;
  1841. MarkStart();
  1842. if (token.Type == Tokens.Identifier)
  1843. {
  1844. IPropertyKeyExpression id = ParseObjectPropertyKey();
  1845. // Property Assignment: Getter and Setter.
  1846. if ("get".Equals(token.Value) && !Match(":"))
  1847. {
  1848. var key = ParseObjectPropertyKey();
  1849. Expect("(");
  1850. Expect(")");
  1851. value = ParsePropertyFunction(new Identifier[0]);
  1852. return MarkEnd(CreateProperty(PropertyKind.Get, key, value));
  1853. }
  1854. if ("set".Equals(token.Value) && !Match(":"))
  1855. {
  1856. var key = ParseObjectPropertyKey();
  1857. Expect("(");
  1858. token = _lookahead;
  1859. if (token.Type != Tokens.Identifier)
  1860. {
  1861. Expect(")");
  1862. ThrowErrorTolerant(token, Messages.UnexpectedToken, (string) token.Value);
  1863. value = ParsePropertyFunction(new Identifier[0]);
  1864. }
  1865. else
  1866. {
  1867. var param = new[] {ParseVariableIdentifier()};
  1868. Expect(")");
  1869. value = ParsePropertyFunction(param, token);
  1870. }
  1871. return MarkEnd(CreateProperty(PropertyKind.Set, key, value));
  1872. }
  1873. Expect(":");
  1874. value = ParseAssignmentExpression();
  1875. return MarkEnd(CreateProperty(PropertyKind.Data, id, value));
  1876. }
  1877. if (token.Type == Tokens.EOF || token.Type == Tokens.Punctuator)
  1878. {
  1879. ThrowUnexpected(token);
  1880. return null; // can't be reached
  1881. }
  1882. else
  1883. {
  1884. IPropertyKeyExpression key = ParseObjectPropertyKey();
  1885. Expect(":");
  1886. value = ParseAssignmentExpression();
  1887. return MarkEnd(CreateProperty(PropertyKind.Data, key, value));
  1888. }
  1889. }
  1890. private ObjectExpression ParseObjectInitialiser()
  1891. {
  1892. var properties = new List<Property>();
  1893. var map = new Dictionary<string, PropertyKind>();
  1894. Expect("{");
  1895. while (!Match("}"))
  1896. {
  1897. Property property = ParseObjectProperty();
  1898. string name = property.Key.GetKey();
  1899. PropertyKind kind = property.Kind;
  1900. string key = "$" + name;
  1901. if (map.ContainsKey(key))
  1902. {
  1903. if (map[key] == PropertyKind.Data)
  1904. {
  1905. if (_strict && kind == PropertyKind.Data)
  1906. {
  1907. ThrowErrorTolerant(Token.Empty, Messages.StrictDuplicateProperty);
  1908. }
  1909. else if (kind != PropertyKind.Data)
  1910. {
  1911. ThrowErrorTolerant(Token.Empty, Messages.AccessorDataProperty);
  1912. }
  1913. }
  1914. else
  1915. {
  1916. if (kind == PropertyKind.Data)
  1917. {
  1918. ThrowErrorTolerant(Token.Empty, Messages.AccessorDataProperty);
  1919. }
  1920. else if ((map[key] & kind) == kind)
  1921. {
  1922. ThrowErrorTolerant(Token.Empty, Messages.AccessorGetSet);
  1923. }
  1924. }
  1925. map[key] |= kind;
  1926. }
  1927. else
  1928. {
  1929. map[key] = kind;
  1930. }
  1931. properties.Add(property);
  1932. if (!Match("}"))
  1933. {
  1934. Expect(",");
  1935. }
  1936. }
  1937. Expect("}");
  1938. return CreateObjectExpression(properties);
  1939. }
  1940. // 11.1.6 The Grouping Operator
  1941. private Expression ParseGroupExpression()
  1942. {
  1943. Expect("(");
  1944. Expression expr = ParseExpression();
  1945. Expect(")");
  1946. return expr;
  1947. }
  1948. // 11.1 Primary Expressions
  1949. private Expression ParsePrimaryExpression()
  1950. {
  1951. Expression expr = null;
  1952. if (Match("("))
  1953. {
  1954. return ParseGroupExpression();
  1955. }
  1956. Tokens type = _lookahead.Type;
  1957. MarkStart();
  1958. if (type == Tokens.Identifier)
  1959. {
  1960. expr = CreateIdentifier((string) Lex().Value);
  1961. }
  1962. else if (type == Tokens.StringLiteral || type == Tokens.NumericLiteral)
  1963. {
  1964. if (_strict && _lookahead.Octal)
  1965. {
  1966. ThrowErrorTolerant(_lookahead, Messages.StrictOctalLiteral);
  1967. }
  1968. expr = CreateLiteral(Lex());
  1969. }
  1970. else if (type == Tokens.Keyword)
  1971. {
  1972. if (MatchKeyword("this"))
  1973. {
  1974. Lex();
  1975. expr = CreateThisExpression();
  1976. }
  1977. else if (MatchKeyword("function"))
  1978. {
  1979. expr = ParseFunctionExpression();
  1980. }
  1981. }
  1982. else if (type == Tokens.BooleanLiteral)
  1983. {
  1984. Token token = Lex();
  1985. token.Value = ("true".Equals(token.Value));
  1986. expr = CreateLiteral(token);
  1987. }
  1988. else if (type == Tokens.NullLiteral)
  1989. {
  1990. Token token = Lex();
  1991. token.Value = null;
  1992. expr = CreateLiteral(token);
  1993. }
  1994. else if (Match("["))
  1995. {
  1996. expr = ParseArrayInitialiser();
  1997. }
  1998. else if (Match("{"))
  1999. {
  2000. expr = ParseObjectInitialiser();
  2001. }
  2002. else if (Match("/") || Match("/="))
  2003. {
  2004. expr = CreateLiteral(_extra.Tokens != null ? CollectRegex() : ScanRegExp());
  2005. }
  2006. if (expr != null)
  2007. {
  2008. return MarkEnd(expr);
  2009. }
  2010. ThrowUnexpected(Lex());
  2011. return null; // can't be reached
  2012. }
  2013. // 11.2 Left-Hand-Side Expressions
  2014. private IEnumerable<Expression> ParseArguments()
  2015. {
  2016. var args = new List<Expression>();
  2017. Expect("(");
  2018. if (!Match(")"))
  2019. {
  2020. while (_index < _length)
  2021. {
  2022. args.Add(ParseAssignmentExpression());
  2023. if (Match(")"))
  2024. {
  2025. break;
  2026. }
  2027. Expect(",");
  2028. }
  2029. }
  2030. Expect(")");
  2031. return args;
  2032. }
  2033. private Identifier ParseNonComputedProperty()
  2034. {
  2035. MarkStart();
  2036. Token token = Lex();
  2037. if (!IsIdentifierName(token))
  2038. {
  2039. ThrowUnexpected(token);
  2040. }
  2041. return MarkEnd(CreateIdentifier((string) token.Value));
  2042. }
  2043. private Identifier ParseNonComputedMember()
  2044. {
  2045. Expect(".");
  2046. return ParseNonComputedProperty();
  2047. }
  2048. private Expression ParseComputedMember()
  2049. {
  2050. Expect("[");
  2051. Expression expr = ParseExpression();
  2052. Expect("]");
  2053. return expr;
  2054. }
  2055. private NewExpression ParseNewExpression()
  2056. {
  2057. MarkStart();
  2058. ExpectKeyword("new");
  2059. Expression callee = ParseLeftHandSideExpression();
  2060. IEnumerable<Expression> args = Match("(") ? ParseArguments() : new AssignmentExpression[0];
  2061. return MarkEnd(CreateNewExpression(callee, args));
  2062. }
  2063. private Expression ParseLeftHandSideExpressionAllowCall()
  2064. {
  2065. LocationMarker marker = CreateLocationMarker();
  2066. var previousAllowIn = _state.AllowIn;
  2067. _state.AllowIn = true;
  2068. Expression expr = MatchKeyword("new") ? ParseNewExpression() : ParsePrimaryExpression();
  2069. _state.AllowIn = previousAllowIn;
  2070. while (Match(".") || Match("[") || Match("("))
  2071. {
  2072. if (Match("("))
  2073. {
  2074. IEnumerable<Expression> args = ParseArguments();
  2075. expr = CreateCallExpression(expr, args);
  2076. }
  2077. else if (Match("["))
  2078. {
  2079. Expression property = ParseComputedMember();
  2080. expr = CreateMemberExpression('[', expr, property);
  2081. }
  2082. else
  2083. {
  2084. Identifier property = ParseNonComputedMember();
  2085. expr = CreateMemberExpression('.', expr, property);
  2086. }
  2087. if (marker != null)
  2088. {
  2089. marker.End(_index, _lineNumber, _lineStart);
  2090. marker.Apply(expr, _extra, PostProcess);
  2091. }
  2092. }
  2093. return expr;
  2094. }
  2095. private Expression ParseLeftHandSideExpression()
  2096. {
  2097. LocationMarker marker = CreateLocationMarker();
  2098. var previousAllowIn = _state.AllowIn;
  2099. Expression expr = MatchKeyword("new") ? ParseNewExpression() : ParsePrimaryExpression();
  2100. _state.AllowIn = previousAllowIn;
  2101. while (Match(".") || Match("["))
  2102. {
  2103. if (Match("["))
  2104. {
  2105. Expression property = ParseComputedMember();
  2106. expr = CreateMemberExpression('[', expr, property);
  2107. }
  2108. else
  2109. {
  2110. Identifier property = ParseNonComputedMember();
  2111. expr = CreateMemberExpression('.', expr, property);
  2112. }
  2113. if (marker != null)
  2114. {
  2115. marker.End(_index, _lineNumber, _lineStart);
  2116. marker.Apply(expr, _extra, PostProcess);
  2117. }
  2118. }
  2119. return expr;
  2120. }
  2121. // 11.3 Postfix Expressions
  2122. private Expression ParsePostfixExpression()
  2123. {
  2124. MarkStart();
  2125. Expression expr = ParseLeftHandSideExpressionAllowCall();
  2126. if (_lookahead.Type == Tokens.Punctuator)
  2127. {
  2128. if ((Match("++") || Match("--")) && !PeekLineTerminator())
  2129. {
  2130. // 11.3.1, 11.3.2
  2131. if (_strict && expr.Type == SyntaxNodes.Identifier && IsRestrictedWord(((Identifier) expr).Name))
  2132. {
  2133. ThrowErrorTolerant(Token.Empty, Messages.StrictLHSPostfix);
  2134. }
  2135. if (!isLeftHandSide(expr))
  2136. {
  2137. ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInAssignment);
  2138. }
  2139. Token token = Lex();
  2140. expr = CreatePostfixExpression((string) token.Value, expr);
  2141. }
  2142. }
  2143. return MarkEndIf(expr);
  2144. }
  2145. // 11.4 Unary Operators
  2146. private Expression ParseUnaryExpression()
  2147. {
  2148. Expression expr;
  2149. MarkStart();
  2150. if (_lookahead.Type != Tokens.Punctuator && _lookahead.Type != Tokens.Keyword)
  2151. {
  2152. expr = ParsePostfixExpression();
  2153. }
  2154. else if (Match("++") || Match("--"))
  2155. {
  2156. Token token = Lex();
  2157. expr = ParseUnaryExpression();
  2158. // 11.4.4, 11.4.5
  2159. if (_strict && expr.Type == SyntaxNodes.Identifier && IsRestrictedWord(((Identifier) expr).Name))
  2160. {
  2161. ThrowErrorTolerant(Token.Empty, Messages.StrictLHSPrefix);
  2162. }
  2163. if (!isLeftHandSide(expr))
  2164. {
  2165. ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInAssignment);
  2166. }
  2167. expr = CreateUnaryExpression((string) token.Value, expr);
  2168. }
  2169. else if (Match("+") || Match("-") || Match("~") || Match("!"))
  2170. {
  2171. Token token = Lex();
  2172. expr = ParseUnaryExpression();
  2173. expr = CreateUnaryExpression((string) token.Value, expr);
  2174. }
  2175. else if (MatchKeyword("delete") || MatchKeyword("void") || MatchKeyword("typeof"))
  2176. {
  2177. Token token = Lex();
  2178. expr = ParseUnaryExpression();
  2179. UnaryExpression unaryExpr = CreateUnaryExpression((string) token.Value, expr);
  2180. if (_strict && unaryExpr.Operator == UnaryOperator.Delete && unaryExpr.Argument.Type == SyntaxNodes.Identifier)
  2181. {
  2182. ThrowErrorTolerant(Token.Empty, Messages.StrictDelete);
  2183. }
  2184. expr = unaryExpr;
  2185. }
  2186. else
  2187. {
  2188. expr = ParsePostfixExpression();
  2189. }
  2190. return MarkEndIf(expr);
  2191. }
  2192. private int binaryPrecedence(Token token, bool allowIn)
  2193. {
  2194. int prec = 0;
  2195. if (token.Type != Tokens.Punctuator && token.Type != Tokens.Keyword)
  2196. {
  2197. return 0;
  2198. }
  2199. switch ((string) token.Value)
  2200. {
  2201. case "||":
  2202. prec = 1;
  2203. break;
  2204. case "&&":
  2205. prec = 2;
  2206. break;
  2207. case "|":
  2208. prec = 3;
  2209. break;
  2210. case "^":
  2211. prec = 4;
  2212. break;
  2213. case "&":
  2214. prec = 5;
  2215. break;
  2216. case "==":
  2217. case "!=":
  2218. case "===":
  2219. case "!==":
  2220. prec = 6;
  2221. break;
  2222. case "<":
  2223. case ">":
  2224. case "<=":
  2225. case ">=":
  2226. case "instanceof":
  2227. prec = 7;
  2228. break;
  2229. case "in":
  2230. prec = allowIn ? 7 : 0;
  2231. break;
  2232. case "<<":
  2233. case ">>":
  2234. case ">>>":
  2235. prec = 8;
  2236. break;
  2237. case "+":
  2238. case "-":
  2239. prec = 9;
  2240. break;
  2241. case "*":
  2242. case "/":
  2243. case "%":
  2244. prec = 11;
  2245. break;
  2246. }
  2247. return prec;
  2248. }
  2249. // 11.5 Multiplicative Operators
  2250. // 11.6 Additive Operators
  2251. // 11.7 Bitwise Shift Operators
  2252. // 11.8 Relational Operators
  2253. // 11.9 Equality Operators
  2254. // 11.10 Binary Bitwise Operators
  2255. // 11.11 Binary Logical Operators
  2256. private Expression ParseBinaryExpression()
  2257. {
  2258. Expression expr;
  2259. LocationMarker marker = CreateLocationMarker();
  2260. Expression left = ParseUnaryExpression();
  2261. Token token = _lookahead;
  2262. int prec = binaryPrecedence(token, _state.AllowIn);
  2263. if (prec == 0)
  2264. {
  2265. return left;
  2266. }
  2267. token.Precedence = prec;
  2268. Lex();
  2269. var markers = new Stack<LocationMarker>( new [] {marker, CreateLocationMarker()});
  2270. Expression right = ParseUnaryExpression();
  2271. var stack = new List<object>( new object[] {left, token, right});
  2272. while ((prec = binaryPrecedence(_lookahead, _state.AllowIn)) > 0)
  2273. {
  2274. // Reduce: make a binary expression from the three topmost entries.
  2275. while ((stack.Count > 2) && (prec <= ((Token) stack[stack.Count - 2]).Precedence))
  2276. {
  2277. right = (Expression) stack.Pop();
  2278. var op = (string) ((Token) stack.Pop()).Value;
  2279. left = (Expression) stack.Pop();
  2280. expr = CreateBinaryExpression(op, left, right);
  2281. markers.Pop();
  2282. marker = markers.Pop();
  2283. if (marker != null)
  2284. {
  2285. marker.End(_index, _lineNumber, _lineStart);
  2286. marker.Apply(expr, _extra, PostProcess);
  2287. }
  2288. stack.Push(expr);
  2289. markers.Push(marker);
  2290. }
  2291. // Shift.
  2292. token = Lex();
  2293. token.Precedence = prec;
  2294. stack.Push(token);
  2295. markers.Push(CreateLocationMarker());
  2296. expr = ParseUnaryExpression();
  2297. stack.Push(expr);
  2298. }
  2299. // Final reduce to clean-up the stack.
  2300. int i = stack.Count - 1;
  2301. expr = (Expression) stack[i];
  2302. markers.Pop();
  2303. while (i > 1)
  2304. {
  2305. expr = CreateBinaryExpression((string) ((Token) stack[i - 1]).Value, (Expression) stack[i - 2], expr);
  2306. i -= 2;
  2307. marker = markers.Pop();
  2308. if (marker != null)
  2309. {
  2310. marker.End(_index, _lineNumber, _lineStart);
  2311. marker.Apply(expr, _extra, PostProcess);
  2312. }
  2313. }
  2314. return expr;
  2315. }
  2316. // 11.12 Conditional Operator
  2317. private Expression ParseConditionalExpression()
  2318. {
  2319. MarkStart();
  2320. Expression expr = ParseBinaryExpression();
  2321. if (Match("?"))
  2322. {
  2323. Lex();
  2324. bool previousAllowIn = _state.AllowIn;
  2325. _state.AllowIn = true;
  2326. Expression consequent = ParseAssignmentExpression();
  2327. _state.AllowIn = previousAllowIn;
  2328. Expect(":");
  2329. Expression alternate = ParseAssignmentExpression();
  2330. expr = MarkEnd(CreateConditionalExpression(expr, consequent, alternate));
  2331. }
  2332. else
  2333. {
  2334. MarkEnd(new SyntaxNode());
  2335. }
  2336. return expr;
  2337. }
  2338. // 11.13 Assignment Operators
  2339. private Expression ParseAssignmentExpression()
  2340. {
  2341. Expression left;
  2342. Token token = _lookahead;
  2343. MarkStart();
  2344. Expression expr = left = ParseConditionalExpression();
  2345. if (MatchAssign())
  2346. {
  2347. // LeftHandSideExpression
  2348. // Ignore issue as it needs to throw a ReferenceError instead of a SyntaxError
  2349. //if (!isLeftHandSide(left))
  2350. //{
  2351. // ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInAssignment);
  2352. //}
  2353. // 11.13.1
  2354. if (_strict && left.Type == SyntaxNodes.Identifier && IsRestrictedWord(((Identifier) left).Name))
  2355. {
  2356. ThrowErrorTolerant(token, Messages.StrictLHSAssignment);
  2357. }
  2358. token = Lex();
  2359. Expression right = ParseAssignmentExpression();
  2360. expr = CreateAssignmentExpression((string) token.Value, left, right);
  2361. }
  2362. return MarkEndIf(expr);
  2363. }
  2364. // 11.14 Comma Operator
  2365. private Expression ParseExpression()
  2366. {
  2367. MarkStart();
  2368. Expression expr = ParseAssignmentExpression();
  2369. if (Match(","))
  2370. {
  2371. expr = CreateSequenceExpression(new List<Expression> {expr});
  2372. while (_index < _length)
  2373. {
  2374. if (!Match(","))
  2375. {
  2376. break;
  2377. }
  2378. Lex();
  2379. ((SequenceExpression) expr).Expressions.Add(ParseAssignmentExpression());
  2380. }
  2381. }
  2382. return MarkEndIf(expr);
  2383. }
  2384. // 12.1 Block
  2385. private IEnumerable<Statement> ParseStatementList()
  2386. {
  2387. var list = new List<Statement>();
  2388. while (_index < _length)
  2389. {
  2390. if (Match("}"))
  2391. {
  2392. break;
  2393. }
  2394. Statement statement = ParseSourceElement();
  2395. if (statement == null)
  2396. {
  2397. break;
  2398. }
  2399. list.Add(statement);
  2400. }
  2401. return list;
  2402. }
  2403. private BlockStatement ParseBlock()
  2404. {
  2405. MarkStart();
  2406. Expect("{");
  2407. IEnumerable<Statement> block = ParseStatementList();
  2408. Expect("}");
  2409. return MarkEnd(CreateBlockStatement(block));
  2410. }
  2411. // 12.2 Variable Statement
  2412. private Identifier ParseVariableIdentifier()
  2413. {
  2414. MarkStart();
  2415. Token token = Lex();
  2416. if (token.Type != Tokens.Identifier)
  2417. {
  2418. ThrowUnexpected(token);
  2419. }
  2420. return MarkEnd(CreateIdentifier((string) token.Value));
  2421. }
  2422. private VariableDeclarator ParseVariableDeclaration(string kind)
  2423. {
  2424. Expression init = null;
  2425. MarkStart();
  2426. Identifier id = ParseVariableIdentifier();
  2427. // 12.2.1
  2428. if (_strict && IsRestrictedWord(id.Name))
  2429. {
  2430. ThrowErrorTolerant(Token.Empty, Messages.StrictVarName);
  2431. }
  2432. if ("const".Equals(kind))
  2433. {
  2434. Expect("=");
  2435. init = ParseAssignmentExpression();
  2436. }
  2437. else if (Match("="))
  2438. {
  2439. Lex();
  2440. init = ParseAssignmentExpression();
  2441. }
  2442. return MarkEnd(CreateVariableDeclarator(id, init));
  2443. }
  2444. private IEnumerable<VariableDeclarator> ParseVariableDeclarationList(string kind)
  2445. {
  2446. var list = new List<VariableDeclarator>();
  2447. do
  2448. {
  2449. list.Add(ParseVariableDeclaration(kind));
  2450. if (!Match(","))
  2451. {
  2452. break;
  2453. }
  2454. Lex();
  2455. } while (_index < _length);
  2456. return list;
  2457. }
  2458. private VariableDeclaration ParseVariableStatement()
  2459. {
  2460. ExpectKeyword("var");
  2461. IEnumerable<VariableDeclarator> declarations = ParseVariableDeclarationList(null);
  2462. ConsumeSemicolon();
  2463. return CreateVariableDeclaration(declarations, "var");
  2464. }
  2465. // kind may be `const` or `let`
  2466. // Both are experimental and not in the specification yet.
  2467. // see http://wiki.ecmascript.org/doku.php?id=harmony:const
  2468. // and http://wiki.ecmascript.org/doku.php?id=harmony:let
  2469. private VariableDeclaration ParseConstLetDeclaration(string kind)
  2470. {
  2471. 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. MarkStart();
  2748. if (MatchKeyword("default"))
  2749. {
  2750. Lex();
  2751. test = null;
  2752. }
  2753. else
  2754. {
  2755. ExpectKeyword("case");
  2756. test = ParseExpression();
  2757. }
  2758. Expect(":");
  2759. while (_index < _length)
  2760. {
  2761. if (Match("}") || MatchKeyword("default") || MatchKeyword("case"))
  2762. {
  2763. break;
  2764. }
  2765. Statement statement = ParseStatement();
  2766. consequent.Add(statement);
  2767. }
  2768. return MarkEnd(CreateSwitchCase(test, consequent));
  2769. }
  2770. private SwitchStatement ParseSwitchStatement()
  2771. {
  2772. ExpectKeyword("switch");
  2773. Expect("(");
  2774. Expression discriminant = ParseExpression();
  2775. Expect(")");
  2776. Expect("{");
  2777. var cases = new List<SwitchCase>();
  2778. if (Match("}"))
  2779. {
  2780. Lex();
  2781. return CreateSwitchStatement(discriminant, cases);
  2782. }
  2783. bool oldInSwitch = _state.InSwitch;
  2784. _state.InSwitch = true;
  2785. bool defaultFound = false;
  2786. while (_index < _length)
  2787. {
  2788. if (Match("}"))
  2789. {
  2790. break;
  2791. }
  2792. SwitchCase clause = ParseSwitchCase();
  2793. if (clause.Test == null)
  2794. {
  2795. if (defaultFound)
  2796. {
  2797. ThrowError(Token.Empty, Messages.MultipleDefaultsInSwitch);
  2798. }
  2799. defaultFound = true;
  2800. }
  2801. cases.Add(clause);
  2802. }
  2803. _state.InSwitch = oldInSwitch;
  2804. Expect("}");
  2805. return CreateSwitchStatement(discriminant, cases);
  2806. }
  2807. // 12.13 The throw statement
  2808. private ThrowStatement ParseThrowStatement()
  2809. {
  2810. ExpectKeyword("throw");
  2811. if (PeekLineTerminator())
  2812. {
  2813. ThrowError(Token.Empty, Messages.NewlineAfterThrow);
  2814. }
  2815. Expression argument = ParseExpression();
  2816. ConsumeSemicolon();
  2817. return CreateThrowStatement(argument);
  2818. }
  2819. // 12.14 The try statement
  2820. private CatchClause ParseCatchClause()
  2821. {
  2822. MarkStart();
  2823. ExpectKeyword("catch");
  2824. Expect("(");
  2825. if (Match(")"))
  2826. {
  2827. ThrowUnexpected(_lookahead);
  2828. }
  2829. Identifier param = ParseVariableIdentifier();
  2830. // 12.14.1
  2831. if (_strict && IsRestrictedWord(param.Name))
  2832. {
  2833. ThrowErrorTolerant(Token.Empty, Messages.StrictCatchVariable);
  2834. }
  2835. Expect(")");
  2836. BlockStatement body = ParseBlock();
  2837. return MarkEnd(CreateCatchClause(param, body));
  2838. }
  2839. private TryStatement ParseTryStatement()
  2840. {
  2841. var handlers = new List<CatchClause>();
  2842. Statement finalizer = null;
  2843. ExpectKeyword("try");
  2844. BlockStatement block = ParseBlock();
  2845. if (MatchKeyword("catch"))
  2846. {
  2847. handlers.Add(ParseCatchClause());
  2848. }
  2849. if (MatchKeyword("finally"))
  2850. {
  2851. Lex();
  2852. finalizer = ParseBlock();
  2853. }
  2854. if (handlers.Count == 0 && finalizer == null)
  2855. {
  2856. ThrowError(Token.Empty, Messages.NoCatchOrFinally);
  2857. }
  2858. return CreateTryStatement(block, new Statement[0], handlers, finalizer);
  2859. }
  2860. // 12.15 The debugger statement
  2861. private DebuggerStatement ParseDebuggerStatement()
  2862. {
  2863. ExpectKeyword("debugger");
  2864. ConsumeSemicolon();
  2865. return CreateDebuggerStatement();
  2866. }
  2867. // 12 Statements
  2868. private Statement ParseStatement()
  2869. {
  2870. Tokens type = _lookahead.Type;
  2871. if (type == Tokens.EOF)
  2872. {
  2873. ThrowUnexpected(_lookahead);
  2874. }
  2875. MarkStart();
  2876. if (type == Tokens.Punctuator)
  2877. {
  2878. switch ((string) _lookahead.Value)
  2879. {
  2880. case ";":
  2881. return MarkEnd(ParseEmptyStatement());
  2882. case "{":
  2883. return MarkEnd(ParseBlock());
  2884. case "(":
  2885. return MarkEnd(ParseExpressionStatement());
  2886. }
  2887. }
  2888. if (type == Tokens.Keyword)
  2889. {
  2890. switch ((string) _lookahead.Value)
  2891. {
  2892. case "break":
  2893. return MarkEnd(ParseBreakStatement());
  2894. case "continue":
  2895. return MarkEnd(ParseContinueStatement());
  2896. case "debugger":
  2897. return MarkEnd(ParseDebuggerStatement());
  2898. case "do":
  2899. return MarkEnd(ParseDoWhileStatement());
  2900. case "for":
  2901. return MarkEnd(ParseForStatement());
  2902. case "function":
  2903. return MarkEnd(ParseFunctionDeclaration());
  2904. case "if":
  2905. return MarkEnd(ParseIfStatement());
  2906. case "return":
  2907. return MarkEnd(ParseReturnStatement());
  2908. case "switch":
  2909. return MarkEnd(ParseSwitchStatement());
  2910. case "throw":
  2911. return MarkEnd(ParseThrowStatement());
  2912. case "try":
  2913. return MarkEnd(ParseTryStatement());
  2914. case "var":
  2915. return MarkEnd(ParseVariableStatement());
  2916. case "while":
  2917. return MarkEnd(ParseWhileStatement());
  2918. case "with":
  2919. return MarkEnd(ParseWithStatement());
  2920. }
  2921. }
  2922. Expression expr = ParseExpression();
  2923. // 12.12 Labelled Statements
  2924. if ((expr.Type == SyntaxNodes.Identifier) && Match(":"))
  2925. {
  2926. Lex();
  2927. string key = "$" + ((Identifier) expr).Name;
  2928. if (_state.LabelSet.Contains(key))
  2929. {
  2930. ThrowError(Token.Empty, Messages.Redeclaration, "Label", ((Identifier) expr).Name);
  2931. }
  2932. _state.LabelSet.Add(key);
  2933. Statement labeledBody = ParseStatement();
  2934. _state.LabelSet.Remove(key);
  2935. return MarkEnd(CreateLabeledStatement((Identifier) expr, labeledBody));
  2936. }
  2937. ConsumeSemicolon();
  2938. return MarkEnd(CreateExpressionStatement(expr));
  2939. }
  2940. // 13 Function Definition
  2941. private Statement ParseFunctionSourceElements()
  2942. {
  2943. Token firstRestricted = Token.Empty;
  2944. var sourceElements = new List<Statement>();
  2945. MarkStart();
  2946. Expect("{");
  2947. while (_index < _length)
  2948. {
  2949. if (_lookahead.Type != Tokens.StringLiteral)
  2950. {
  2951. break;
  2952. }
  2953. Token token = _lookahead;
  2954. Statement sourceElement = ParseSourceElement();
  2955. sourceElements.Add(sourceElement);
  2956. if (((ExpressionStatement) sourceElement).Expression.Type != SyntaxNodes.Literal)
  2957. {
  2958. // this is not directive
  2959. break;
  2960. }
  2961. string directive = _source.Slice(token.Range[0] + 1, token.Range[1] - 1);
  2962. if (directive == "use strict")
  2963. {
  2964. _strict = true;
  2965. if (firstRestricted != Token.Empty)
  2966. {
  2967. ThrowErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  2968. }
  2969. }
  2970. else
  2971. {
  2972. if (firstRestricted == Token.Empty && token.Octal)
  2973. {
  2974. firstRestricted = token;
  2975. }
  2976. }
  2977. }
  2978. HashSet<string> oldLabelSet = _state.LabelSet;
  2979. bool oldInIteration = _state.InIteration;
  2980. bool oldInSwitch = _state.InSwitch;
  2981. bool oldInFunctionBody = _state.InFunctionBody;
  2982. _state.LabelSet = new HashSet<string>();
  2983. _state.InIteration = false;
  2984. _state.InSwitch = false;
  2985. _state.InFunctionBody = true;
  2986. while (_index < _length)
  2987. {
  2988. if (Match("}"))
  2989. {
  2990. break;
  2991. }
  2992. Statement sourceElement = ParseSourceElement();
  2993. if (sourceElement == null)
  2994. {
  2995. break;
  2996. }
  2997. sourceElements.Add(sourceElement);
  2998. }
  2999. Expect("}");
  3000. _state.LabelSet = oldLabelSet;
  3001. _state.InIteration = oldInIteration;
  3002. _state.InSwitch = oldInSwitch;
  3003. _state.InFunctionBody = oldInFunctionBody;
  3004. return MarkEnd(CreateBlockStatement(sourceElements));
  3005. }
  3006. private ParsedParameters ParseParams(Token firstRestricted)
  3007. {
  3008. string message = null;
  3009. Token stricted = Token.Empty;
  3010. var parameters = new List<Identifier>();
  3011. Expect("(");
  3012. if (!Match(")"))
  3013. {
  3014. var paramSet = new HashSet<string>();
  3015. while (_index < _length)
  3016. {
  3017. Token token = _lookahead;
  3018. Identifier param = ParseVariableIdentifier();
  3019. string key = '$' + (string) token.Value;
  3020. if (_strict)
  3021. {
  3022. if (IsRestrictedWord((string) token.Value))
  3023. {
  3024. stricted = token;
  3025. message = Messages.StrictParamName;
  3026. }
  3027. if (paramSet.Contains(key))
  3028. {
  3029. stricted = token;
  3030. message = Messages.StrictParamDupe;
  3031. }
  3032. }
  3033. else if (firstRestricted == Token.Empty)
  3034. {
  3035. if (IsRestrictedWord((string) token.Value))
  3036. {
  3037. firstRestricted = token;
  3038. message = Messages.StrictParamName;
  3039. }
  3040. else if (IsStrictModeReservedWord((string) token.Value))
  3041. {
  3042. firstRestricted = token;
  3043. message = Messages.StrictReservedWord;
  3044. }
  3045. else if (paramSet.Contains(key))
  3046. {
  3047. firstRestricted = token;
  3048. message = Messages.StrictParamDupe;
  3049. }
  3050. }
  3051. parameters.Add(param);
  3052. paramSet.Add(key);
  3053. if (Match(")"))
  3054. {
  3055. break;
  3056. }
  3057. Expect(",");
  3058. }
  3059. }
  3060. Expect(")");
  3061. return new ParsedParameters
  3062. {
  3063. Parameters = parameters,
  3064. Stricted = stricted,
  3065. FirstRestricted = firstRestricted,
  3066. Message = message
  3067. };
  3068. }
  3069. private Statement ParseFunctionDeclaration()
  3070. {
  3071. EnterVariableScope();
  3072. EnterFunctionScope();
  3073. Token firstRestricted = Token.Empty;
  3074. string message = null;
  3075. MarkStart();
  3076. ExpectKeyword("function");
  3077. Token token = _lookahead;
  3078. Identifier id = ParseVariableIdentifier();
  3079. if (_strict)
  3080. {
  3081. if (IsRestrictedWord((string) token.Value))
  3082. {
  3083. ThrowErrorTolerant(token, Messages.StrictFunctionName);
  3084. }
  3085. }
  3086. else
  3087. {
  3088. if (IsRestrictedWord((string) token.Value))
  3089. {
  3090. firstRestricted = token;
  3091. message = Messages.StrictFunctionName;
  3092. }
  3093. else if (IsStrictModeReservedWord((string) token.Value))
  3094. {
  3095. firstRestricted = token;
  3096. message = Messages.StrictReservedWord;
  3097. }
  3098. }
  3099. ParsedParameters tmp = ParseParams(firstRestricted);
  3100. IEnumerable<Identifier> parameters = tmp.Parameters;
  3101. Token stricted = tmp.Stricted;
  3102. firstRestricted = tmp.FirstRestricted;
  3103. if (tmp.Message != null)
  3104. {
  3105. message = tmp.Message;
  3106. }
  3107. bool previousStrict = _strict;
  3108. Statement body = ParseFunctionSourceElements();
  3109. if (_strict && firstRestricted != Token.Empty)
  3110. {
  3111. ThrowError(firstRestricted, message);
  3112. }
  3113. if (_strict && stricted != Token.Empty)
  3114. {
  3115. ThrowErrorTolerant(stricted, message);
  3116. }
  3117. bool functionStrict = _strict;
  3118. _strict = previousStrict;
  3119. return MarkEnd(CreateFunctionDeclaration(id, parameters, new Expression[0], body, functionStrict));
  3120. }
  3121. private void EnterVariableScope()
  3122. {
  3123. _variableScopes.Push(new VariableScope());
  3124. }
  3125. private IList<VariableDeclaration> LeaveVariableScope()
  3126. {
  3127. return _variableScopes.Pop().VariableDeclarations;
  3128. }
  3129. private void EnterFunctionScope()
  3130. {
  3131. _functionScopes.Push(new FunctionScope());
  3132. }
  3133. private IList<FunctionDeclaration> LeaveFunctionScope()
  3134. {
  3135. return _functionScopes.Pop().FunctionDeclarations;
  3136. }
  3137. private FunctionExpression ParseFunctionExpression()
  3138. {
  3139. EnterVariableScope();
  3140. EnterFunctionScope();
  3141. Token firstRestricted = Token.Empty;
  3142. string message = null;
  3143. Identifier id = null;
  3144. MarkStart();
  3145. ExpectKeyword("function");
  3146. if (!Match("("))
  3147. {
  3148. Token token = _lookahead;
  3149. id = ParseVariableIdentifier();
  3150. if (_strict)
  3151. {
  3152. if (IsRestrictedWord((string) token.Value))
  3153. {
  3154. ThrowErrorTolerant(token, Messages.StrictFunctionName);
  3155. }
  3156. }
  3157. else
  3158. {
  3159. if (IsRestrictedWord((string) token.Value))
  3160. {
  3161. firstRestricted = token;
  3162. message = Messages.StrictFunctionName;
  3163. }
  3164. else if (IsStrictModeReservedWord((string) token.Value))
  3165. {
  3166. firstRestricted = token;
  3167. message = Messages.StrictReservedWord;
  3168. }
  3169. }
  3170. }
  3171. ParsedParameters tmp = ParseParams(firstRestricted);
  3172. IEnumerable<Identifier> parameters = tmp.Parameters;
  3173. Token stricted = tmp.Stricted;
  3174. firstRestricted = tmp.FirstRestricted;
  3175. if (tmp.Message != null)
  3176. {
  3177. message = tmp.Message;
  3178. }
  3179. bool previousStrict = _strict;
  3180. Statement body = ParseFunctionSourceElements();
  3181. if (_strict && firstRestricted != Token.Empty)
  3182. {
  3183. ThrowError(firstRestricted, message);
  3184. }
  3185. if (_strict && stricted != Token.Empty)
  3186. {
  3187. ThrowErrorTolerant(stricted, message);
  3188. }
  3189. bool functionStrict = _strict;
  3190. _strict = previousStrict;
  3191. return MarkEnd(CreateFunctionExpression(id, parameters, new Expression[0], body, functionStrict));
  3192. }
  3193. // 14 Program
  3194. private Statement ParseSourceElement()
  3195. {
  3196. if (_lookahead.Type == Tokens.Keyword)
  3197. {
  3198. switch ((string) _lookahead.Value)
  3199. {
  3200. case "const":
  3201. case "let":
  3202. return ParseConstLetDeclaration((string) _lookahead.Value);
  3203. case "function":
  3204. return ParseFunctionDeclaration();
  3205. default:
  3206. return ParseStatement();
  3207. }
  3208. }
  3209. if (_lookahead.Type != Tokens.EOF)
  3210. {
  3211. return ParseStatement();
  3212. }
  3213. return null;
  3214. }
  3215. private ICollection<Statement> ParseSourceElements()
  3216. {
  3217. var sourceElements = new List<Statement>();
  3218. Token firstRestricted = Token.Empty;
  3219. Statement sourceElement;
  3220. while (_index < _length)
  3221. {
  3222. Token token = _lookahead;
  3223. if (token.Type != Tokens.StringLiteral)
  3224. {
  3225. break;
  3226. }
  3227. sourceElement = ParseSourceElement();
  3228. sourceElements.Add(sourceElement);
  3229. if (((ExpressionStatement) sourceElement).Expression.Type != SyntaxNodes.Literal)
  3230. {
  3231. // this is not directive
  3232. break;
  3233. }
  3234. string directive = _source.Slice(token.Range[0] + 1, token.Range[1] - 1);
  3235. if (directive == "use strict")
  3236. {
  3237. _strict = true;
  3238. if (firstRestricted != Token.Empty)
  3239. {
  3240. ThrowErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  3241. }
  3242. }
  3243. else
  3244. {
  3245. if (firstRestricted == Token.Empty && token.Octal)
  3246. {
  3247. firstRestricted = token;
  3248. }
  3249. }
  3250. }
  3251. while (_index < _length)
  3252. {
  3253. sourceElement = ParseSourceElement();
  3254. if (sourceElement == null)
  3255. {
  3256. break;
  3257. }
  3258. sourceElements.Add(sourceElement);
  3259. }
  3260. return sourceElements;
  3261. }
  3262. private Program ParseProgram()
  3263. {
  3264. EnterVariableScope();
  3265. EnterFunctionScope();
  3266. MarkStart();
  3267. Peek();
  3268. ICollection<Statement> body = ParseSourceElements();
  3269. return MarkEnd(CreateProgram(body, _strict));
  3270. }
  3271. private LocationMarker CreateLocationMarker()
  3272. {
  3273. if (!_extra.Loc.HasValue && _extra.Range.Length == 0)
  3274. {
  3275. return null;
  3276. }
  3277. SkipComment();
  3278. return new LocationMarker(_index, _lineNumber, _lineStart);
  3279. }
  3280. public Program Parse(string code)
  3281. {
  3282. return Parse(code, null);
  3283. }
  3284. public Program Parse(string code, ParserOptions options)
  3285. {
  3286. Program program;
  3287. _source = code;
  3288. _index = 0;
  3289. _lineNumber = (_source.Length > 0) ? 1 : 0;
  3290. _lineStart = 0;
  3291. _length = _source.Length;
  3292. _lookahead = null;
  3293. _state = new State
  3294. {
  3295. AllowIn = true,
  3296. LabelSet = new HashSet<string>(),
  3297. InFunctionBody = false,
  3298. InIteration = false,
  3299. InSwitch = false,
  3300. LastCommentStart = -1,
  3301. MarkerStack = new Stack<int>()
  3302. };
  3303. _extra = new Extra
  3304. {
  3305. Range = new int[0],
  3306. Loc = 0,
  3307. };
  3308. if (options != null)
  3309. {
  3310. if (!String.IsNullOrEmpty(options.Source))
  3311. {
  3312. _extra.Source = options.Source;
  3313. }
  3314. if (options.Tokens)
  3315. {
  3316. _extra.Tokens = new List<Token>();
  3317. }
  3318. if (options.Comment)
  3319. {
  3320. _extra.Comments = new List<Comment>();
  3321. }
  3322. if (options.Tolerant)
  3323. {
  3324. _extra.Errors = new List<ParserException>();
  3325. }
  3326. }
  3327. try
  3328. {
  3329. program = ParseProgram();
  3330. if (_extra.Comments != null)
  3331. {
  3332. program.Comments = _extra.Comments;
  3333. }
  3334. if (_extra.Tokens != null)
  3335. {
  3336. program.Tokens = _extra.Tokens;
  3337. }
  3338. if (_extra.Errors != null)
  3339. {
  3340. program.Errors = _extra.Errors;
  3341. }
  3342. }
  3343. finally
  3344. {
  3345. _extra = new Extra();
  3346. }
  3347. return program;
  3348. }
  3349. public FunctionExpression ParseFunctionExpression(string functionExpression)
  3350. {
  3351. _source = functionExpression;
  3352. _index = 0;
  3353. _lineNumber = (_source.Length > 0) ? 1 : 0;
  3354. _lineStart = 0;
  3355. _length = _source.Length;
  3356. _lookahead = null;
  3357. _state = new State
  3358. {
  3359. AllowIn = true,
  3360. LabelSet = new HashSet<string>(),
  3361. InFunctionBody = true,
  3362. InIteration = false,
  3363. InSwitch = false,
  3364. LastCommentStart = -1,
  3365. MarkerStack = new Stack<int>()
  3366. };
  3367. _extra = new Extra
  3368. {
  3369. Range = new int[0],
  3370. Loc = 0,
  3371. };
  3372. _strict = false;
  3373. Peek();
  3374. return ParseFunctionExpression();
  3375. }
  3376. private class Extra
  3377. {
  3378. public int? Loc;
  3379. public int[] Range;
  3380. public string Source;
  3381. public List<Comment> Comments;
  3382. public List<Token> Tokens;
  3383. public List<ParserException> Errors;
  3384. }
  3385. private class LocationMarker
  3386. {
  3387. private readonly int[] _marker;
  3388. public LocationMarker(int index, int lineNumber, int lineStart)
  3389. {
  3390. _marker = new[] {index, lineNumber, index - lineStart, 0, 0, 0};
  3391. }
  3392. public void End(int index, int lineNumber, int lineStart)
  3393. {
  3394. _marker[3] = index;
  3395. _marker[4] = lineNumber;
  3396. _marker[5] = index - lineStart;
  3397. }
  3398. public void Apply(SyntaxNode node, Extra extra, Func<SyntaxNode, SyntaxNode> postProcess)
  3399. {
  3400. if (extra.Range.Length > 0)
  3401. {
  3402. node.Range = new[] {_marker[0], _marker[3]};
  3403. }
  3404. if (extra.Loc.HasValue)
  3405. {
  3406. node.Location = new Location
  3407. {
  3408. Start = new Position
  3409. {
  3410. Line = _marker[1],
  3411. Column = _marker[2]
  3412. },
  3413. End = new Position
  3414. {
  3415. Line = _marker[4],
  3416. Column = _marker[5]
  3417. }
  3418. };
  3419. }
  3420. node = postProcess(node);
  3421. }
  3422. };
  3423. private struct ParsedParameters
  3424. {
  3425. public Token FirstRestricted;
  3426. public string Message;
  3427. public IEnumerable<Identifier> Parameters;
  3428. public Token Stricted;
  3429. }
  3430. private static class Regexes
  3431. {
  3432. public static readonly Regex NonAsciiIdentifierStart = new Regex("[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]");
  3433. public static readonly Regex NonAsciiIdentifierPart = new Regex("[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]");
  3434. };
  3435. }
  3436. }