JavascriptParser.cs 133 KB

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