JavascriptParser.cs 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using Jint.Parser.Ast;
  8. namespace Jint.Parser
  9. {
  10. public class JavaScriptParser
  11. {
  12. private static readonly object[] Keywords =
  13. {
  14. "if", "in", "do", "var", "for", "new", "try", "let",
  15. "this", "else", "case", "void", "with", "enum",
  16. "while", "break", "catch", "throw", "const", "yield",
  17. "class", "super", "return", "typeof", "delete",
  18. "switch", "export", "import", "default", "finally", "extends",
  19. "function", "continue", "debugger", "instanceof"
  20. };
  21. private static readonly object[] StrictModeReservedWords =
  22. {
  23. "implements",
  24. "interface",
  25. "package",
  26. "private",
  27. "protected",
  28. "public",
  29. "static",
  30. "yield",
  31. "let"
  32. };
  33. private static readonly object[] FutureReservedWords =
  34. {
  35. "class",
  36. "enum",
  37. "export",
  38. "extends",
  39. "import",
  40. "super"
  41. };
  42. private Extra _extra;
  43. private int _index; // position in the stream
  44. private int _length; // length of the stream
  45. private int _lineNumber;
  46. private int _lineStart;
  47. private Location _location;
  48. private Token _lookahead;
  49. private string _source;
  50. private State _state;
  51. private bool _strict;
  52. private readonly Stack<IVariableScope> _variableScopes = new Stack<IVariableScope>();
  53. private readonly Stack<IFunctionScope> _functionScopes = new Stack<IFunctionScope>();
  54. public JavaScriptParser()
  55. {
  56. }
  57. public JavaScriptParser(bool strict)
  58. {
  59. _strict = strict;
  60. }
  61. private static bool IsDecimalDigit(char ch)
  62. {
  63. return (ch >= '0' && ch <= '9');
  64. }
  65. private static bool IsHexDigit(char ch)
  66. {
  67. return
  68. ch >= '0' && ch <= '9' ||
  69. ch >= 'a' && ch <= 'f' ||
  70. ch >= 'A' && ch <= 'F'
  71. ;
  72. }
  73. private static bool IsOctalDigit(char ch)
  74. {
  75. return ch >= '0' && ch <= '7';
  76. }
  77. // 7.2 White Space
  78. private static bool IsWhiteSpace(char ch)
  79. {
  80. return (ch == 32) || // space
  81. (ch == 9) || // tab
  82. (ch == 0xB) ||
  83. (ch == 0xC) ||
  84. (ch == 0xA0) ||
  85. (ch >= 0x1680 && (
  86. ch == 0x1680 ||
  87. ch == 0x180E ||
  88. (ch >= 0x2000 && ch <= 0x200A) ||
  89. ch == 0x202F ||
  90. ch == 0x205F ||
  91. ch == 0x3000 ||
  92. ch == 0xFEFF));
  93. }
  94. // 7.3 Line Terminators
  95. private static bool IsLineTerminator(char ch)
  96. {
  97. return (ch == 10)
  98. || (ch == 13)
  99. || (ch == 0x2028) // line separator
  100. || (ch == 0x2029) // paragraph separator
  101. ;
  102. }
  103. // 7.6 Identifier Names and Identifiers
  104. private static bool IsIdentifierStart(char ch)
  105. {
  106. return (ch == '$') || (ch == '_') ||
  107. (ch >= 'A' && ch <= 'Z') ||
  108. (ch >= 'a' && ch <= 'z') ||
  109. (ch == '\\') ||
  110. ((ch >= 0x80) && Regexes.NonAsciiIdentifierStart.IsMatch(ch.ToString()));
  111. }
  112. private static bool IsIdentifierPart(char ch)
  113. {
  114. return (ch == '$') || (ch == '_') ||
  115. (ch >= 'A' && ch <= 'Z') ||
  116. (ch >= 'a' && ch <= 'z') ||
  117. (ch >= '0' && ch <= '9') ||
  118. (ch == '\\') ||
  119. ((ch >= 0x80) && Regexes.NonAsciiIdentifierPart.IsMatch(ch.ToString()));
  120. }
  121. // 7.6.1.2 Future Reserved Words
  122. private static bool IsFutureReservedWord(string id)
  123. {
  124. return Array.IndexOf(FutureReservedWords, id) >= 0;
  125. }
  126. private static bool IsStrictModeReservedWord(string id)
  127. {
  128. return Array.IndexOf(StrictModeReservedWords, id) >= 0;
  129. }
  130. private static bool IsRestrictedWord(string id)
  131. {
  132. return "eval".Equals(id) || "arguments".Equals(id);
  133. }
  134. // 7.6.1.1 Keywords
  135. private bool IsKeyword(string id)
  136. {
  137. if (_strict && IsStrictModeReservedWord(id))
  138. {
  139. return true;
  140. }
  141. // 'const' is specialized as Keyword in V8.
  142. // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next.
  143. // Some others are from future reserved words.
  144. return Array.IndexOf(Keywords, id) >= 0;
  145. }
  146. // 7.4 Comments
  147. private void AddComment(string type, string value, int start, int end, Location location)
  148. {
  149. // Because the way the actual token is scanned, often the comments
  150. // (if any) are skipped twice during the lexical analysis.
  151. // Thus, we need to skip adding a comment if the comment array already
  152. // handled it.
  153. if (_state.LastCommentStart >= start)
  154. {
  155. return;
  156. }
  157. _state.LastCommentStart = start;
  158. var comment = new Comment
  159. {
  160. Type = type,
  161. Value = value
  162. };
  163. if (_extra.Range != null)
  164. {
  165. comment.Range = new[] {start, end};
  166. }
  167. if (_extra.Loc.HasValue)
  168. {
  169. comment.Location = location;
  170. }
  171. _extra.Comments.Add(comment);
  172. }
  173. private void SkipSingleLineComment()
  174. {
  175. //var start, loc, ch, comment;
  176. int start = _index - 2;
  177. _location = new Location
  178. {
  179. Start = new Position
  180. {
  181. Line = _lineNumber,
  182. Column = _index - _lineStart - 2
  183. }
  184. };
  185. while (_index < _length)
  186. {
  187. char ch = _source.CharCodeAt(_index);
  188. ++_index;
  189. if (IsLineTerminator(ch))
  190. {
  191. if (_extra.Comments != null)
  192. {
  193. var comment = _source.Slice(start + 2, _index - 1);
  194. _location.End = new Position
  195. {
  196. Line = _lineNumber,
  197. Column = _index - _lineStart - 1
  198. };
  199. AddComment("Line", comment, start, _index - 1, _location);
  200. }
  201. if (ch == 13 && _source.CharCodeAt(_index) == 10)
  202. {
  203. ++_index;
  204. }
  205. ++_lineNumber;
  206. _lineStart = _index;
  207. return;
  208. }
  209. }
  210. if (_extra.Comments != null)
  211. {
  212. var comment = _source.Slice(start + 2, _index);
  213. _location.End = new Position
  214. {
  215. Line = _lineNumber,
  216. Column = _index - _lineStart
  217. };
  218. AddComment("Line", comment, start, _index, _location);
  219. }
  220. }
  221. private void SkipMultiLineComment()
  222. {
  223. //var start, loc, ch, comment;
  224. int start = 0;
  225. if (_extra.Comments != null)
  226. {
  227. start = _index - 2;
  228. _location = new Location
  229. {
  230. Start = new Position
  231. {
  232. Line = _lineNumber,
  233. Column = _index - _lineStart - 2
  234. }
  235. };
  236. }
  237. while (_index < _length)
  238. {
  239. char ch = _source.CharCodeAt(_index);
  240. if (IsLineTerminator(ch))
  241. {
  242. if (ch == 13 && _source.CharCodeAt(_index + 1) == 10)
  243. {
  244. ++_index;
  245. }
  246. ++_lineNumber;
  247. ++_index;
  248. _lineStart = _index;
  249. if (_index >= _length)
  250. {
  251. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  252. }
  253. }
  254. else if (ch == 42)
  255. {
  256. // Block comment ends with '*/' (char #42, char #47).
  257. if (_source.CharCodeAt(_index + 1) == 47)
  258. {
  259. ++_index;
  260. ++_index;
  261. if (_extra.Comments != null)
  262. {
  263. string comment = _source.Slice(start + 2, _index - 2);
  264. _location.End = new Position
  265. {
  266. Line = _lineNumber,
  267. Column = _index - _lineStart
  268. };
  269. AddComment("Block", comment, start, _index, _location);
  270. }
  271. return;
  272. }
  273. ++_index;
  274. }
  275. else
  276. {
  277. ++_index;
  278. }
  279. }
  280. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  281. }
  282. private void SkipComment()
  283. {
  284. while (_index < _length)
  285. {
  286. char ch = _source.CharCodeAt(_index);
  287. if (IsWhiteSpace(ch))
  288. {
  289. ++_index;
  290. }
  291. else if (IsLineTerminator(ch))
  292. {
  293. ++_index;
  294. if (ch == 13 && _source.CharCodeAt(_index) == 10)
  295. {
  296. ++_index;
  297. }
  298. ++_lineNumber;
  299. _lineStart = _index;
  300. }
  301. else if (ch == 47)
  302. {
  303. // 47 is '/'
  304. ch = _source.CharCodeAt(_index + 1);
  305. if (ch == 47)
  306. {
  307. ++_index;
  308. ++_index;
  309. SkipSingleLineComment();
  310. }
  311. else if (ch == 42)
  312. {
  313. // 42 is '*'
  314. ++_index;
  315. ++_index;
  316. SkipMultiLineComment();
  317. }
  318. else
  319. {
  320. break;
  321. }
  322. }
  323. else
  324. {
  325. break;
  326. }
  327. }
  328. }
  329. private bool ScanHexEscape(char prefix, out char result)
  330. {
  331. int code = char.MinValue;
  332. int len = (prefix == 'u') ? 4 : 2;
  333. for (int i = 0; i < len; ++i)
  334. {
  335. if (_index < _length && IsHexDigit(_source.CharCodeAt(_index)))
  336. {
  337. char ch = _source.CharCodeAt(_index++);
  338. code = code*16 +
  339. "0123456789abcdef".IndexOf(ch.ToString(),
  340. StringComparison.OrdinalIgnoreCase);
  341. }
  342. else
  343. {
  344. result = char.MinValue;
  345. return false;
  346. }
  347. }
  348. result = (char) code;
  349. return true;
  350. }
  351. private string GetEscapedIdentifier()
  352. {
  353. char ch = _source.CharCodeAt(_index++);
  354. var id = new StringBuilder(ch.ToString());
  355. // '\u' (char #92, char #117) denotes an escaped character.
  356. if (ch == 92)
  357. {
  358. if (_source.CharCodeAt(_index) != 117)
  359. {
  360. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  361. }
  362. ++_index;
  363. if (!ScanHexEscape('u', out ch) || ch == '\\' || !IsIdentifierStart(ch))
  364. {
  365. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  366. }
  367. id = new StringBuilder(ch.ToString());
  368. }
  369. while (_index < _length)
  370. {
  371. ch = _source.CharCodeAt(_index);
  372. if (!IsIdentifierPart(ch))
  373. {
  374. break;
  375. }
  376. ++_index;
  377. // '\u' (char #92, char #117) denotes an escaped character.
  378. if (ch == 92)
  379. {
  380. if (_source.CharCodeAt(_index) != 117)
  381. {
  382. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  383. }
  384. ++_index;
  385. if (!ScanHexEscape('u', out ch) || ch == '\\' || !IsIdentifierPart(ch))
  386. {
  387. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  388. }
  389. id.Append(ch);
  390. }
  391. else
  392. {
  393. id.Append(ch);
  394. }
  395. }
  396. return id.ToString();
  397. }
  398. private string GetIdentifier()
  399. {
  400. int start = _index++;
  401. while (_index < _length)
  402. {
  403. char ch = _source.CharCodeAt(_index);
  404. if (ch == 92)
  405. {
  406. // Blackslash (char #92) marks Unicode escape sequence.
  407. _index = start;
  408. return GetEscapedIdentifier();
  409. }
  410. if (IsIdentifierPart(ch))
  411. {
  412. ++_index;
  413. }
  414. else
  415. {
  416. break;
  417. }
  418. }
  419. return _source.Slice(start, _index);
  420. }
  421. private Token ScanIdentifier()
  422. {
  423. int start = _index;
  424. Tokens type;
  425. // Backslash (char #92) starts an escaped character.
  426. string id = (_source.CharCodeAt(_index) == 92) ? GetEscapedIdentifier() : GetIdentifier();
  427. // There is no keyword or literal with only one character.
  428. // Thus, it must be an identifier.
  429. if (id.Length == 1)
  430. {
  431. type = Tokens.Identifier;
  432. }
  433. else if (IsKeyword(id))
  434. {
  435. type = Tokens.Keyword;
  436. }
  437. else if ("null".Equals(id))
  438. {
  439. type = Tokens.NullLiteral;
  440. }
  441. else if ("true".Equals(id) || "false".Equals(id))
  442. {
  443. type = Tokens.BooleanLiteral;
  444. }
  445. else
  446. {
  447. type = Tokens.Identifier;
  448. }
  449. return new Token
  450. {
  451. Type = type,
  452. Value = id,
  453. LineNumber = _lineNumber,
  454. LineStart = _lineStart,
  455. Range = new[] {start, _index}
  456. };
  457. }
  458. // 7.7 Punctuators
  459. private Token ScanPunctuator()
  460. {
  461. int start = _index;
  462. char code = _source.CharCodeAt(_index);
  463. char ch1 = _source.CharCodeAt(_index);
  464. switch ((int) code)
  465. {
  466. // Check for most common single-character punctuators.
  467. case 46: // . dot
  468. case 40: // ( open bracket
  469. case 41: // ) close bracket
  470. case 59: // ; semicolon
  471. case 44: // , comma
  472. case 123: // { open curly brace
  473. case 125: // } close curly brace
  474. case 91: // [
  475. case 93: // ]
  476. case 58: // :
  477. case 63: // ?
  478. case 126: // ~
  479. ++_index;
  480. return new Token
  481. {
  482. Type = Tokens.Punctuator,
  483. Value = code.ToString(),
  484. LineNumber = _lineNumber,
  485. LineStart = _lineStart,
  486. Range = new[] {start, _index}
  487. };
  488. default:
  489. char code2 = _source.CharCodeAt(_index + 1);
  490. // '=' (char #61) marks an assignment or comparison operator.
  491. if (code2 == 61)
  492. {
  493. switch ((int) code)
  494. {
  495. case 37: // %
  496. case 38: // &
  497. case 42: // *:
  498. case 43: // +
  499. case 45: // -
  500. case 47: // /
  501. case 60: // <
  502. case 62: // >
  503. case 94: // ^
  504. case 124: // |
  505. _index += 2;
  506. return new Token
  507. {
  508. Type = Tokens.Punctuator,
  509. Value =
  510. code.ToString() +
  511. code2.ToString(),
  512. LineNumber = _lineNumber,
  513. LineStart = _lineStart,
  514. Range = new[] {start, _index}
  515. };
  516. case 33: // !
  517. case 61: // =
  518. _index += 2;
  519. // !== and ===
  520. if (_source.CharCodeAt(_index) == 61)
  521. {
  522. ++_index;
  523. }
  524. return new Token
  525. {
  526. Type = Tokens.Punctuator,
  527. Value = _source.Slice(start, _index),
  528. LineNumber = _lineNumber,
  529. LineStart = _lineStart,
  530. Range = new[] {start, _index}
  531. };
  532. }
  533. }
  534. break;
  535. }
  536. // Peek more characters.
  537. char ch2 = _source.CharCodeAt(_index + 1);
  538. char ch3 = _source.CharCodeAt(_index + 2);
  539. char ch4 = _source.CharCodeAt(_index + 3);
  540. // 4-character punctuator: >>>=
  541. if (ch1 == '>' && ch2 == '>' && ch3 == '>')
  542. {
  543. if (ch4 == '=')
  544. {
  545. _index += 4;
  546. return new Token
  547. {
  548. Type = Tokens.Punctuator,
  549. Value = ">>>=",
  550. LineNumber = _lineNumber,
  551. LineStart = _lineStart,
  552. Range = new[] {start, _index}
  553. };
  554. }
  555. }
  556. // 3-character punctuators: == !== >>> <<= >>=
  557. if (ch1 == '>' && ch2 == '>' && ch3 == '>')
  558. {
  559. _index += 3;
  560. return new Token
  561. {
  562. Type = Tokens.Punctuator,
  563. Value = ">>>",
  564. LineNumber = _lineNumber,
  565. LineStart = _lineStart,
  566. Range = new[] {start, _index}
  567. };
  568. }
  569. if (ch1 == '<' && ch2 == '<' && ch3 == '=')
  570. {
  571. _index += 3;
  572. return new Token
  573. {
  574. Type = Tokens.Punctuator,
  575. Value = "<<=",
  576. LineNumber = _lineNumber,
  577. LineStart = _lineStart,
  578. Range = new[] {start, _index}
  579. };
  580. }
  581. if (ch1 == '>' && ch2 == '>' && ch3 == '=')
  582. {
  583. _index += 3;
  584. return new Token
  585. {
  586. Type = Tokens.Punctuator,
  587. Value = ">>=",
  588. LineNumber = _lineNumber,
  589. LineStart = _lineStart,
  590. Range = new[] {start, _index}
  591. };
  592. }
  593. // Other 2-character punctuators: ++ -- << >> && ||
  594. if (ch1 == ch2 && ("+-<>&|".IndexOf(ch1) >= 0))
  595. {
  596. _index += 2;
  597. return new Token
  598. {
  599. Type = Tokens.Punctuator,
  600. Value = ch1.ToString() + ch2.ToString(),
  601. LineNumber = _lineNumber,
  602. LineStart = _lineStart,
  603. Range = new[] {start, _index}
  604. };
  605. }
  606. if ("<>=!+-*%&|^/".IndexOf(ch1) >= 0)
  607. {
  608. ++_index;
  609. return new Token
  610. {
  611. Type = Tokens.Punctuator,
  612. Value = ch1.ToString(),
  613. LineNumber = _lineNumber,
  614. LineStart = _lineStart,
  615. Range = new[] {start, _index}
  616. };
  617. }
  618. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  619. return null;
  620. }
  621. // 7.8.3 Numeric Literals
  622. private Token ScanHexLiteral(int start)
  623. {
  624. string number = "";
  625. while (_index < _length)
  626. {
  627. if (!IsHexDigit(_source.CharCodeAt(_index)))
  628. {
  629. break;
  630. }
  631. number += _source.CharCodeAt(_index++).ToString();
  632. }
  633. if (number.Length == 0)
  634. {
  635. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  636. }
  637. if (IsIdentifierStart(_source.CharCodeAt(_index)))
  638. {
  639. ThrowError(null, Messages.UnexpectedToken, "ILLEGAL");
  640. }
  641. return new Token
  642. {
  643. Type = Tokens.NumericLiteral,
  644. Value = Convert.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. ParserError error;
  1621. string msg = String.Format(messageFormat, arguments);
  1622. if (token != null && token.LineNumber.HasValue)
  1623. {
  1624. error = new ParserError("Line " + token.LineNumber + ": " + msg)
  1625. {
  1626. Index = token.Range[0],
  1627. LineNumber = token.LineNumber.Value,
  1628. Column = token.Range[0] - _lineStart + 1
  1629. };
  1630. }
  1631. else
  1632. {
  1633. error = new ParserError("Line " + _lineNumber + ": " + msg)
  1634. {
  1635. Index = _index,
  1636. LineNumber = _lineNumber,
  1637. Column = _index - _lineStart + 1
  1638. };
  1639. }
  1640. error.Description = msg;
  1641. throw error;
  1642. }
  1643. private void ThrowErrorTolerant(Token token, string messageFormat, params object[] arguments)
  1644. {
  1645. try
  1646. {
  1647. ThrowError(token, messageFormat, arguments);
  1648. }
  1649. catch (Exception e)
  1650. {
  1651. if (_extra.Errors != null)
  1652. {
  1653. _extra.Errors.Add(new ParserError(e.Message));
  1654. }
  1655. else
  1656. {
  1657. throw;
  1658. }
  1659. }
  1660. }
  1661. // Throw an exception because of the token.
  1662. private void ThrowUnexpected(Token token)
  1663. {
  1664. if (token.Type == Tokens.EOF)
  1665. {
  1666. ThrowError(token, Messages.UnexpectedEOS);
  1667. }
  1668. if (token.Type == Tokens.NumericLiteral)
  1669. {
  1670. ThrowError(token, Messages.UnexpectedNumber);
  1671. }
  1672. if (token.Type == Tokens.StringLiteral)
  1673. {
  1674. ThrowError(token, Messages.UnexpectedString);
  1675. }
  1676. if (token.Type == Tokens.Identifier)
  1677. {
  1678. ThrowError(token, Messages.UnexpectedIdentifier);
  1679. }
  1680. if (token.Type == Tokens.Keyword)
  1681. {
  1682. if (IsFutureReservedWord(token.Value as string))
  1683. {
  1684. ThrowError(token, Messages.UnexpectedReserved);
  1685. }
  1686. else if (_strict && IsStrictModeReservedWord(token.Value as string))
  1687. {
  1688. ThrowErrorTolerant(token, Messages.StrictReservedWord);
  1689. return;
  1690. }
  1691. ThrowError(token, Messages.UnexpectedToken, token.Value as string);
  1692. }
  1693. // BooleanLiteral, NullLiteral, or Punctuator.
  1694. ThrowError(token, Messages.UnexpectedToken, token.Value as string);
  1695. }
  1696. // Expect the next token to match the specified punctuator.
  1697. // If not, an exception will be thrown.
  1698. private void Expect(string value)
  1699. {
  1700. Token token = Lex();
  1701. if (token.Type != Tokens.Punctuator || !value.Equals(token.Value))
  1702. {
  1703. ThrowUnexpected(token);
  1704. }
  1705. }
  1706. // Expect the next token to match the specified keyword.
  1707. // If not, an exception will be thrown.
  1708. private void ExpectKeyword(string keyword)
  1709. {
  1710. Token token = Lex();
  1711. if (token.Type != Tokens.Keyword || !keyword.Equals(token.Value))
  1712. {
  1713. ThrowUnexpected(token);
  1714. }
  1715. }
  1716. // Return true if the next token matches the specified punctuator.
  1717. private bool Match(string value)
  1718. {
  1719. return _lookahead.Type == Tokens.Punctuator && value.Equals(_lookahead.Value);
  1720. }
  1721. // Return true if the next token matches the specified keyword
  1722. private bool MatchKeyword(object keyword)
  1723. {
  1724. return _lookahead.Type == Tokens.Keyword && keyword.Equals(_lookahead.Value);
  1725. }
  1726. // Return true if the next token is an assignment operator
  1727. private bool MatchAssign()
  1728. {
  1729. if (_lookahead.Type != Tokens.Punctuator)
  1730. {
  1731. return false;
  1732. }
  1733. var op = _lookahead.Value as string;
  1734. return op == "=" ||
  1735. op == "*=" ||
  1736. op == "/=" ||
  1737. op == "%=" ||
  1738. op == "+=" ||
  1739. op == "-=" ||
  1740. op == "<<=" ||
  1741. op == ">>=" ||
  1742. op == ">>>=" ||
  1743. op == "&=" ||
  1744. op == "^=" ||
  1745. op == "|=";
  1746. }
  1747. private void ConsumeSemicolon()
  1748. {
  1749. // Catch the very common case first: immediately a semicolon (char #59).
  1750. if (_source.CharCodeAt(_index) == 59)
  1751. {
  1752. Lex();
  1753. return;
  1754. }
  1755. int line = _lineNumber;
  1756. SkipComment();
  1757. if (_lineNumber != line)
  1758. {
  1759. return;
  1760. }
  1761. if (Match(";"))
  1762. {
  1763. Lex();
  1764. return;
  1765. }
  1766. if (_lookahead.Type != Tokens.EOF && !Match("}"))
  1767. {
  1768. ThrowUnexpected(_lookahead);
  1769. }
  1770. }
  1771. // Return true if provided expression is LeftHandSideExpression
  1772. private bool isLeftHandSide(Expression expr)
  1773. {
  1774. return expr.Type == SyntaxNodes.Identifier || expr.Type == SyntaxNodes.MemberExpression;
  1775. }
  1776. // 11.1.4 Array Initialiser
  1777. private ArrayExpression ParseArrayInitialiser()
  1778. {
  1779. var elements = new List<Expression>();
  1780. Expect("[");
  1781. while (!Match("]"))
  1782. {
  1783. if (Match(","))
  1784. {
  1785. Lex();
  1786. elements.Add(null);
  1787. }
  1788. else
  1789. {
  1790. elements.Add(ParseAssignmentExpression());
  1791. if (!Match("]"))
  1792. {
  1793. Expect(",");
  1794. }
  1795. }
  1796. }
  1797. Expect("]");
  1798. return CreateArrayExpression(elements);
  1799. }
  1800. // 11.1.5 Object Initialiser
  1801. private FunctionExpression ParsePropertyFunction(Identifier[] parameters, Token first = null)
  1802. {
  1803. EnterVariableScope();
  1804. EnterFunctionScope();
  1805. bool previousStrict = _strict;
  1806. MarkStart();
  1807. Statement body = ParseFunctionSourceElements();
  1808. if (first != null && _strict && IsRestrictedWord(parameters[0].Name))
  1809. {
  1810. ThrowErrorTolerant(first, Messages.StrictParamName);
  1811. }
  1812. bool functionStrict = _strict;
  1813. _strict = previousStrict;
  1814. return MarkEnd(CreateFunctionExpression(null, parameters, new Expression[0], body, functionStrict));
  1815. }
  1816. private IPropertyKeyExpression ParseObjectPropertyKey()
  1817. {
  1818. MarkStart();
  1819. Token token = Lex();
  1820. // Note: This function is called only from parseObjectProperty(), where
  1821. // EOF and Punctuator tokens are already filtered out.
  1822. if (token.Type == Tokens.StringLiteral || token.Type == Tokens.NumericLiteral)
  1823. {
  1824. if (_strict && token.Octal)
  1825. {
  1826. ThrowErrorTolerant(token, Messages.StrictOctalLiteral);
  1827. }
  1828. return MarkEnd(CreateLiteral(token));
  1829. }
  1830. return MarkEnd(CreateIdentifier((string) token.Value));
  1831. }
  1832. private Property ParseObjectProperty()
  1833. {
  1834. Expression value;
  1835. Token token = _lookahead;
  1836. MarkStart();
  1837. if (token.Type == Tokens.Identifier)
  1838. {
  1839. IPropertyKeyExpression id = ParseObjectPropertyKey();
  1840. // Property Assignment: Getter and Setter.
  1841. if ("get".Equals(token.Value) && !Match(":"))
  1842. {
  1843. var key = ParseObjectPropertyKey();
  1844. Expect("(");
  1845. Expect(")");
  1846. value = ParsePropertyFunction(new Identifier[0]);
  1847. return MarkEnd(CreateProperty(PropertyKind.Get, key, value));
  1848. }
  1849. if ("set".Equals(token.Value) && !Match(":"))
  1850. {
  1851. var key = ParseObjectPropertyKey();
  1852. Expect("(");
  1853. token = _lookahead;
  1854. if (token.Type != Tokens.Identifier)
  1855. {
  1856. Expect(")");
  1857. ThrowErrorTolerant(token, Messages.UnexpectedToken, (string) token.Value);
  1858. value = ParsePropertyFunction(new Identifier[0]);
  1859. }
  1860. else
  1861. {
  1862. var param = new[] {ParseVariableIdentifier()};
  1863. Expect(")");
  1864. value = ParsePropertyFunction(param, token);
  1865. }
  1866. return MarkEnd(CreateProperty(PropertyKind.Set, key, value));
  1867. }
  1868. Expect(":");
  1869. value = ParseAssignmentExpression();
  1870. return MarkEnd(CreateProperty(PropertyKind.Data, id, value));
  1871. }
  1872. if (token.Type == Tokens.EOF || token.Type == Tokens.Punctuator)
  1873. {
  1874. ThrowUnexpected(token);
  1875. return null; // can't be reached
  1876. }
  1877. else
  1878. {
  1879. IPropertyKeyExpression key = ParseObjectPropertyKey();
  1880. Expect(":");
  1881. value = ParseAssignmentExpression();
  1882. return MarkEnd(CreateProperty(PropertyKind.Data, key, value));
  1883. }
  1884. }
  1885. private ObjectExpression ParseObjectInitialiser()
  1886. {
  1887. var properties = new List<Property>();
  1888. var map = new Dictionary<string, PropertyKind>();
  1889. Expect("{");
  1890. while (!Match("}"))
  1891. {
  1892. Property property = ParseObjectProperty();
  1893. string name = property.Key.GetKey();
  1894. PropertyKind kind = property.Kind;
  1895. string key = "$" + name;
  1896. if (map.ContainsKey(key))
  1897. {
  1898. if (map[key] == PropertyKind.Data)
  1899. {
  1900. if (_strict && kind == PropertyKind.Data)
  1901. {
  1902. ThrowErrorTolerant(Token.Empty, Messages.StrictDuplicateProperty);
  1903. }
  1904. else if (kind != PropertyKind.Data)
  1905. {
  1906. ThrowErrorTolerant(Token.Empty, Messages.AccessorDataProperty);
  1907. }
  1908. }
  1909. else
  1910. {
  1911. if (kind == PropertyKind.Data)
  1912. {
  1913. ThrowErrorTolerant(Token.Empty, Messages.AccessorDataProperty);
  1914. }
  1915. else if ((map[key] & kind) == kind)
  1916. {
  1917. ThrowErrorTolerant(Token.Empty, Messages.AccessorGetSet);
  1918. }
  1919. }
  1920. map[key] |= kind;
  1921. }
  1922. else
  1923. {
  1924. map[key] = kind;
  1925. }
  1926. properties.Add(property);
  1927. if (!Match("}"))
  1928. {
  1929. Expect(",");
  1930. }
  1931. }
  1932. Expect("}");
  1933. return CreateObjectExpression(properties);
  1934. }
  1935. // 11.1.6 The Grouping Operator
  1936. private Expression ParseGroupExpression()
  1937. {
  1938. Expect("(");
  1939. Expression expr = ParseExpression();
  1940. Expect(")");
  1941. return expr;
  1942. }
  1943. // 11.1 Primary Expressions
  1944. private Expression ParsePrimaryExpression()
  1945. {
  1946. Expression expr = null;
  1947. if (Match("("))
  1948. {
  1949. return ParseGroupExpression();
  1950. }
  1951. Tokens type = _lookahead.Type;
  1952. MarkStart();
  1953. if (type == Tokens.Identifier)
  1954. {
  1955. expr = CreateIdentifier((string) Lex().Value);
  1956. }
  1957. else if (type == Tokens.StringLiteral || type == Tokens.NumericLiteral)
  1958. {
  1959. if (_strict && _lookahead.Octal)
  1960. {
  1961. ThrowErrorTolerant(_lookahead, Messages.StrictOctalLiteral);
  1962. }
  1963. expr = CreateLiteral(Lex());
  1964. }
  1965. else if (type == Tokens.Keyword)
  1966. {
  1967. if (MatchKeyword("this"))
  1968. {
  1969. Lex();
  1970. expr = CreateThisExpression();
  1971. }
  1972. else if (MatchKeyword("function"))
  1973. {
  1974. expr = ParseFunctionExpression();
  1975. }
  1976. }
  1977. else if (type == Tokens.BooleanLiteral)
  1978. {
  1979. Token token = Lex();
  1980. token.Value = ("true".Equals(token.Value));
  1981. expr = CreateLiteral(token);
  1982. }
  1983. else if (type == Tokens.NullLiteral)
  1984. {
  1985. Token token = Lex();
  1986. token.Value = null;
  1987. expr = CreateLiteral(token);
  1988. }
  1989. else if (Match("["))
  1990. {
  1991. expr = ParseArrayInitialiser();
  1992. }
  1993. else if (Match("{"))
  1994. {
  1995. expr = ParseObjectInitialiser();
  1996. }
  1997. else if (Match("/") || Match("/="))
  1998. {
  1999. expr = CreateLiteral(_extra.Tokens != null ? CollectRegex() : ScanRegExp());
  2000. }
  2001. if (expr != null)
  2002. {
  2003. return MarkEnd(expr);
  2004. }
  2005. ThrowUnexpected(Lex());
  2006. return null; // can't be reached
  2007. }
  2008. // 11.2 Left-Hand-Side Expressions
  2009. private IEnumerable<Expression> ParseArguments()
  2010. {
  2011. var args = new List<Expression>();
  2012. Expect("(");
  2013. if (!Match(")"))
  2014. {
  2015. while (_index < _length)
  2016. {
  2017. args.Add(ParseAssignmentExpression());
  2018. if (Match(")"))
  2019. {
  2020. break;
  2021. }
  2022. Expect(",");
  2023. }
  2024. }
  2025. Expect(")");
  2026. return args;
  2027. }
  2028. private Identifier ParseNonComputedProperty()
  2029. {
  2030. MarkStart();
  2031. Token token = Lex();
  2032. if (!IsIdentifierName(token))
  2033. {
  2034. ThrowUnexpected(token);
  2035. }
  2036. return MarkEnd(CreateIdentifier((string) token.Value));
  2037. }
  2038. private Identifier ParseNonComputedMember()
  2039. {
  2040. Expect(".");
  2041. return ParseNonComputedProperty();
  2042. }
  2043. private Expression ParseComputedMember()
  2044. {
  2045. Expect("[");
  2046. Expression expr = ParseExpression();
  2047. Expect("]");
  2048. return expr;
  2049. }
  2050. private NewExpression ParseNewExpression()
  2051. {
  2052. MarkStart();
  2053. ExpectKeyword("new");
  2054. Expression callee = ParseLeftHandSideExpression();
  2055. IEnumerable<Expression> args = Match("(") ? ParseArguments() : new AssignmentExpression[0];
  2056. return MarkEnd(CreateNewExpression(callee, args));
  2057. }
  2058. private Expression ParseLeftHandSideExpressionAllowCall()
  2059. {
  2060. LocationMarker marker = CreateLocationMarker();
  2061. var previousAllowIn = _state.AllowIn;
  2062. _state.AllowIn = true;
  2063. Expression expr = MatchKeyword("new") ? ParseNewExpression() : ParsePrimaryExpression();
  2064. _state.AllowIn = previousAllowIn;
  2065. while (Match(".") || Match("[") || Match("("))
  2066. {
  2067. if (Match("("))
  2068. {
  2069. IEnumerable<Expression> args = ParseArguments();
  2070. expr = CreateCallExpression(expr, args);
  2071. }
  2072. else if (Match("["))
  2073. {
  2074. Expression property = ParseComputedMember();
  2075. expr = CreateMemberExpression('[', expr, property);
  2076. }
  2077. else
  2078. {
  2079. Identifier property = ParseNonComputedMember();
  2080. expr = CreateMemberExpression('.', expr, property);
  2081. }
  2082. if (marker != null)
  2083. {
  2084. marker.End(_index, _lineNumber, _lineStart);
  2085. marker.Apply(expr, _extra, PostProcess);
  2086. }
  2087. }
  2088. return expr;
  2089. }
  2090. private Expression ParseLeftHandSideExpression()
  2091. {
  2092. LocationMarker marker = CreateLocationMarker();
  2093. var previousAllowIn = _state.AllowIn;
  2094. Expression expr = MatchKeyword("new") ? ParseNewExpression() : ParsePrimaryExpression();
  2095. _state.AllowIn = previousAllowIn;
  2096. while (Match(".") || Match("["))
  2097. {
  2098. if (Match("["))
  2099. {
  2100. Expression property = ParseComputedMember();
  2101. expr = CreateMemberExpression('[', expr, property);
  2102. }
  2103. else
  2104. {
  2105. Identifier property = ParseNonComputedMember();
  2106. expr = CreateMemberExpression('.', expr, property);
  2107. }
  2108. if (marker != null)
  2109. {
  2110. marker.End(_index, _lineNumber, _lineStart);
  2111. marker.Apply(expr, _extra, PostProcess);
  2112. }
  2113. }
  2114. return expr;
  2115. }
  2116. // 11.3 Postfix Expressions
  2117. private Expression ParsePostfixExpression()
  2118. {
  2119. MarkStart();
  2120. Expression expr = ParseLeftHandSideExpressionAllowCall();
  2121. if (_lookahead.Type == Tokens.Punctuator)
  2122. {
  2123. if ((Match("++") || Match("--")) && !PeekLineTerminator())
  2124. {
  2125. // 11.3.1, 11.3.2
  2126. if (_strict && expr.Type == SyntaxNodes.Identifier && IsRestrictedWord(((Identifier) expr).Name))
  2127. {
  2128. ThrowErrorTolerant(Token.Empty, Messages.StrictLHSPostfix);
  2129. }
  2130. if (!isLeftHandSide(expr))
  2131. {
  2132. ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInAssignment);
  2133. }
  2134. Token token = Lex();
  2135. expr = CreatePostfixExpression((string) token.Value, expr);
  2136. }
  2137. }
  2138. return MarkEndIf(expr);
  2139. }
  2140. // 11.4 Unary Operators
  2141. private Expression ParseUnaryExpression()
  2142. {
  2143. Expression expr;
  2144. MarkStart();
  2145. if (_lookahead.Type != Tokens.Punctuator && _lookahead.Type != Tokens.Keyword)
  2146. {
  2147. expr = ParsePostfixExpression();
  2148. }
  2149. else if (Match("++") || Match("--"))
  2150. {
  2151. Token token = Lex();
  2152. expr = ParseUnaryExpression();
  2153. // 11.4.4, 11.4.5
  2154. if (_strict && expr.Type == SyntaxNodes.Identifier && IsRestrictedWord(((Identifier) expr).Name))
  2155. {
  2156. ThrowErrorTolerant(Token.Empty, Messages.StrictLHSPrefix);
  2157. }
  2158. if (!isLeftHandSide(expr))
  2159. {
  2160. ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInAssignment);
  2161. }
  2162. expr = CreateUnaryExpression((string) token.Value, expr);
  2163. }
  2164. else if (Match("+") || Match("-") || Match("~") || Match("!"))
  2165. {
  2166. Token token = Lex();
  2167. expr = ParseUnaryExpression();
  2168. expr = CreateUnaryExpression((string) token.Value, expr);
  2169. }
  2170. else if (MatchKeyword("delete") || MatchKeyword("void") || MatchKeyword("typeof"))
  2171. {
  2172. Token token = Lex();
  2173. expr = ParseUnaryExpression();
  2174. UnaryExpression unaryExpr = CreateUnaryExpression((string) token.Value, expr);
  2175. if (_strict && unaryExpr.Operator == UnaryOperator.Delete && unaryExpr.Argument.Type == SyntaxNodes.Identifier)
  2176. {
  2177. ThrowErrorTolerant(Token.Empty, Messages.StrictDelete);
  2178. }
  2179. expr = unaryExpr;
  2180. }
  2181. else
  2182. {
  2183. expr = ParsePostfixExpression();
  2184. }
  2185. return MarkEndIf(expr);
  2186. }
  2187. private int binaryPrecedence(Token token, bool allowIn)
  2188. {
  2189. int prec = 0;
  2190. if (token.Type != Tokens.Punctuator && token.Type != Tokens.Keyword)
  2191. {
  2192. return 0;
  2193. }
  2194. switch ((string) token.Value)
  2195. {
  2196. case "||":
  2197. prec = 1;
  2198. break;
  2199. case "&&":
  2200. prec = 2;
  2201. break;
  2202. case "|":
  2203. prec = 3;
  2204. break;
  2205. case "^":
  2206. prec = 4;
  2207. break;
  2208. case "&":
  2209. prec = 5;
  2210. break;
  2211. case "==":
  2212. case "!=":
  2213. case "===":
  2214. case "!==":
  2215. prec = 6;
  2216. break;
  2217. case "<":
  2218. case ">":
  2219. case "<=":
  2220. case ">=":
  2221. case "instanceof":
  2222. prec = 7;
  2223. break;
  2224. case "in":
  2225. prec = allowIn ? 7 : 0;
  2226. break;
  2227. case "<<":
  2228. case ">>":
  2229. case ">>>":
  2230. prec = 8;
  2231. break;
  2232. case "+":
  2233. case "-":
  2234. prec = 9;
  2235. break;
  2236. case "*":
  2237. case "/":
  2238. case "%":
  2239. prec = 11;
  2240. break;
  2241. }
  2242. return prec;
  2243. }
  2244. // 11.5 Multiplicative Operators
  2245. // 11.6 Additive Operators
  2246. // 11.7 Bitwise Shift Operators
  2247. // 11.8 Relational Operators
  2248. // 11.9 Equality Operators
  2249. // 11.10 Binary Bitwise Operators
  2250. // 11.11 Binary Logical Operators
  2251. private Expression ParseBinaryExpression()
  2252. {
  2253. Expression expr;
  2254. LocationMarker marker = CreateLocationMarker();
  2255. Expression left = ParseUnaryExpression();
  2256. Token token = _lookahead;
  2257. int prec = binaryPrecedence(token, _state.AllowIn);
  2258. if (prec == 0)
  2259. {
  2260. return left;
  2261. }
  2262. token.Precedence = prec;
  2263. Lex();
  2264. var markers = new Stack<LocationMarker>( new [] {marker, CreateLocationMarker()});
  2265. Expression right = ParseUnaryExpression();
  2266. var stack = new List<object>( new object[] {left, token, right});
  2267. while ((prec = binaryPrecedence(_lookahead, _state.AllowIn)) > 0)
  2268. {
  2269. // Reduce: make a binary expression from the three topmost entries.
  2270. while ((stack.Count > 2) && (prec <= ((Token) stack[stack.Count - 2]).Precedence))
  2271. {
  2272. right = (Expression) stack.Pop();
  2273. var op = (string) ((Token) stack.Pop()).Value;
  2274. left = (Expression) stack.Pop();
  2275. expr = CreateBinaryExpression(op, left, right);
  2276. markers.Pop();
  2277. marker = markers.Pop();
  2278. if (marker != null)
  2279. {
  2280. marker.End(_index, _lineNumber, _lineStart);
  2281. marker.Apply(expr, _extra, PostProcess);
  2282. }
  2283. stack.Push(expr);
  2284. markers.Push(marker);
  2285. }
  2286. // Shift.
  2287. token = Lex();
  2288. token.Precedence = prec;
  2289. stack.Push(token);
  2290. markers.Push(CreateLocationMarker());
  2291. expr = ParseUnaryExpression();
  2292. stack.Push(expr);
  2293. }
  2294. // Final reduce to clean-up the stack.
  2295. int i = stack.Count - 1;
  2296. expr = (Expression) stack[i];
  2297. markers.Pop();
  2298. while (i > 1)
  2299. {
  2300. expr = CreateBinaryExpression((string) ((Token) stack[i - 1]).Value, (Expression) stack[i - 2], expr);
  2301. i -= 2;
  2302. marker = markers.Pop();
  2303. if (marker != null)
  2304. {
  2305. marker.End(_index, _lineNumber, _lineStart);
  2306. marker.Apply(expr, _extra, PostProcess);
  2307. }
  2308. }
  2309. return expr;
  2310. }
  2311. // 11.12 Conditional Operator
  2312. private Expression ParseConditionalExpression()
  2313. {
  2314. MarkStart();
  2315. Expression expr = ParseBinaryExpression();
  2316. if (Match("?"))
  2317. {
  2318. Lex();
  2319. bool previousAllowIn = _state.AllowIn;
  2320. _state.AllowIn = true;
  2321. Expression consequent = ParseAssignmentExpression();
  2322. _state.AllowIn = previousAllowIn;
  2323. Expect(":");
  2324. Expression alternate = ParseAssignmentExpression();
  2325. expr = MarkEnd(CreateConditionalExpression(expr, consequent, alternate));
  2326. }
  2327. else
  2328. {
  2329. MarkEnd(new SyntaxNode());
  2330. }
  2331. return expr;
  2332. }
  2333. // 11.13 Assignment Operators
  2334. private Expression ParseAssignmentExpression()
  2335. {
  2336. Expression left;
  2337. Token token = _lookahead;
  2338. MarkStart();
  2339. Expression expr = left = ParseConditionalExpression();
  2340. if (MatchAssign())
  2341. {
  2342. // LeftHandSideExpression
  2343. // Ignore issue as it needs to throw a ReferenceError instead of a SyntaxError
  2344. //if (!isLeftHandSide(left))
  2345. //{
  2346. // ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInAssignment);
  2347. //}
  2348. // 11.13.1
  2349. if (_strict && left.Type == SyntaxNodes.Identifier && IsRestrictedWord(((Identifier) left).Name))
  2350. {
  2351. ThrowErrorTolerant(token, Messages.StrictLHSAssignment);
  2352. }
  2353. token = Lex();
  2354. Expression right = ParseAssignmentExpression();
  2355. expr = CreateAssignmentExpression((string) token.Value, left, right);
  2356. }
  2357. return MarkEndIf(expr);
  2358. }
  2359. // 11.14 Comma Operator
  2360. private Expression ParseExpression()
  2361. {
  2362. MarkStart();
  2363. Expression expr = ParseAssignmentExpression();
  2364. if (Match(","))
  2365. {
  2366. expr = CreateSequenceExpression(new List<Expression> {expr});
  2367. while (_index < _length)
  2368. {
  2369. if (!Match(","))
  2370. {
  2371. break;
  2372. }
  2373. Lex();
  2374. ((SequenceExpression) expr).Expressions.Add(ParseAssignmentExpression());
  2375. }
  2376. }
  2377. return MarkEndIf(expr);
  2378. }
  2379. // 12.1 Block
  2380. private IEnumerable<Statement> ParseStatementList()
  2381. {
  2382. var list = new List<Statement>();
  2383. while (_index < _length)
  2384. {
  2385. if (Match("}"))
  2386. {
  2387. break;
  2388. }
  2389. Statement statement = ParseSourceElement();
  2390. if (statement == null)
  2391. {
  2392. break;
  2393. }
  2394. list.Add(statement);
  2395. }
  2396. return list;
  2397. }
  2398. private BlockStatement ParseBlock()
  2399. {
  2400. MarkStart();
  2401. Expect("{");
  2402. IEnumerable<Statement> block = ParseStatementList();
  2403. Expect("}");
  2404. return MarkEnd(CreateBlockStatement(block));
  2405. }
  2406. // 12.2 Variable Statement
  2407. private Identifier ParseVariableIdentifier()
  2408. {
  2409. MarkStart();
  2410. Token token = Lex();
  2411. if (token.Type != Tokens.Identifier)
  2412. {
  2413. ThrowUnexpected(token);
  2414. }
  2415. return MarkEnd(CreateIdentifier((string) token.Value));
  2416. }
  2417. private VariableDeclarator ParseVariableDeclaration(string kind)
  2418. {
  2419. Expression init = null;
  2420. MarkStart();
  2421. Identifier id = ParseVariableIdentifier();
  2422. // 12.2.1
  2423. if (_strict && IsRestrictedWord(id.Name))
  2424. {
  2425. ThrowErrorTolerant(Token.Empty, Messages.StrictVarName);
  2426. }
  2427. if ("const".Equals(kind))
  2428. {
  2429. Expect("=");
  2430. init = ParseAssignmentExpression();
  2431. }
  2432. else if (Match("="))
  2433. {
  2434. Lex();
  2435. init = ParseAssignmentExpression();
  2436. }
  2437. return MarkEnd(CreateVariableDeclarator(id, init));
  2438. }
  2439. private IEnumerable<VariableDeclarator> ParseVariableDeclarationList(string kind)
  2440. {
  2441. var list = new List<VariableDeclarator>();
  2442. do
  2443. {
  2444. list.Add(ParseVariableDeclaration(kind));
  2445. if (!Match(","))
  2446. {
  2447. break;
  2448. }
  2449. Lex();
  2450. } while (_index < _length);
  2451. return list;
  2452. }
  2453. private VariableDeclaration ParseVariableStatement()
  2454. {
  2455. ExpectKeyword("var");
  2456. IEnumerable<VariableDeclarator> declarations = ParseVariableDeclarationList(null);
  2457. ConsumeSemicolon();
  2458. return CreateVariableDeclaration(declarations, "var");
  2459. }
  2460. // kind may be `const` or `let`
  2461. // Both are experimental and not in the specification yet.
  2462. // see http://wiki.ecmascript.org/doku.php?id=harmony:const
  2463. // and http://wiki.ecmascript.org/doku.php?id=harmony:let
  2464. private VariableDeclaration ParseConstLetDeclaration(string kind)
  2465. {
  2466. MarkStart();
  2467. ExpectKeyword(kind);
  2468. IEnumerable<VariableDeclarator> declarations = ParseVariableDeclarationList(kind);
  2469. ConsumeSemicolon();
  2470. return MarkEnd(CreateVariableDeclaration(declarations, kind));
  2471. }
  2472. // 12.3 Empty Statement
  2473. private EmptyStatement ParseEmptyStatement()
  2474. {
  2475. Expect(";");
  2476. return CreateEmptyStatement();
  2477. }
  2478. // 12.4 Expression Statement
  2479. private ExpressionStatement ParseExpressionStatement()
  2480. {
  2481. Expression expr = ParseExpression();
  2482. ConsumeSemicolon();
  2483. return CreateExpressionStatement(expr);
  2484. }
  2485. // 12.5 If statement
  2486. private IfStatement ParseIfStatement()
  2487. {
  2488. Statement alternate;
  2489. ExpectKeyword("if");
  2490. Expect("(");
  2491. Expression test = ParseExpression();
  2492. Expect(")");
  2493. Statement consequent = ParseStatement();
  2494. if (MatchKeyword("else"))
  2495. {
  2496. Lex();
  2497. alternate = ParseStatement();
  2498. }
  2499. else
  2500. {
  2501. alternate = null;
  2502. }
  2503. return CreateIfStatement(test, consequent, alternate);
  2504. }
  2505. // 12.6 Iteration Statements
  2506. private DoWhileStatement ParseDoWhileStatement()
  2507. {
  2508. ExpectKeyword("do");
  2509. bool oldInIteration = _state.InIteration;
  2510. _state.InIteration = true;
  2511. Statement body = ParseStatement();
  2512. _state.InIteration = oldInIteration;
  2513. ExpectKeyword("while");
  2514. Expect("(");
  2515. Expression test = ParseExpression();
  2516. Expect(")");
  2517. if (Match(";"))
  2518. {
  2519. Lex();
  2520. }
  2521. return CreateDoWhileStatement(body, test);
  2522. }
  2523. private WhileStatement ParseWhileStatement()
  2524. {
  2525. ExpectKeyword("while");
  2526. Expect("(");
  2527. Expression test = ParseExpression();
  2528. Expect(")");
  2529. bool oldInIteration = _state.InIteration;
  2530. _state.InIteration = true;
  2531. Statement body = ParseStatement();
  2532. _state.InIteration = oldInIteration;
  2533. return CreateWhileStatement(test, body);
  2534. }
  2535. private VariableDeclaration ParseForVariableDeclaration()
  2536. {
  2537. MarkStart();
  2538. Token token = Lex();
  2539. IEnumerable<VariableDeclarator> declarations = ParseVariableDeclarationList(null);
  2540. return MarkEnd(CreateVariableDeclaration(declarations, (string) token.Value));
  2541. }
  2542. private Statement ParseForStatement()
  2543. {
  2544. SyntaxNode init = null, left = null;
  2545. Expression right = null;
  2546. Expression test = null, update = null;
  2547. ExpectKeyword("for");
  2548. Expect("(");
  2549. if (Match(";"))
  2550. {
  2551. Lex();
  2552. }
  2553. else
  2554. {
  2555. if (MatchKeyword("var") || MatchKeyword("let"))
  2556. {
  2557. _state.AllowIn = false;
  2558. init = ParseForVariableDeclaration();
  2559. _state.AllowIn = true;
  2560. if (init.As<VariableDeclaration>().Declarations.Count() == 1 && MatchKeyword("in"))
  2561. {
  2562. Lex();
  2563. left = init;
  2564. right = ParseExpression();
  2565. init = null;
  2566. }
  2567. }
  2568. else
  2569. {
  2570. _state.AllowIn = false;
  2571. init = ParseExpression();
  2572. _state.AllowIn = true;
  2573. if (MatchKeyword("in"))
  2574. {
  2575. // LeftHandSideExpression
  2576. if (!isLeftHandSide((Expression) init))
  2577. {
  2578. ThrowErrorTolerant(Token.Empty, Messages.InvalidLHSInForIn);
  2579. }
  2580. Lex();
  2581. left = init;
  2582. right = ParseExpression();
  2583. init = null;
  2584. }
  2585. }
  2586. if (left == null)
  2587. {
  2588. Expect(";");
  2589. }
  2590. }
  2591. if (left == null)
  2592. {
  2593. if (!Match(";"))
  2594. {
  2595. test = ParseExpression();
  2596. }
  2597. Expect(";");
  2598. if (!Match(")"))
  2599. {
  2600. update = ParseExpression();
  2601. }
  2602. }
  2603. Expect(")");
  2604. bool oldInIteration = _state.InIteration;
  2605. _state.InIteration = true;
  2606. Statement body = ParseStatement();
  2607. _state.InIteration = oldInIteration;
  2608. return (left == null)
  2609. ? (Statement) CreateForStatement(init, test, update, body)
  2610. : CreateForInStatement(left, right, body);
  2611. }
  2612. // 12.7 The continue statement
  2613. private Statement ParseContinueStatement()
  2614. {
  2615. Identifier label = null;
  2616. ExpectKeyword("continue");
  2617. // Optimize the most common form: 'continue;'.
  2618. if (_source.CharCodeAt(_index) == 59)
  2619. {
  2620. Lex();
  2621. if (!_state.InIteration)
  2622. {
  2623. ThrowError(Token.Empty, Messages.IllegalContinue);
  2624. }
  2625. return CreateContinueStatement(null);
  2626. }
  2627. if (PeekLineTerminator())
  2628. {
  2629. if (!_state.InIteration)
  2630. {
  2631. ThrowError(Token.Empty, Messages.IllegalContinue);
  2632. }
  2633. return CreateContinueStatement(null);
  2634. }
  2635. if (_lookahead.Type == Tokens.Identifier)
  2636. {
  2637. label = ParseVariableIdentifier();
  2638. string key = "$" + label.Name;
  2639. if (!_state.LabelSet.Contains(key))
  2640. {
  2641. ThrowError(Token.Empty, Messages.UnknownLabel, label.Name);
  2642. }
  2643. }
  2644. ConsumeSemicolon();
  2645. if (label == null && !_state.InIteration)
  2646. {
  2647. ThrowError(Token.Empty, Messages.IllegalContinue);
  2648. }
  2649. return CreateContinueStatement(label);
  2650. }
  2651. // 12.8 The break statement
  2652. private BreakStatement ParseBreakStatement()
  2653. {
  2654. Identifier label = null;
  2655. ExpectKeyword("break");
  2656. // Catch the very common case first: immediately a semicolon (char #59).
  2657. if (_source.CharCodeAt(_index) == 59)
  2658. {
  2659. Lex();
  2660. if (!(_state.InIteration || _state.InSwitch))
  2661. {
  2662. ThrowError(Token.Empty, Messages.IllegalBreak);
  2663. }
  2664. return CreateBreakStatement(null);
  2665. }
  2666. if (PeekLineTerminator())
  2667. {
  2668. if (!(_state.InIteration || _state.InSwitch))
  2669. {
  2670. ThrowError(Token.Empty, Messages.IllegalBreak);
  2671. }
  2672. return CreateBreakStatement(null);
  2673. }
  2674. if (_lookahead.Type == Tokens.Identifier)
  2675. {
  2676. label = ParseVariableIdentifier();
  2677. string key = "$" + label.Name;
  2678. if (!_state.LabelSet.Contains(key))
  2679. {
  2680. ThrowError(Token.Empty, Messages.UnknownLabel, label.Name);
  2681. }
  2682. }
  2683. ConsumeSemicolon();
  2684. if (label == null && !(_state.InIteration || _state.InSwitch))
  2685. {
  2686. ThrowError(Token.Empty, Messages.IllegalBreak);
  2687. }
  2688. return CreateBreakStatement(label);
  2689. }
  2690. // 12.9 The return statement
  2691. private ReturnStatement ParseReturnStatement()
  2692. {
  2693. Expression argument = null;
  2694. ExpectKeyword("return");
  2695. if (!_state.InFunctionBody)
  2696. {
  2697. ThrowErrorTolerant(Token.Empty, Messages.IllegalReturn);
  2698. }
  2699. // 'return' followed by a space and an identifier is very common.
  2700. if (_source.CharCodeAt(_index) == 32)
  2701. {
  2702. if (IsIdentifierStart(_source.CharCodeAt(_index + 1)))
  2703. {
  2704. argument = ParseExpression();
  2705. ConsumeSemicolon();
  2706. return CreateReturnStatement(argument);
  2707. }
  2708. }
  2709. if (PeekLineTerminator())
  2710. {
  2711. return CreateReturnStatement(null);
  2712. }
  2713. if (!Match(";"))
  2714. {
  2715. if (!Match("}") && _lookahead.Type != Tokens.EOF)
  2716. {
  2717. argument = ParseExpression();
  2718. }
  2719. }
  2720. ConsumeSemicolon();
  2721. return CreateReturnStatement(argument);
  2722. }
  2723. // 12.10 The with statement
  2724. private WithStatement ParseWithStatement()
  2725. {
  2726. if (_strict)
  2727. {
  2728. ThrowErrorTolerant(Token.Empty, Messages.StrictModeWith);
  2729. }
  2730. ExpectKeyword("with");
  2731. Expect("(");
  2732. Expression obj = ParseExpression();
  2733. Expect(")");
  2734. Statement body = ParseStatement();
  2735. return CreateWithStatement(obj, body);
  2736. }
  2737. // 12.10 The swith statement
  2738. private SwitchCase ParseSwitchCase()
  2739. {
  2740. Expression test;
  2741. var consequent = new List<Statement>();
  2742. MarkStart();
  2743. if (MatchKeyword("default"))
  2744. {
  2745. Lex();
  2746. test = null;
  2747. }
  2748. else
  2749. {
  2750. ExpectKeyword("case");
  2751. test = ParseExpression();
  2752. }
  2753. Expect(":");
  2754. while (_index < _length)
  2755. {
  2756. if (Match("}") || MatchKeyword("default") || MatchKeyword("case"))
  2757. {
  2758. break;
  2759. }
  2760. Statement statement = ParseStatement();
  2761. consequent.Add(statement);
  2762. }
  2763. return MarkEnd(CreateSwitchCase(test, consequent));
  2764. }
  2765. private SwitchStatement ParseSwitchStatement()
  2766. {
  2767. ExpectKeyword("switch");
  2768. Expect("(");
  2769. Expression discriminant = ParseExpression();
  2770. Expect(")");
  2771. Expect("{");
  2772. var cases = new List<SwitchCase>();
  2773. if (Match("}"))
  2774. {
  2775. Lex();
  2776. return CreateSwitchStatement(discriminant, cases);
  2777. }
  2778. bool oldInSwitch = _state.InSwitch;
  2779. _state.InSwitch = true;
  2780. bool defaultFound = false;
  2781. while (_index < _length)
  2782. {
  2783. if (Match("}"))
  2784. {
  2785. break;
  2786. }
  2787. SwitchCase clause = ParseSwitchCase();
  2788. if (clause.Test == null)
  2789. {
  2790. if (defaultFound)
  2791. {
  2792. ThrowError(Token.Empty, Messages.MultipleDefaultsInSwitch);
  2793. }
  2794. defaultFound = true;
  2795. }
  2796. cases.Add(clause);
  2797. }
  2798. _state.InSwitch = oldInSwitch;
  2799. Expect("}");
  2800. return CreateSwitchStatement(discriminant, cases);
  2801. }
  2802. // 12.13 The throw statement
  2803. private ThrowStatement ParseThrowStatement()
  2804. {
  2805. ExpectKeyword("throw");
  2806. if (PeekLineTerminator())
  2807. {
  2808. ThrowError(Token.Empty, Messages.NewlineAfterThrow);
  2809. }
  2810. Expression argument = ParseExpression();
  2811. ConsumeSemicolon();
  2812. return CreateThrowStatement(argument);
  2813. }
  2814. // 12.14 The try statement
  2815. private CatchClause ParseCatchClause()
  2816. {
  2817. MarkStart();
  2818. ExpectKeyword("catch");
  2819. Expect("(");
  2820. if (Match(")"))
  2821. {
  2822. ThrowUnexpected(_lookahead);
  2823. }
  2824. Identifier param = ParseVariableIdentifier();
  2825. // 12.14.1
  2826. if (_strict && IsRestrictedWord(param.Name))
  2827. {
  2828. ThrowErrorTolerant(Token.Empty, Messages.StrictCatchVariable);
  2829. }
  2830. Expect(")");
  2831. BlockStatement body = ParseBlock();
  2832. return MarkEnd(CreateCatchClause(param, body));
  2833. }
  2834. private TryStatement ParseTryStatement()
  2835. {
  2836. var handlers = new List<CatchClause>();
  2837. Statement finalizer = null;
  2838. ExpectKeyword("try");
  2839. BlockStatement block = ParseBlock();
  2840. if (MatchKeyword("catch"))
  2841. {
  2842. handlers.Add(ParseCatchClause());
  2843. }
  2844. if (MatchKeyword("finally"))
  2845. {
  2846. Lex();
  2847. finalizer = ParseBlock();
  2848. }
  2849. if (handlers.Count == 0 && finalizer == null)
  2850. {
  2851. ThrowError(Token.Empty, Messages.NoCatchOrFinally);
  2852. }
  2853. return CreateTryStatement(block, new Statement[0], handlers, finalizer);
  2854. }
  2855. // 12.15 The debugger statement
  2856. private DebuggerStatement ParseDebuggerStatement()
  2857. {
  2858. ExpectKeyword("debugger");
  2859. ConsumeSemicolon();
  2860. return CreateDebuggerStatement();
  2861. }
  2862. // 12 Statements
  2863. private Statement ParseStatement()
  2864. {
  2865. Tokens type = _lookahead.Type;
  2866. if (type == Tokens.EOF)
  2867. {
  2868. ThrowUnexpected(_lookahead);
  2869. }
  2870. MarkStart();
  2871. if (type == Tokens.Punctuator)
  2872. {
  2873. switch ((string) _lookahead.Value)
  2874. {
  2875. case ";":
  2876. return MarkEnd(ParseEmptyStatement());
  2877. case "{":
  2878. return MarkEnd(ParseBlock());
  2879. case "(":
  2880. return MarkEnd(ParseExpressionStatement());
  2881. }
  2882. }
  2883. if (type == Tokens.Keyword)
  2884. {
  2885. switch ((string) _lookahead.Value)
  2886. {
  2887. case "break":
  2888. return MarkEnd(ParseBreakStatement());
  2889. case "continue":
  2890. return MarkEnd(ParseContinueStatement());
  2891. case "debugger":
  2892. return MarkEnd(ParseDebuggerStatement());
  2893. case "do":
  2894. return MarkEnd(ParseDoWhileStatement());
  2895. case "for":
  2896. return MarkEnd(ParseForStatement());
  2897. case "function":
  2898. return MarkEnd(ParseFunctionDeclaration());
  2899. case "if":
  2900. return MarkEnd(ParseIfStatement());
  2901. case "return":
  2902. return MarkEnd(ParseReturnStatement());
  2903. case "switch":
  2904. return MarkEnd(ParseSwitchStatement());
  2905. case "throw":
  2906. return MarkEnd(ParseThrowStatement());
  2907. case "try":
  2908. return MarkEnd(ParseTryStatement());
  2909. case "var":
  2910. return MarkEnd(ParseVariableStatement());
  2911. case "while":
  2912. return MarkEnd(ParseWhileStatement());
  2913. case "with":
  2914. return MarkEnd(ParseWithStatement());
  2915. }
  2916. }
  2917. Expression expr = ParseExpression();
  2918. // 12.12 Labelled Statements
  2919. if ((expr.Type == SyntaxNodes.Identifier) && Match(":"))
  2920. {
  2921. Lex();
  2922. string key = "$" + ((Identifier) expr).Name;
  2923. if (_state.LabelSet.Contains(key))
  2924. {
  2925. ThrowError(Token.Empty, Messages.Redeclaration, "Label", ((Identifier) expr).Name);
  2926. }
  2927. _state.LabelSet.Add(key);
  2928. Statement labeledBody = ParseStatement();
  2929. _state.LabelSet.Remove(key);
  2930. return MarkEnd(CreateLabeledStatement((Identifier) expr, labeledBody));
  2931. }
  2932. ConsumeSemicolon();
  2933. return MarkEnd(CreateExpressionStatement(expr));
  2934. }
  2935. // 13 Function Definition
  2936. private Statement ParseFunctionSourceElements()
  2937. {
  2938. Token firstRestricted = Token.Empty;
  2939. var sourceElements = new List<Statement>();
  2940. MarkStart();
  2941. Expect("{");
  2942. while (_index < _length)
  2943. {
  2944. if (_lookahead.Type != Tokens.StringLiteral)
  2945. {
  2946. break;
  2947. }
  2948. Token token = _lookahead;
  2949. Statement sourceElement = ParseSourceElement();
  2950. sourceElements.Add(sourceElement);
  2951. if (((ExpressionStatement) sourceElement).Expression.Type != SyntaxNodes.Literal)
  2952. {
  2953. // this is not directive
  2954. break;
  2955. }
  2956. string directive = _source.Slice(token.Range[0] + 1, token.Range[1] - 1);
  2957. if (directive == "use strict")
  2958. {
  2959. _strict = true;
  2960. if (firstRestricted != Token.Empty)
  2961. {
  2962. ThrowErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  2963. }
  2964. }
  2965. else
  2966. {
  2967. if (firstRestricted == Token.Empty && token.Octal)
  2968. {
  2969. firstRestricted = token;
  2970. }
  2971. }
  2972. }
  2973. HashSet<string> oldLabelSet = _state.LabelSet;
  2974. bool oldInIteration = _state.InIteration;
  2975. bool oldInSwitch = _state.InSwitch;
  2976. bool oldInFunctionBody = _state.InFunctionBody;
  2977. _state.LabelSet = new HashSet<string>();
  2978. _state.InIteration = false;
  2979. _state.InSwitch = false;
  2980. _state.InFunctionBody = true;
  2981. while (_index < _length)
  2982. {
  2983. if (Match("}"))
  2984. {
  2985. break;
  2986. }
  2987. Statement sourceElement = ParseSourceElement();
  2988. if (sourceElement == null)
  2989. {
  2990. break;
  2991. }
  2992. sourceElements.Add(sourceElement);
  2993. }
  2994. Expect("}");
  2995. _state.LabelSet = oldLabelSet;
  2996. _state.InIteration = oldInIteration;
  2997. _state.InSwitch = oldInSwitch;
  2998. _state.InFunctionBody = oldInFunctionBody;
  2999. return MarkEnd(CreateBlockStatement(sourceElements));
  3000. }
  3001. private ParsedParameters ParseParams(Token firstRestricted)
  3002. {
  3003. string message = null;
  3004. Token stricted = Token.Empty;
  3005. var parameters = new List<Identifier>();
  3006. Expect("(");
  3007. if (!Match(")"))
  3008. {
  3009. var paramSet = new HashSet<string>();
  3010. while (_index < _length)
  3011. {
  3012. Token token = _lookahead;
  3013. Identifier param = ParseVariableIdentifier();
  3014. string key = '$' + (string) token.Value;
  3015. if (_strict)
  3016. {
  3017. if (IsRestrictedWord((string) token.Value))
  3018. {
  3019. stricted = token;
  3020. message = Messages.StrictParamName;
  3021. }
  3022. if (paramSet.Contains(key))
  3023. {
  3024. stricted = token;
  3025. message = Messages.StrictParamDupe;
  3026. }
  3027. }
  3028. else if (firstRestricted == Token.Empty)
  3029. {
  3030. if (IsRestrictedWord((string) token.Value))
  3031. {
  3032. firstRestricted = token;
  3033. message = Messages.StrictParamName;
  3034. }
  3035. else if (IsStrictModeReservedWord((string) token.Value))
  3036. {
  3037. firstRestricted = token;
  3038. message = Messages.StrictReservedWord;
  3039. }
  3040. else if (paramSet.Contains(key))
  3041. {
  3042. firstRestricted = token;
  3043. message = Messages.StrictParamDupe;
  3044. }
  3045. }
  3046. parameters.Add(param);
  3047. paramSet.Add(key);
  3048. if (Match(")"))
  3049. {
  3050. break;
  3051. }
  3052. Expect(",");
  3053. }
  3054. }
  3055. Expect(")");
  3056. return new ParsedParameters
  3057. {
  3058. Parameters = parameters,
  3059. Stricted = stricted,
  3060. FirstRestricted = firstRestricted,
  3061. Message = message
  3062. };
  3063. }
  3064. private Statement ParseFunctionDeclaration()
  3065. {
  3066. EnterVariableScope();
  3067. EnterFunctionScope();
  3068. Token firstRestricted = Token.Empty;
  3069. string message = null;
  3070. MarkStart();
  3071. ExpectKeyword("function");
  3072. Token token = _lookahead;
  3073. Identifier id = ParseVariableIdentifier();
  3074. if (_strict)
  3075. {
  3076. if (IsRestrictedWord((string) token.Value))
  3077. {
  3078. ThrowErrorTolerant(token, Messages.StrictFunctionName);
  3079. }
  3080. }
  3081. else
  3082. {
  3083. if (IsRestrictedWord((string) token.Value))
  3084. {
  3085. firstRestricted = token;
  3086. message = Messages.StrictFunctionName;
  3087. }
  3088. else if (IsStrictModeReservedWord((string) token.Value))
  3089. {
  3090. firstRestricted = token;
  3091. message = Messages.StrictReservedWord;
  3092. }
  3093. }
  3094. ParsedParameters tmp = ParseParams(firstRestricted);
  3095. IEnumerable<Identifier> parameters = tmp.Parameters;
  3096. Token stricted = tmp.Stricted;
  3097. firstRestricted = tmp.FirstRestricted;
  3098. if (tmp.Message != null)
  3099. {
  3100. message = tmp.Message;
  3101. }
  3102. bool previousStrict = _strict;
  3103. Statement body = ParseFunctionSourceElements();
  3104. if (_strict && firstRestricted != Token.Empty)
  3105. {
  3106. ThrowError(firstRestricted, message);
  3107. }
  3108. if (_strict && stricted != Token.Empty)
  3109. {
  3110. ThrowErrorTolerant(stricted, message);
  3111. }
  3112. bool functionStrict = _strict;
  3113. _strict = previousStrict;
  3114. return MarkEnd(CreateFunctionDeclaration(id, parameters, new Expression[0], body, functionStrict));
  3115. }
  3116. private void EnterVariableScope()
  3117. {
  3118. _variableScopes.Push(new VariableScope());
  3119. }
  3120. private IList<VariableDeclaration> LeaveVariableScope()
  3121. {
  3122. return _variableScopes.Pop().VariableDeclarations;
  3123. }
  3124. private void EnterFunctionScope()
  3125. {
  3126. _functionScopes.Push(new FunctionScope());
  3127. }
  3128. private IList<FunctionDeclaration> LeaveFunctionScope()
  3129. {
  3130. return _functionScopes.Pop().FunctionDeclarations;
  3131. }
  3132. private FunctionExpression ParseFunctionExpression()
  3133. {
  3134. EnterVariableScope();
  3135. EnterFunctionScope();
  3136. Token firstRestricted = Token.Empty;
  3137. string message = null;
  3138. Identifier id = null;
  3139. MarkStart();
  3140. ExpectKeyword("function");
  3141. if (!Match("("))
  3142. {
  3143. Token token = _lookahead;
  3144. id = ParseVariableIdentifier();
  3145. if (_strict)
  3146. {
  3147. if (IsRestrictedWord((string) token.Value))
  3148. {
  3149. ThrowErrorTolerant(token, Messages.StrictFunctionName);
  3150. }
  3151. }
  3152. else
  3153. {
  3154. if (IsRestrictedWord((string) token.Value))
  3155. {
  3156. firstRestricted = token;
  3157. message = Messages.StrictFunctionName;
  3158. }
  3159. else if (IsStrictModeReservedWord((string) token.Value))
  3160. {
  3161. firstRestricted = token;
  3162. message = Messages.StrictReservedWord;
  3163. }
  3164. }
  3165. }
  3166. ParsedParameters tmp = ParseParams(firstRestricted);
  3167. IEnumerable<Identifier> parameters = tmp.Parameters;
  3168. Token stricted = tmp.Stricted;
  3169. firstRestricted = tmp.FirstRestricted;
  3170. if (tmp.Message != null)
  3171. {
  3172. message = tmp.Message;
  3173. }
  3174. bool previousStrict = _strict;
  3175. Statement body = ParseFunctionSourceElements();
  3176. if (_strict && firstRestricted != Token.Empty)
  3177. {
  3178. ThrowError(firstRestricted, message);
  3179. }
  3180. if (_strict && stricted != Token.Empty)
  3181. {
  3182. ThrowErrorTolerant(stricted, message);
  3183. }
  3184. bool functionStrict = _strict;
  3185. _strict = previousStrict;
  3186. return MarkEnd(CreateFunctionExpression(id, parameters, new Expression[0], body, functionStrict));
  3187. }
  3188. // 14 Program
  3189. private Statement ParseSourceElement()
  3190. {
  3191. if (_lookahead.Type == Tokens.Keyword)
  3192. {
  3193. switch ((string) _lookahead.Value)
  3194. {
  3195. case "const":
  3196. case "let":
  3197. return ParseConstLetDeclaration((string) _lookahead.Value);
  3198. case "function":
  3199. return ParseFunctionDeclaration();
  3200. default:
  3201. return ParseStatement();
  3202. }
  3203. }
  3204. if (_lookahead.Type != Tokens.EOF)
  3205. {
  3206. return ParseStatement();
  3207. }
  3208. return null;
  3209. }
  3210. private ICollection<Statement> ParseSourceElements()
  3211. {
  3212. var sourceElements = new List<Statement>();
  3213. Token firstRestricted = Token.Empty;
  3214. Statement sourceElement;
  3215. while (_index < _length)
  3216. {
  3217. Token token = _lookahead;
  3218. if (token.Type != Tokens.StringLiteral)
  3219. {
  3220. break;
  3221. }
  3222. sourceElement = ParseSourceElement();
  3223. sourceElements.Add(sourceElement);
  3224. if (((ExpressionStatement) sourceElement).Expression.Type != SyntaxNodes.Literal)
  3225. {
  3226. // this is not directive
  3227. break;
  3228. }
  3229. string directive = _source.Slice(token.Range[0] + 1, token.Range[1] - 1);
  3230. if (directive == "use strict")
  3231. {
  3232. _strict = true;
  3233. if (firstRestricted != Token.Empty)
  3234. {
  3235. ThrowErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
  3236. }
  3237. }
  3238. else
  3239. {
  3240. if (firstRestricted == Token.Empty && token.Octal)
  3241. {
  3242. firstRestricted = token;
  3243. }
  3244. }
  3245. }
  3246. while (_index < _length)
  3247. {
  3248. sourceElement = ParseSourceElement();
  3249. if (sourceElement == null)
  3250. {
  3251. break;
  3252. }
  3253. sourceElements.Add(sourceElement);
  3254. }
  3255. return sourceElements;
  3256. }
  3257. private Program ParseProgram()
  3258. {
  3259. EnterVariableScope();
  3260. EnterFunctionScope();
  3261. MarkStart();
  3262. Peek();
  3263. ICollection<Statement> body = ParseSourceElements();
  3264. return MarkEnd(CreateProgram(body, _strict));
  3265. }
  3266. private LocationMarker CreateLocationMarker()
  3267. {
  3268. if (!_extra.Loc.HasValue && _extra.Range.Length == 0)
  3269. {
  3270. return null;
  3271. }
  3272. SkipComment();
  3273. return new LocationMarker(_index, _lineNumber, _lineStart);
  3274. }
  3275. public Program Parse(string code)
  3276. {
  3277. return Parse(code, null);
  3278. }
  3279. public Program Parse(string code, ParserOptions options)
  3280. {
  3281. Program program;
  3282. _source = code;
  3283. _index = 0;
  3284. _lineNumber = (_source.Length > 0) ? 1 : 0;
  3285. _lineStart = 0;
  3286. _length = _source.Length;
  3287. _lookahead = null;
  3288. _state = new State
  3289. {
  3290. AllowIn = true,
  3291. LabelSet = new HashSet<string>(),
  3292. InFunctionBody = false,
  3293. InIteration = false,
  3294. InSwitch = false,
  3295. LastCommentStart = -1,
  3296. MarkerStack = new Stack<int>()
  3297. };
  3298. _extra = new Extra
  3299. {
  3300. Range = new int[0],
  3301. Loc = 0,
  3302. };
  3303. if (options != null)
  3304. {
  3305. if (!String.IsNullOrEmpty(options.Source))
  3306. {
  3307. _extra.Source = options.Source;
  3308. }
  3309. if (options.Tokens)
  3310. {
  3311. _extra.Tokens = new List<Token>();
  3312. }
  3313. if (options.Comment)
  3314. {
  3315. _extra.Comments = new List<Comment>();
  3316. }
  3317. if (options.Tolerant)
  3318. {
  3319. _extra.Errors = new List<ParserError>();
  3320. }
  3321. }
  3322. try
  3323. {
  3324. program = ParseProgram();
  3325. if (_extra.Comments != null)
  3326. {
  3327. program.Comments = _extra.Comments;
  3328. }
  3329. if (_extra.Tokens != null)
  3330. {
  3331. program.Tokens = _extra.Tokens;
  3332. }
  3333. if (_extra.Errors != null)
  3334. {
  3335. program.Errors = _extra.Errors;
  3336. }
  3337. }
  3338. finally
  3339. {
  3340. _extra = new Extra();
  3341. }
  3342. return program;
  3343. }
  3344. public FunctionExpression ParseFunctionExpression(string functionExpression)
  3345. {
  3346. _source = functionExpression;
  3347. _index = 0;
  3348. _lineNumber = (_source.Length > 0) ? 1 : 0;
  3349. _lineStart = 0;
  3350. _length = _source.Length;
  3351. _lookahead = null;
  3352. _state = new State
  3353. {
  3354. AllowIn = true,
  3355. LabelSet = new HashSet<string>(),
  3356. InFunctionBody = true,
  3357. InIteration = false,
  3358. InSwitch = false,
  3359. LastCommentStart = -1,
  3360. MarkerStack = new Stack<int>()
  3361. };
  3362. _extra = new Extra
  3363. {
  3364. Range = new int[0],
  3365. Loc = 0,
  3366. };
  3367. _strict = false;
  3368. Peek();
  3369. return ParseFunctionExpression();
  3370. }
  3371. private class Extra
  3372. {
  3373. public int? Loc;
  3374. public int[] Range;
  3375. public string Source;
  3376. public List<Comment> Comments;
  3377. public List<Token> Tokens;
  3378. public List<ParserError> Errors;
  3379. }
  3380. private class LocationMarker
  3381. {
  3382. private readonly int[] _marker;
  3383. public LocationMarker(int index, int lineNumber, int lineStart)
  3384. {
  3385. _marker = new[] {index, lineNumber, index - lineStart, 0, 0, 0};
  3386. }
  3387. public void End(int index, int lineNumber, int lineStart)
  3388. {
  3389. _marker[3] = index;
  3390. _marker[4] = lineNumber;
  3391. _marker[5] = index - lineStart;
  3392. }
  3393. public void Apply(SyntaxNode node, Extra extra, Func<SyntaxNode, SyntaxNode> postProcess)
  3394. {
  3395. if (extra.Range.Length > 0)
  3396. {
  3397. node.Range = new[] {_marker[0], _marker[3]};
  3398. }
  3399. if (extra.Loc.HasValue)
  3400. {
  3401. node.Location = new Location
  3402. {
  3403. Start = new Position
  3404. {
  3405. Line = _marker[1],
  3406. Column = _marker[2]
  3407. },
  3408. End = new Position
  3409. {
  3410. Line = _marker[4],
  3411. Column = _marker[5]
  3412. }
  3413. };
  3414. }
  3415. node = postProcess(node);
  3416. }
  3417. };
  3418. private struct ParsedParameters
  3419. {
  3420. public Token FirstRestricted;
  3421. public string Message;
  3422. public IEnumerable<Identifier> Parameters;
  3423. public Token Stricted;
  3424. }
  3425. private static class Regexes
  3426. {
  3427. 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]");
  3428. 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]");
  3429. };
  3430. }
  3431. }