r.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002
  1. /**
  2. * @license r.js 2.1.17 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved.
  3. * Available via the MIT or new BSD license.
  4. * see: http://github.com/jrburke/requirejs for details
  5. */
  6. /*
  7. * This is a bootstrap script to allow running RequireJS in the command line
  8. * in either a Java/Rhino or Node environment. It is modified by the top-level
  9. * dist.js file to inject other files to completely enable this file. It is
  10. * the shell of the r.js file.
  11. */
  12. /*jslint evil: true, nomen: true, sloppy: true */
  13. /*global readFile: true, process: false, Packages: false, print: false,
  14. console: false, java: false, module: false, requirejsVars, navigator,
  15. document, importScripts, self, location, Components, FileUtils */
  16. var requirejs, require, define, xpcUtil;
  17. (function (console, args, readFileFunc) {
  18. var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire,
  19. nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode, Cc, Ci,
  20. version = '2.1.17',
  21. jsSuffixRegExp = /\.js$/,
  22. commandOption = '',
  23. useLibLoaded = {},
  24. //Used by jslib/rhino/args.js
  25. rhinoArgs = args,
  26. //Used by jslib/xpconnect/args.js
  27. xpconnectArgs = args,
  28. readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null;
  29. function showHelp() {
  30. console.log('See https://github.com/jrburke/r.js for usage.');
  31. }
  32. if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  33. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  34. env = 'browser';
  35. readFile = function (path) {
  36. return fs.readFileSync(path, 'utf8');
  37. };
  38. exec = function (string) {
  39. return eval(string);
  40. };
  41. exists = function () {
  42. console.log('x.js exists not applicable in browser env');
  43. return false;
  44. };
  45. } else if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  46. env = 'node';
  47. //Get the fs module via Node's require before it
  48. //gets replaced. Used in require/node.js
  49. fs = require('fs');
  50. vm = require('vm');
  51. path = require('path');
  52. //In Node 0.7+ existsSync is on fs.
  53. existsForNode = fs.existsSync || path.existsSync;
  54. nodeRequire = require;
  55. nodeDefine = define;
  56. reqMain = require.main;
  57. //Temporarily hide require and define to allow require.js to define
  58. //them.
  59. require = undefined;
  60. define = undefined;
  61. readFile = function (path) {
  62. return fs.readFileSync(path, 'utf8');
  63. };
  64. exec = function (string, name) {
  65. return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string),
  66. name ? fs.realpathSync(name) : '');
  67. };
  68. exists = function (fileName) {
  69. return existsForNode(fileName);
  70. };
  71. fileName = process.argv[2];
  72. if (fileName && fileName.indexOf('-') === 0) {
  73. commandOption = fileName.substring(1);
  74. fileName = process.argv[3];
  75. }
  76. } else if (typeof Packages !== 'undefined') {
  77. env = 'rhino';
  78. fileName = args[0];
  79. if (fileName && fileName.indexOf('-') === 0) {
  80. commandOption = fileName.substring(1);
  81. fileName = args[1];
  82. }
  83. //Exec/readFile differs between Rhino and Nashorn. Rhino has an
  84. //importPackage where Nashorn does not, so branch on that. This is a
  85. //coarser check -- detecting readFile existence might also be enough for
  86. //this spot. However, sticking with importPackage to keep it the same
  87. //as other Rhino/Nashorn detection branches.
  88. if (typeof importPackage !== 'undefined') {
  89. rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext();
  90. exec = function (string, name) {
  91. return rhinoContext.evaluateString(this, string, name, 0, null);
  92. };
  93. } else {
  94. exec = function (string, name) {
  95. load({ script: string, name: name});
  96. };
  97. readFile = readFully;
  98. }
  99. exists = function (fileName) {
  100. return (new java.io.File(fileName)).exists();
  101. };
  102. //Define a console.log for easier logging. Don't
  103. //get fancy though.
  104. if (typeof console === 'undefined') {
  105. console = {
  106. log: function () {
  107. print.apply(undefined, arguments);
  108. }
  109. };
  110. }
  111. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  112. env = 'xpconnect';
  113. Components.utils['import']('resource://gre/modules/FileUtils.jsm');
  114. Cc = Components.classes;
  115. Ci = Components.interfaces;
  116. fileName = args[0];
  117. if (fileName && fileName.indexOf('-') === 0) {
  118. commandOption = fileName.substring(1);
  119. fileName = args[1];
  120. }
  121. xpcUtil = {
  122. isWindows: ('@mozilla.org/windows-registry-key;1' in Cc),
  123. cwd: function () {
  124. return FileUtils.getFile("CurWorkD", []).path;
  125. },
  126. //Remove . and .. from paths, normalize on front slashes
  127. normalize: function (path) {
  128. //There has to be an easier way to do this.
  129. var i, part, ary,
  130. firstChar = path.charAt(0);
  131. if (firstChar !== '/' &&
  132. firstChar !== '\\' &&
  133. path.indexOf(':') === -1) {
  134. //A relative path. Use the current working directory.
  135. path = xpcUtil.cwd() + '/' + path;
  136. }
  137. ary = path.replace(/\\/g, '/').split('/');
  138. for (i = 0; i < ary.length; i += 1) {
  139. part = ary[i];
  140. if (part === '.') {
  141. ary.splice(i, 1);
  142. i -= 1;
  143. } else if (part === '..') {
  144. ary.splice(i - 1, 2);
  145. i -= 2;
  146. }
  147. }
  148. return ary.join('/');
  149. },
  150. xpfile: function (path) {
  151. var fullPath;
  152. try {
  153. fullPath = xpcUtil.normalize(path);
  154. if (xpcUtil.isWindows) {
  155. fullPath = fullPath.replace(/\//g, '\\');
  156. }
  157. return new FileUtils.File(fullPath);
  158. } catch (e) {
  159. throw new Error((fullPath || path) + ' failed: ' + e);
  160. }
  161. },
  162. readFile: function (/*String*/path, /*String?*/encoding) {
  163. //A file read function that can deal with BOMs
  164. encoding = encoding || "utf-8";
  165. var inStream, convertStream,
  166. readData = {},
  167. fileObj = xpcUtil.xpfile(path);
  168. //XPCOM, you so crazy
  169. try {
  170. inStream = Cc['@mozilla.org/network/file-input-stream;1']
  171. .createInstance(Ci.nsIFileInputStream);
  172. inStream.init(fileObj, 1, 0, false);
  173. convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
  174. .createInstance(Ci.nsIConverterInputStream);
  175. convertStream.init(inStream, encoding, inStream.available(),
  176. Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
  177. convertStream.readString(inStream.available(), readData);
  178. return readData.value;
  179. } catch (e) {
  180. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  181. } finally {
  182. if (convertStream) {
  183. convertStream.close();
  184. }
  185. if (inStream) {
  186. inStream.close();
  187. }
  188. }
  189. }
  190. };
  191. readFile = xpcUtil.readFile;
  192. exec = function (string) {
  193. return eval(string);
  194. };
  195. exists = function (fileName) {
  196. return xpcUtil.xpfile(fileName).exists();
  197. };
  198. //Define a console.log for easier logging. Don't
  199. //get fancy though.
  200. if (typeof console === 'undefined') {
  201. console = {
  202. log: function () {
  203. print.apply(undefined, arguments);
  204. }
  205. };
  206. }
  207. }
  208. /** vim: et:ts=4:sw=4:sts=4
  209. * @license RequireJS 2.1.17 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved.
  210. * Available via the MIT or new BSD license.
  211. * see: http://github.com/jrburke/requirejs for details
  212. */
  213. //Not using strict: uneven strict support in browsers, #392, and causes
  214. //problems with requirejs.exec()/transpiler plugins that may not be strict.
  215. /*jslint regexp: true, nomen: true, sloppy: true */
  216. /*global window, navigator, document, importScripts, setTimeout, opera */
  217. (function (global) {
  218. var req, s, head, baseElement, dataMain, src,
  219. interactiveScript, currentlyAddingScript, mainScript, subPath,
  220. version = '2.1.17',
  221. commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
  222. cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
  223. jsSuffixRegExp = /\.js$/,
  224. currDirRegExp = /^\.\//,
  225. op = Object.prototype,
  226. ostring = op.toString,
  227. hasOwn = op.hasOwnProperty,
  228. ap = Array.prototype,
  229. apsp = ap.splice,
  230. isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
  231. isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
  232. //PS3 indicates loaded and complete, but need to wait for complete
  233. //specifically. Sequence is 'loading', 'loaded', execution,
  234. // then 'complete'. The UA check is unfortunate, but not sure how
  235. //to feature test w/o causing perf issues.
  236. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
  237. /^complete$/ : /^(complete|loaded)$/,
  238. defContextName = '_',
  239. //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
  240. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
  241. contexts = {},
  242. cfg = {},
  243. globalDefQueue = [],
  244. useInteractive = false;
  245. function isFunction(it) {
  246. return ostring.call(it) === '[object Function]';
  247. }
  248. function isArray(it) {
  249. return ostring.call(it) === '[object Array]';
  250. }
  251. /**
  252. * Helper function for iterating over an array. If the func returns
  253. * a true value, it will break out of the loop.
  254. */
  255. function each(ary, func) {
  256. if (ary) {
  257. var i;
  258. for (i = 0; i < ary.length; i += 1) {
  259. if (ary[i] && func(ary[i], i, ary)) {
  260. break;
  261. }
  262. }
  263. }
  264. }
  265. /**
  266. * Helper function for iterating over an array backwards. If the func
  267. * returns a true value, it will break out of the loop.
  268. */
  269. function eachReverse(ary, func) {
  270. if (ary) {
  271. var i;
  272. for (i = ary.length - 1; i > -1; i -= 1) {
  273. if (ary[i] && func(ary[i], i, ary)) {
  274. break;
  275. }
  276. }
  277. }
  278. }
  279. function hasProp(obj, prop) {
  280. return hasOwn.call(obj, prop);
  281. }
  282. function getOwn(obj, prop) {
  283. return hasProp(obj, prop) && obj[prop];
  284. }
  285. /**
  286. * Cycles over properties in an object and calls a function for each
  287. * property value. If the function returns a truthy value, then the
  288. * iteration is stopped.
  289. */
  290. function eachProp(obj, func) {
  291. var prop;
  292. for (prop in obj) {
  293. if (hasProp(obj, prop)) {
  294. if (func(obj[prop], prop)) {
  295. break;
  296. }
  297. }
  298. }
  299. }
  300. /**
  301. * Simple function to mix in properties from source into target,
  302. * but only if target does not already have a property of the same name.
  303. */
  304. function mixin(target, source, force, deepStringMixin) {
  305. if (source) {
  306. eachProp(source, function (value, prop) {
  307. if (force || !hasProp(target, prop)) {
  308. if (deepStringMixin && typeof value === 'object' && value &&
  309. !isArray(value) && !isFunction(value) &&
  310. !(value instanceof RegExp)) {
  311. if (!target[prop]) {
  312. target[prop] = {};
  313. }
  314. mixin(target[prop], value, force, deepStringMixin);
  315. } else {
  316. target[prop] = value;
  317. }
  318. }
  319. });
  320. }
  321. return target;
  322. }
  323. //Similar to Function.prototype.bind, but the 'this' object is specified
  324. //first, since it is easier to read/figure out what 'this' will be.
  325. function bind(obj, fn) {
  326. return function () {
  327. return fn.apply(obj, arguments);
  328. };
  329. }
  330. function scripts() {
  331. return document.getElementsByTagName('script');
  332. }
  333. function defaultOnError(err) {
  334. throw err;
  335. }
  336. //Allow getting a global that is expressed in
  337. //dot notation, like 'a.b.c'.
  338. function getGlobal(value) {
  339. if (!value) {
  340. return value;
  341. }
  342. var g = global;
  343. each(value.split('.'), function (part) {
  344. g = g[part];
  345. });
  346. return g;
  347. }
  348. /**
  349. * Constructs an error with a pointer to an URL with more information.
  350. * @param {String} id the error ID that maps to an ID on a web page.
  351. * @param {String} message human readable error.
  352. * @param {Error} [err] the original error, if there is one.
  353. *
  354. * @returns {Error}
  355. */
  356. function makeError(id, msg, err, requireModules) {
  357. var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
  358. e.requireType = id;
  359. e.requireModules = requireModules;
  360. if (err) {
  361. e.originalError = err;
  362. }
  363. return e;
  364. }
  365. if (typeof define !== 'undefined') {
  366. //If a define is already in play via another AMD loader,
  367. //do not overwrite.
  368. return;
  369. }
  370. if (typeof requirejs !== 'undefined') {
  371. if (isFunction(requirejs)) {
  372. //Do not overwrite an existing requirejs instance.
  373. return;
  374. }
  375. cfg = requirejs;
  376. requirejs = undefined;
  377. }
  378. //Allow for a require config object
  379. if (typeof require !== 'undefined' && !isFunction(require)) {
  380. //assume it is a config object.
  381. cfg = require;
  382. require = undefined;
  383. }
  384. function newContext(contextName) {
  385. var inCheckLoaded, Module, context, handlers,
  386. checkLoadedTimeoutId,
  387. config = {
  388. //Defaults. Do not set a default for map
  389. //config to speed up normalize(), which
  390. //will run faster if there is no default.
  391. waitSeconds: 7,
  392. baseUrl: './',
  393. paths: {},
  394. bundles: {},
  395. pkgs: {},
  396. shim: {},
  397. config: {}
  398. },
  399. registry = {},
  400. //registry of just enabled modules, to speed
  401. //cycle breaking code when lots of modules
  402. //are registered, but not activated.
  403. enabledRegistry = {},
  404. undefEvents = {},
  405. defQueue = [],
  406. defined = {},
  407. urlFetched = {},
  408. bundlesMap = {},
  409. requireCounter = 1,
  410. unnormalizedCounter = 1;
  411. /**
  412. * Trims the . and .. from an array of path segments.
  413. * It will keep a leading path segment if a .. will become
  414. * the first path segment, to help with module name lookups,
  415. * which act like paths, but can be remapped. But the end result,
  416. * all paths that use this function should look normalized.
  417. * NOTE: this method MODIFIES the input array.
  418. * @param {Array} ary the array of path segments.
  419. */
  420. function trimDots(ary) {
  421. var i, part;
  422. for (i = 0; i < ary.length; i++) {
  423. part = ary[i];
  424. if (part === '.') {
  425. ary.splice(i, 1);
  426. i -= 1;
  427. } else if (part === '..') {
  428. // If at the start, or previous value is still ..,
  429. // keep them so that when converted to a path it may
  430. // still work when converted to a path, even though
  431. // as an ID it is less than ideal. In larger point
  432. // releases, may be better to just kick out an error.
  433. if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
  434. continue;
  435. } else if (i > 0) {
  436. ary.splice(i - 1, 2);
  437. i -= 2;
  438. }
  439. }
  440. }
  441. }
  442. /**
  443. * Given a relative module name, like ./something, normalize it to
  444. * a real name that can be mapped to a path.
  445. * @param {String} name the relative name
  446. * @param {String} baseName a real name that the name arg is relative
  447. * to.
  448. * @param {Boolean} applyMap apply the map config to the value. Should
  449. * only be done if this normalization is for a dependency ID.
  450. * @returns {String} normalized name
  451. */
  452. function normalize(name, baseName, applyMap) {
  453. var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
  454. foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
  455. baseParts = (baseName && baseName.split('/')),
  456. map = config.map,
  457. starMap = map && map['*'];
  458. //Adjust any relative paths.
  459. if (name) {
  460. name = name.split('/');
  461. lastIndex = name.length - 1;
  462. // If wanting node ID compatibility, strip .js from end
  463. // of IDs. Have to do this here, and not in nameToUrl
  464. // because node allows either .js or non .js to map
  465. // to same file.
  466. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
  467. name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
  468. }
  469. // Starts with a '.' so need the baseName
  470. if (name[0].charAt(0) === '.' && baseParts) {
  471. //Convert baseName to array, and lop off the last part,
  472. //so that . matches that 'directory' and not name of the baseName's
  473. //module. For instance, baseName of 'one/two/three', maps to
  474. //'one/two/three.js', but we want the directory, 'one/two' for
  475. //this normalization.
  476. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
  477. name = normalizedBaseParts.concat(name);
  478. }
  479. trimDots(name);
  480. name = name.join('/');
  481. }
  482. //Apply map config if available.
  483. if (applyMap && map && (baseParts || starMap)) {
  484. nameParts = name.split('/');
  485. outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
  486. nameSegment = nameParts.slice(0, i).join('/');
  487. if (baseParts) {
  488. //Find the longest baseName segment match in the config.
  489. //So, do joins on the biggest to smallest lengths of baseParts.
  490. for (j = baseParts.length; j > 0; j -= 1) {
  491. mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
  492. //baseName segment has config, find if it has one for
  493. //this name.
  494. if (mapValue) {
  495. mapValue = getOwn(mapValue, nameSegment);
  496. if (mapValue) {
  497. //Match, update name to the new value.
  498. foundMap = mapValue;
  499. foundI = i;
  500. break outerLoop;
  501. }
  502. }
  503. }
  504. }
  505. //Check for a star map match, but just hold on to it,
  506. //if there is a shorter segment match later in a matching
  507. //config, then favor over this star map.
  508. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
  509. foundStarMap = getOwn(starMap, nameSegment);
  510. starI = i;
  511. }
  512. }
  513. if (!foundMap && foundStarMap) {
  514. foundMap = foundStarMap;
  515. foundI = starI;
  516. }
  517. if (foundMap) {
  518. nameParts.splice(0, foundI, foundMap);
  519. name = nameParts.join('/');
  520. }
  521. }
  522. // If the name points to a package's name, use
  523. // the package main instead.
  524. pkgMain = getOwn(config.pkgs, name);
  525. return pkgMain ? pkgMain : name;
  526. }
  527. function removeScript(name) {
  528. if (isBrowser) {
  529. each(scripts(), function (scriptNode) {
  530. if (scriptNode.getAttribute('data-requiremodule') === name &&
  531. scriptNode.getAttribute('data-requirecontext') === context.contextName) {
  532. scriptNode.parentNode.removeChild(scriptNode);
  533. return true;
  534. }
  535. });
  536. }
  537. }
  538. function hasPathFallback(id) {
  539. var pathConfig = getOwn(config.paths, id);
  540. if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
  541. //Pop off the first array value, since it failed, and
  542. //retry
  543. pathConfig.shift();
  544. context.require.undef(id);
  545. //Custom require that does not do map translation, since
  546. //ID is "absolute", already mapped/resolved.
  547. context.makeRequire(null, {
  548. skipMap: true
  549. })([id]);
  550. return true;
  551. }
  552. }
  553. //Turns a plugin!resource to [plugin, resource]
  554. //with the plugin being undefined if the name
  555. //did not have a plugin prefix.
  556. function splitPrefix(name) {
  557. var prefix,
  558. index = name ? name.indexOf('!') : -1;
  559. if (index > -1) {
  560. prefix = name.substring(0, index);
  561. name = name.substring(index + 1, name.length);
  562. }
  563. return [prefix, name];
  564. }
  565. /**
  566. * Creates a module mapping that includes plugin prefix, module
  567. * name, and path. If parentModuleMap is provided it will
  568. * also normalize the name via require.normalize()
  569. *
  570. * @param {String} name the module name
  571. * @param {String} [parentModuleMap] parent module map
  572. * for the module name, used to resolve relative names.
  573. * @param {Boolean} isNormalized: is the ID already normalized.
  574. * This is true if this call is done for a define() module ID.
  575. * @param {Boolean} applyMap: apply the map config to the ID.
  576. * Should only be true if this map is for a dependency.
  577. *
  578. * @returns {Object}
  579. */
  580. function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
  581. var url, pluginModule, suffix, nameParts,
  582. prefix = null,
  583. parentName = parentModuleMap ? parentModuleMap.name : null,
  584. originalName = name,
  585. isDefine = true,
  586. normalizedName = '';
  587. //If no name, then it means it is a require call, generate an
  588. //internal name.
  589. if (!name) {
  590. isDefine = false;
  591. name = '_@r' + (requireCounter += 1);
  592. }
  593. nameParts = splitPrefix(name);
  594. prefix = nameParts[0];
  595. name = nameParts[1];
  596. if (prefix) {
  597. prefix = normalize(prefix, parentName, applyMap);
  598. pluginModule = getOwn(defined, prefix);
  599. }
  600. //Account for relative paths if there is a base name.
  601. if (name) {
  602. if (prefix) {
  603. if (pluginModule && pluginModule.normalize) {
  604. //Plugin is loaded, use its normalize method.
  605. normalizedName = pluginModule.normalize(name, function (name) {
  606. return normalize(name, parentName, applyMap);
  607. });
  608. } else {
  609. // If nested plugin references, then do not try to
  610. // normalize, as it will not normalize correctly. This
  611. // places a restriction on resourceIds, and the longer
  612. // term solution is not to normalize until plugins are
  613. // loaded and all normalizations to allow for async
  614. // loading of a loader plugin. But for now, fixes the
  615. // common uses. Details in #1131
  616. normalizedName = name.indexOf('!') === -1 ?
  617. normalize(name, parentName, applyMap) :
  618. name;
  619. }
  620. } else {
  621. //A regular module.
  622. normalizedName = normalize(name, parentName, applyMap);
  623. //Normalized name may be a plugin ID due to map config
  624. //application in normalize. The map config values must
  625. //already be normalized, so do not need to redo that part.
  626. nameParts = splitPrefix(normalizedName);
  627. prefix = nameParts[0];
  628. normalizedName = nameParts[1];
  629. isNormalized = true;
  630. url = context.nameToUrl(normalizedName);
  631. }
  632. }
  633. //If the id is a plugin id that cannot be determined if it needs
  634. //normalization, stamp it with a unique ID so two matching relative
  635. //ids that may conflict can be separate.
  636. suffix = prefix && !pluginModule && !isNormalized ?
  637. '_unnormalized' + (unnormalizedCounter += 1) :
  638. '';
  639. return {
  640. prefix: prefix,
  641. name: normalizedName,
  642. parentMap: parentModuleMap,
  643. unnormalized: !!suffix,
  644. url: url,
  645. originalName: originalName,
  646. isDefine: isDefine,
  647. id: (prefix ?
  648. prefix + '!' + normalizedName :
  649. normalizedName) + suffix
  650. };
  651. }
  652. function getModule(depMap) {
  653. var id = depMap.id,
  654. mod = getOwn(registry, id);
  655. if (!mod) {
  656. mod = registry[id] = new context.Module(depMap);
  657. }
  658. return mod;
  659. }
  660. function on(depMap, name, fn) {
  661. var id = depMap.id,
  662. mod = getOwn(registry, id);
  663. if (hasProp(defined, id) &&
  664. (!mod || mod.defineEmitComplete)) {
  665. if (name === 'defined') {
  666. fn(defined[id]);
  667. }
  668. } else {
  669. mod = getModule(depMap);
  670. if (mod.error && name === 'error') {
  671. fn(mod.error);
  672. } else {
  673. mod.on(name, fn);
  674. }
  675. }
  676. }
  677. function onError(err, errback) {
  678. var ids = err.requireModules,
  679. notified = false;
  680. if (errback) {
  681. errback(err);
  682. } else {
  683. each(ids, function (id) {
  684. var mod = getOwn(registry, id);
  685. if (mod) {
  686. //Set error on module, so it skips timeout checks.
  687. mod.error = err;
  688. if (mod.events.error) {
  689. notified = true;
  690. mod.emit('error', err);
  691. }
  692. }
  693. });
  694. if (!notified) {
  695. req.onError(err);
  696. }
  697. }
  698. }
  699. /**
  700. * Internal method to transfer globalQueue items to this context's
  701. * defQueue.
  702. */
  703. function takeGlobalQueue() {
  704. //Push all the globalDefQueue items into the context's defQueue
  705. if (globalDefQueue.length) {
  706. //Array splice in the values since the context code has a
  707. //local var ref to defQueue, so cannot just reassign the one
  708. //on context.
  709. apsp.apply(defQueue,
  710. [defQueue.length, 0].concat(globalDefQueue));
  711. globalDefQueue = [];
  712. }
  713. }
  714. handlers = {
  715. 'require': function (mod) {
  716. if (mod.require) {
  717. return mod.require;
  718. } else {
  719. return (mod.require = context.makeRequire(mod.map));
  720. }
  721. },
  722. 'exports': function (mod) {
  723. mod.usingExports = true;
  724. if (mod.map.isDefine) {
  725. if (mod.exports) {
  726. return (defined[mod.map.id] = mod.exports);
  727. } else {
  728. return (mod.exports = defined[mod.map.id] = {});
  729. }
  730. }
  731. },
  732. 'module': function (mod) {
  733. if (mod.module) {
  734. return mod.module;
  735. } else {
  736. return (mod.module = {
  737. id: mod.map.id,
  738. uri: mod.map.url,
  739. config: function () {
  740. return getOwn(config.config, mod.map.id) || {};
  741. },
  742. exports: mod.exports || (mod.exports = {})
  743. });
  744. }
  745. }
  746. };
  747. function cleanRegistry(id) {
  748. //Clean up machinery used for waiting modules.
  749. delete registry[id];
  750. delete enabledRegistry[id];
  751. }
  752. function breakCycle(mod, traced, processed) {
  753. var id = mod.map.id;
  754. if (mod.error) {
  755. mod.emit('error', mod.error);
  756. } else {
  757. traced[id] = true;
  758. each(mod.depMaps, function (depMap, i) {
  759. var depId = depMap.id,
  760. dep = getOwn(registry, depId);
  761. //Only force things that have not completed
  762. //being defined, so still in the registry,
  763. //and only if it has not been matched up
  764. //in the module already.
  765. if (dep && !mod.depMatched[i] && !processed[depId]) {
  766. if (getOwn(traced, depId)) {
  767. mod.defineDep(i, defined[depId]);
  768. mod.check(); //pass false?
  769. } else {
  770. breakCycle(dep, traced, processed);
  771. }
  772. }
  773. });
  774. processed[id] = true;
  775. }
  776. }
  777. function checkLoaded() {
  778. var err, usingPathFallback,
  779. waitInterval = config.waitSeconds * 1000,
  780. //It is possible to disable the wait interval by using waitSeconds of 0.
  781. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
  782. noLoads = [],
  783. reqCalls = [],
  784. stillLoading = false,
  785. needCycleCheck = true;
  786. //Do not bother if this call was a result of a cycle break.
  787. if (inCheckLoaded) {
  788. return;
  789. }
  790. inCheckLoaded = true;
  791. //Figure out the state of all the modules.
  792. eachProp(enabledRegistry, function (mod) {
  793. var map = mod.map,
  794. modId = map.id;
  795. //Skip things that are not enabled or in error state.
  796. if (!mod.enabled) {
  797. return;
  798. }
  799. if (!map.isDefine) {
  800. reqCalls.push(mod);
  801. }
  802. if (!mod.error) {
  803. //If the module should be executed, and it has not
  804. //been inited and time is up, remember it.
  805. if (!mod.inited && expired) {
  806. if (hasPathFallback(modId)) {
  807. usingPathFallback = true;
  808. stillLoading = true;
  809. } else {
  810. noLoads.push(modId);
  811. removeScript(modId);
  812. }
  813. } else if (!mod.inited && mod.fetched && map.isDefine) {
  814. stillLoading = true;
  815. if (!map.prefix) {
  816. //No reason to keep looking for unfinished
  817. //loading. If the only stillLoading is a
  818. //plugin resource though, keep going,
  819. //because it may be that a plugin resource
  820. //is waiting on a non-plugin cycle.
  821. return (needCycleCheck = false);
  822. }
  823. }
  824. }
  825. });
  826. if (expired && noLoads.length) {
  827. //If wait time expired, throw error of unloaded modules.
  828. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
  829. err.contextName = context.contextName;
  830. return onError(err);
  831. }
  832. //Not expired, check for a cycle.
  833. if (needCycleCheck) {
  834. each(reqCalls, function (mod) {
  835. breakCycle(mod, {}, {});
  836. });
  837. }
  838. //If still waiting on loads, and the waiting load is something
  839. //other than a plugin resource, or there are still outstanding
  840. //scripts, then just try back later.
  841. if ((!expired || usingPathFallback) && stillLoading) {
  842. //Something is still waiting to load. Wait for it, but only
  843. //if a timeout is not already in effect.
  844. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
  845. checkLoadedTimeoutId = setTimeout(function () {
  846. checkLoadedTimeoutId = 0;
  847. checkLoaded();
  848. }, 50);
  849. }
  850. }
  851. inCheckLoaded = false;
  852. }
  853. Module = function (map) {
  854. this.events = getOwn(undefEvents, map.id) || {};
  855. this.map = map;
  856. this.shim = getOwn(config.shim, map.id);
  857. this.depExports = [];
  858. this.depMaps = [];
  859. this.depMatched = [];
  860. this.pluginMaps = {};
  861. this.depCount = 0;
  862. /* this.exports this.factory
  863. this.depMaps = [],
  864. this.enabled, this.fetched
  865. */
  866. };
  867. Module.prototype = {
  868. init: function (depMaps, factory, errback, options) {
  869. options = options || {};
  870. //Do not do more inits if already done. Can happen if there
  871. //are multiple define calls for the same module. That is not
  872. //a normal, common case, but it is also not unexpected.
  873. if (this.inited) {
  874. return;
  875. }
  876. this.factory = factory;
  877. if (errback) {
  878. //Register for errors on this module.
  879. this.on('error', errback);
  880. } else if (this.events.error) {
  881. //If no errback already, but there are error listeners
  882. //on this module, set up an errback to pass to the deps.
  883. errback = bind(this, function (err) {
  884. this.emit('error', err);
  885. });
  886. }
  887. //Do a copy of the dependency array, so that
  888. //source inputs are not modified. For example
  889. //"shim" deps are passed in here directly, and
  890. //doing a direct modification of the depMaps array
  891. //would affect that config.
  892. this.depMaps = depMaps && depMaps.slice(0);
  893. this.errback = errback;
  894. //Indicate this module has be initialized
  895. this.inited = true;
  896. this.ignore = options.ignore;
  897. //Could have option to init this module in enabled mode,
  898. //or could have been previously marked as enabled. However,
  899. //the dependencies are not known until init is called. So
  900. //if enabled previously, now trigger dependencies as enabled.
  901. if (options.enabled || this.enabled) {
  902. //Enable this module and dependencies.
  903. //Will call this.check()
  904. this.enable();
  905. } else {
  906. this.check();
  907. }
  908. },
  909. defineDep: function (i, depExports) {
  910. //Because of cycles, defined callback for a given
  911. //export can be called more than once.
  912. if (!this.depMatched[i]) {
  913. this.depMatched[i] = true;
  914. this.depCount -= 1;
  915. this.depExports[i] = depExports;
  916. }
  917. },
  918. fetch: function () {
  919. if (this.fetched) {
  920. return;
  921. }
  922. this.fetched = true;
  923. context.startTime = (new Date()).getTime();
  924. var map = this.map;
  925. //If the manager is for a plugin managed resource,
  926. //ask the plugin to load it now.
  927. if (this.shim) {
  928. context.makeRequire(this.map, {
  929. enableBuildCallback: true
  930. })(this.shim.deps || [], bind(this, function () {
  931. return map.prefix ? this.callPlugin() : this.load();
  932. }));
  933. } else {
  934. //Regular dependency.
  935. return map.prefix ? this.callPlugin() : this.load();
  936. }
  937. },
  938. load: function () {
  939. var url = this.map.url;
  940. //Regular dependency.
  941. if (!urlFetched[url]) {
  942. urlFetched[url] = true;
  943. context.load(this.map.id, url);
  944. }
  945. },
  946. /**
  947. * Checks if the module is ready to define itself, and if so,
  948. * define it.
  949. */
  950. check: function () {
  951. if (!this.enabled || this.enabling) {
  952. return;
  953. }
  954. var err, cjsModule,
  955. id = this.map.id,
  956. depExports = this.depExports,
  957. exports = this.exports,
  958. factory = this.factory;
  959. if (!this.inited) {
  960. this.fetch();
  961. } else if (this.error) {
  962. this.emit('error', this.error);
  963. } else if (!this.defining) {
  964. //The factory could trigger another require call
  965. //that would result in checking this module to
  966. //define itself again. If already in the process
  967. //of doing that, skip this work.
  968. this.defining = true;
  969. if (this.depCount < 1 && !this.defined) {
  970. if (isFunction(factory)) {
  971. //If there is an error listener, favor passing
  972. //to that instead of throwing an error. However,
  973. //only do it for define()'d modules. require
  974. //errbacks should not be called for failures in
  975. //their callbacks (#699). However if a global
  976. //onError is set, use that.
  977. if ((this.events.error && this.map.isDefine) ||
  978. req.onError !== defaultOnError) {
  979. try {
  980. exports = context.execCb(id, factory, depExports, exports);
  981. } catch (e) {
  982. err = e;
  983. }
  984. } else {
  985. exports = context.execCb(id, factory, depExports, exports);
  986. }
  987. // Favor return value over exports. If node/cjs in play,
  988. // then will not have a return value anyway. Favor
  989. // module.exports assignment over exports object.
  990. if (this.map.isDefine && exports === undefined) {
  991. cjsModule = this.module;
  992. if (cjsModule) {
  993. exports = cjsModule.exports;
  994. } else if (this.usingExports) {
  995. //exports already set the defined value.
  996. exports = this.exports;
  997. }
  998. }
  999. if (err) {
  1000. err.requireMap = this.map;
  1001. err.requireModules = this.map.isDefine ? [this.map.id] : null;
  1002. err.requireType = this.map.isDefine ? 'define' : 'require';
  1003. return onError((this.error = err));
  1004. }
  1005. } else {
  1006. //Just a literal value
  1007. exports = factory;
  1008. }
  1009. this.exports = exports;
  1010. if (this.map.isDefine && !this.ignore) {
  1011. defined[id] = exports;
  1012. if (req.onResourceLoad) {
  1013. req.onResourceLoad(context, this.map, this.depMaps);
  1014. }
  1015. }
  1016. //Clean up
  1017. cleanRegistry(id);
  1018. this.defined = true;
  1019. }
  1020. //Finished the define stage. Allow calling check again
  1021. //to allow define notifications below in the case of a
  1022. //cycle.
  1023. this.defining = false;
  1024. if (this.defined && !this.defineEmitted) {
  1025. this.defineEmitted = true;
  1026. this.emit('defined', this.exports);
  1027. this.defineEmitComplete = true;
  1028. }
  1029. }
  1030. },
  1031. callPlugin: function () {
  1032. var map = this.map,
  1033. id = map.id,
  1034. //Map already normalized the prefix.
  1035. pluginMap = makeModuleMap(map.prefix);
  1036. //Mark this as a dependency for this plugin, so it
  1037. //can be traced for cycles.
  1038. this.depMaps.push(pluginMap);
  1039. on(pluginMap, 'defined', bind(this, function (plugin) {
  1040. var load, normalizedMap, normalizedMod,
  1041. bundleId = getOwn(bundlesMap, this.map.id),
  1042. name = this.map.name,
  1043. parentName = this.map.parentMap ? this.map.parentMap.name : null,
  1044. localRequire = context.makeRequire(map.parentMap, {
  1045. enableBuildCallback: true
  1046. });
  1047. //If current map is not normalized, wait for that
  1048. //normalized name to load instead of continuing.
  1049. if (this.map.unnormalized) {
  1050. //Normalize the ID if the plugin allows it.
  1051. if (plugin.normalize) {
  1052. name = plugin.normalize(name, function (name) {
  1053. return normalize(name, parentName, true);
  1054. }) || '';
  1055. }
  1056. //prefix and name should already be normalized, no need
  1057. //for applying map config again either.
  1058. normalizedMap = makeModuleMap(map.prefix + '!' + name,
  1059. this.map.parentMap);
  1060. on(normalizedMap,
  1061. 'defined', bind(this, function (value) {
  1062. this.init([], function () { return value; }, null, {
  1063. enabled: true,
  1064. ignore: true
  1065. });
  1066. }));
  1067. normalizedMod = getOwn(registry, normalizedMap.id);
  1068. if (normalizedMod) {
  1069. //Mark this as a dependency for this plugin, so it
  1070. //can be traced for cycles.
  1071. this.depMaps.push(normalizedMap);
  1072. if (this.events.error) {
  1073. normalizedMod.on('error', bind(this, function (err) {
  1074. this.emit('error', err);
  1075. }));
  1076. }
  1077. normalizedMod.enable();
  1078. }
  1079. return;
  1080. }
  1081. //If a paths config, then just load that file instead to
  1082. //resolve the plugin, as it is built into that paths layer.
  1083. if (bundleId) {
  1084. this.map.url = context.nameToUrl(bundleId);
  1085. this.load();
  1086. return;
  1087. }
  1088. load = bind(this, function (value) {
  1089. this.init([], function () { return value; }, null, {
  1090. enabled: true
  1091. });
  1092. });
  1093. load.error = bind(this, function (err) {
  1094. this.inited = true;
  1095. this.error = err;
  1096. err.requireModules = [id];
  1097. //Remove temp unnormalized modules for this module,
  1098. //since they will never be resolved otherwise now.
  1099. eachProp(registry, function (mod) {
  1100. if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
  1101. cleanRegistry(mod.map.id);
  1102. }
  1103. });
  1104. onError(err);
  1105. });
  1106. //Allow plugins to load other code without having to know the
  1107. //context or how to 'complete' the load.
  1108. load.fromText = bind(this, function (text, textAlt) {
  1109. /*jslint evil: true */
  1110. var moduleName = map.name,
  1111. moduleMap = makeModuleMap(moduleName),
  1112. hasInteractive = useInteractive;
  1113. //As of 2.1.0, support just passing the text, to reinforce
  1114. //fromText only being called once per resource. Still
  1115. //support old style of passing moduleName but discard
  1116. //that moduleName in favor of the internal ref.
  1117. if (textAlt) {
  1118. text = textAlt;
  1119. }
  1120. //Turn off interactive script matching for IE for any define
  1121. //calls in the text, then turn it back on at the end.
  1122. if (hasInteractive) {
  1123. useInteractive = false;
  1124. }
  1125. //Prime the system by creating a module instance for
  1126. //it.
  1127. getModule(moduleMap);
  1128. //Transfer any config to this other module.
  1129. if (hasProp(config.config, id)) {
  1130. config.config[moduleName] = config.config[id];
  1131. }
  1132. try {
  1133. req.exec(text);
  1134. } catch (e) {
  1135. return onError(makeError('fromtexteval',
  1136. 'fromText eval for ' + id +
  1137. ' failed: ' + e,
  1138. e,
  1139. [id]));
  1140. }
  1141. if (hasInteractive) {
  1142. useInteractive = true;
  1143. }
  1144. //Mark this as a dependency for the plugin
  1145. //resource
  1146. this.depMaps.push(moduleMap);
  1147. //Support anonymous modules.
  1148. context.completeLoad(moduleName);
  1149. //Bind the value of that module to the value for this
  1150. //resource ID.
  1151. localRequire([moduleName], load);
  1152. });
  1153. //Use parentName here since the plugin's name is not reliable,
  1154. //could be some weird string with no path that actually wants to
  1155. //reference the parentName's path.
  1156. plugin.load(map.name, localRequire, load, config);
  1157. }));
  1158. context.enable(pluginMap, this);
  1159. this.pluginMaps[pluginMap.id] = pluginMap;
  1160. },
  1161. enable: function () {
  1162. enabledRegistry[this.map.id] = this;
  1163. this.enabled = true;
  1164. //Set flag mentioning that the module is enabling,
  1165. //so that immediate calls to the defined callbacks
  1166. //for dependencies do not trigger inadvertent load
  1167. //with the depCount still being zero.
  1168. this.enabling = true;
  1169. //Enable each dependency
  1170. each(this.depMaps, bind(this, function (depMap, i) {
  1171. var id, mod, handler;
  1172. if (typeof depMap === 'string') {
  1173. //Dependency needs to be converted to a depMap
  1174. //and wired up to this module.
  1175. depMap = makeModuleMap(depMap,
  1176. (this.map.isDefine ? this.map : this.map.parentMap),
  1177. false,
  1178. !this.skipMap);
  1179. this.depMaps[i] = depMap;
  1180. handler = getOwn(handlers, depMap.id);
  1181. if (handler) {
  1182. this.depExports[i] = handler(this);
  1183. return;
  1184. }
  1185. this.depCount += 1;
  1186. on(depMap, 'defined', bind(this, function (depExports) {
  1187. this.defineDep(i, depExports);
  1188. this.check();
  1189. }));
  1190. if (this.errback) {
  1191. on(depMap, 'error', bind(this, this.errback));
  1192. } else if (this.events.error) {
  1193. // No direct errback on this module, but something
  1194. // else is listening for errors, so be sure to
  1195. // propagate the error correctly.
  1196. on(depMap, 'error', bind(this, function(err) {
  1197. this.emit('error', err);
  1198. }));
  1199. }
  1200. }
  1201. id = depMap.id;
  1202. mod = registry[id];
  1203. //Skip special modules like 'require', 'exports', 'module'
  1204. //Also, don't call enable if it is already enabled,
  1205. //important in circular dependency cases.
  1206. if (!hasProp(handlers, id) && mod && !mod.enabled) {
  1207. context.enable(depMap, this);
  1208. }
  1209. }));
  1210. //Enable each plugin that is used in
  1211. //a dependency
  1212. eachProp(this.pluginMaps, bind(this, function (pluginMap) {
  1213. var mod = getOwn(registry, pluginMap.id);
  1214. if (mod && !mod.enabled) {
  1215. context.enable(pluginMap, this);
  1216. }
  1217. }));
  1218. this.enabling = false;
  1219. this.check();
  1220. },
  1221. on: function (name, cb) {
  1222. var cbs = this.events[name];
  1223. if (!cbs) {
  1224. cbs = this.events[name] = [];
  1225. }
  1226. cbs.push(cb);
  1227. },
  1228. emit: function (name, evt) {
  1229. each(this.events[name], function (cb) {
  1230. cb(evt);
  1231. });
  1232. if (name === 'error') {
  1233. //Now that the error handler was triggered, remove
  1234. //the listeners, since this broken Module instance
  1235. //can stay around for a while in the registry.
  1236. delete this.events[name];
  1237. }
  1238. }
  1239. };
  1240. function callGetModule(args) {
  1241. //Skip modules already defined.
  1242. if (!hasProp(defined, args[0])) {
  1243. getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
  1244. }
  1245. }
  1246. function removeListener(node, func, name, ieName) {
  1247. //Favor detachEvent because of IE9
  1248. //issue, see attachEvent/addEventListener comment elsewhere
  1249. //in this file.
  1250. if (node.detachEvent && !isOpera) {
  1251. //Probably IE. If not it will throw an error, which will be
  1252. //useful to know.
  1253. if (ieName) {
  1254. node.detachEvent(ieName, func);
  1255. }
  1256. } else {
  1257. node.removeEventListener(name, func, false);
  1258. }
  1259. }
  1260. /**
  1261. * Given an event from a script node, get the requirejs info from it,
  1262. * and then removes the event listeners on the node.
  1263. * @param {Event} evt
  1264. * @returns {Object}
  1265. */
  1266. function getScriptData(evt) {
  1267. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1268. //all old browsers will be supported, but this one was easy enough
  1269. //to support and still makes sense.
  1270. var node = evt.currentTarget || evt.srcElement;
  1271. //Remove the listeners once here.
  1272. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
  1273. removeListener(node, context.onScriptError, 'error');
  1274. return {
  1275. node: node,
  1276. id: node && node.getAttribute('data-requiremodule')
  1277. };
  1278. }
  1279. function intakeDefines() {
  1280. var args;
  1281. //Any defined modules in the global queue, intake them now.
  1282. takeGlobalQueue();
  1283. //Make sure any remaining defQueue items get properly processed.
  1284. while (defQueue.length) {
  1285. args = defQueue.shift();
  1286. if (args[0] === null) {
  1287. return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
  1288. } else {
  1289. //args are id, deps, factory. Should be normalized by the
  1290. //define() function.
  1291. callGetModule(args);
  1292. }
  1293. }
  1294. }
  1295. context = {
  1296. config: config,
  1297. contextName: contextName,
  1298. registry: registry,
  1299. defined: defined,
  1300. urlFetched: urlFetched,
  1301. defQueue: defQueue,
  1302. Module: Module,
  1303. makeModuleMap: makeModuleMap,
  1304. nextTick: req.nextTick,
  1305. onError: onError,
  1306. /**
  1307. * Set a configuration for the context.
  1308. * @param {Object} cfg config object to integrate.
  1309. */
  1310. configure: function (cfg) {
  1311. //Make sure the baseUrl ends in a slash.
  1312. if (cfg.baseUrl) {
  1313. if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
  1314. cfg.baseUrl += '/';
  1315. }
  1316. }
  1317. //Save off the paths since they require special processing,
  1318. //they are additive.
  1319. var shim = config.shim,
  1320. objs = {
  1321. paths: true,
  1322. bundles: true,
  1323. config: true,
  1324. map: true
  1325. };
  1326. eachProp(cfg, function (value, prop) {
  1327. if (objs[prop]) {
  1328. if (!config[prop]) {
  1329. config[prop] = {};
  1330. }
  1331. mixin(config[prop], value, true, true);
  1332. } else {
  1333. config[prop] = value;
  1334. }
  1335. });
  1336. //Reverse map the bundles
  1337. if (cfg.bundles) {
  1338. eachProp(cfg.bundles, function (value, prop) {
  1339. each(value, function (v) {
  1340. if (v !== prop) {
  1341. bundlesMap[v] = prop;
  1342. }
  1343. });
  1344. });
  1345. }
  1346. //Merge shim
  1347. if (cfg.shim) {
  1348. eachProp(cfg.shim, function (value, id) {
  1349. //Normalize the structure
  1350. if (isArray(value)) {
  1351. value = {
  1352. deps: value
  1353. };
  1354. }
  1355. if ((value.exports || value.init) && !value.exportsFn) {
  1356. value.exportsFn = context.makeShimExports(value);
  1357. }
  1358. shim[id] = value;
  1359. });
  1360. config.shim = shim;
  1361. }
  1362. //Adjust packages if necessary.
  1363. if (cfg.packages) {
  1364. each(cfg.packages, function (pkgObj) {
  1365. var location, name;
  1366. pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
  1367. name = pkgObj.name;
  1368. location = pkgObj.location;
  1369. if (location) {
  1370. config.paths[name] = pkgObj.location;
  1371. }
  1372. //Save pointer to main module ID for pkg name.
  1373. //Remove leading dot in main, so main paths are normalized,
  1374. //and remove any trailing .js, since different package
  1375. //envs have different conventions: some use a module name,
  1376. //some use a file name.
  1377. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
  1378. .replace(currDirRegExp, '')
  1379. .replace(jsSuffixRegExp, '');
  1380. });
  1381. }
  1382. //If there are any "waiting to execute" modules in the registry,
  1383. //update the maps for them, since their info, like URLs to load,
  1384. //may have changed.
  1385. eachProp(registry, function (mod, id) {
  1386. //If module already has init called, since it is too
  1387. //late to modify them, and ignore unnormalized ones
  1388. //since they are transient.
  1389. if (!mod.inited && !mod.map.unnormalized) {
  1390. mod.map = makeModuleMap(id);
  1391. }
  1392. });
  1393. //If a deps array or a config callback is specified, then call
  1394. //require with those args. This is useful when require is defined as a
  1395. //config object before require.js is loaded.
  1396. if (cfg.deps || cfg.callback) {
  1397. context.require(cfg.deps || [], cfg.callback);
  1398. }
  1399. },
  1400. makeShimExports: function (value) {
  1401. function fn() {
  1402. var ret;
  1403. if (value.init) {
  1404. ret = value.init.apply(global, arguments);
  1405. }
  1406. return ret || (value.exports && getGlobal(value.exports));
  1407. }
  1408. return fn;
  1409. },
  1410. makeRequire: function (relMap, options) {
  1411. options = options || {};
  1412. function localRequire(deps, callback, errback) {
  1413. var id, map, requireMod;
  1414. if (options.enableBuildCallback && callback && isFunction(callback)) {
  1415. callback.__requireJsBuild = true;
  1416. }
  1417. if (typeof deps === 'string') {
  1418. if (isFunction(callback)) {
  1419. //Invalid call
  1420. return onError(makeError('requireargs', 'Invalid require call'), errback);
  1421. }
  1422. //If require|exports|module are requested, get the
  1423. //value for them from the special handlers. Caveat:
  1424. //this only works while module is being defined.
  1425. if (relMap && hasProp(handlers, deps)) {
  1426. return handlers[deps](registry[relMap.id]);
  1427. }
  1428. //Synchronous access to one module. If require.get is
  1429. //available (as in the Node adapter), prefer that.
  1430. if (req.get) {
  1431. return req.get(context, deps, relMap, localRequire);
  1432. }
  1433. //Normalize module name, if it contains . or ..
  1434. map = makeModuleMap(deps, relMap, false, true);
  1435. id = map.id;
  1436. if (!hasProp(defined, id)) {
  1437. return onError(makeError('notloaded', 'Module name "' +
  1438. id +
  1439. '" has not been loaded yet for context: ' +
  1440. contextName +
  1441. (relMap ? '' : '. Use require([])')));
  1442. }
  1443. return defined[id];
  1444. }
  1445. //Grab defines waiting in the global queue.
  1446. intakeDefines();
  1447. //Mark all the dependencies as needing to be loaded.
  1448. context.nextTick(function () {
  1449. //Some defines could have been added since the
  1450. //require call, collect them.
  1451. intakeDefines();
  1452. requireMod = getModule(makeModuleMap(null, relMap));
  1453. //Store if map config should be applied to this require
  1454. //call for dependencies.
  1455. requireMod.skipMap = options.skipMap;
  1456. requireMod.init(deps, callback, errback, {
  1457. enabled: true
  1458. });
  1459. checkLoaded();
  1460. });
  1461. return localRequire;
  1462. }
  1463. mixin(localRequire, {
  1464. isBrowser: isBrowser,
  1465. /**
  1466. * Converts a module name + .extension into an URL path.
  1467. * *Requires* the use of a module name. It does not support using
  1468. * plain URLs like nameToUrl.
  1469. */
  1470. toUrl: function (moduleNamePlusExt) {
  1471. var ext,
  1472. index = moduleNamePlusExt.lastIndexOf('.'),
  1473. segment = moduleNamePlusExt.split('/')[0],
  1474. isRelative = segment === '.' || segment === '..';
  1475. //Have a file extension alias, and it is not the
  1476. //dots from a relative path.
  1477. if (index !== -1 && (!isRelative || index > 1)) {
  1478. ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
  1479. moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
  1480. }
  1481. return context.nameToUrl(normalize(moduleNamePlusExt,
  1482. relMap && relMap.id, true), ext, true);
  1483. },
  1484. defined: function (id) {
  1485. return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
  1486. },
  1487. specified: function (id) {
  1488. id = makeModuleMap(id, relMap, false, true).id;
  1489. return hasProp(defined, id) || hasProp(registry, id);
  1490. }
  1491. });
  1492. //Only allow undef on top level require calls
  1493. if (!relMap) {
  1494. localRequire.undef = function (id) {
  1495. //Bind any waiting define() calls to this context,
  1496. //fix for #408
  1497. takeGlobalQueue();
  1498. var map = makeModuleMap(id, relMap, true),
  1499. mod = getOwn(registry, id);
  1500. removeScript(id);
  1501. delete defined[id];
  1502. delete urlFetched[map.url];
  1503. delete undefEvents[id];
  1504. //Clean queued defines too. Go backwards
  1505. //in array so that the splices do not
  1506. //mess up the iteration.
  1507. eachReverse(defQueue, function(args, i) {
  1508. if(args[0] === id) {
  1509. defQueue.splice(i, 1);
  1510. }
  1511. });
  1512. if (mod) {
  1513. //Hold on to listeners in case the
  1514. //module will be attempted to be reloaded
  1515. //using a different config.
  1516. if (mod.events.defined) {
  1517. undefEvents[id] = mod.events;
  1518. }
  1519. cleanRegistry(id);
  1520. }
  1521. };
  1522. }
  1523. return localRequire;
  1524. },
  1525. /**
  1526. * Called to enable a module if it is still in the registry
  1527. * awaiting enablement. A second arg, parent, the parent module,
  1528. * is passed in for context, when this method is overridden by
  1529. * the optimizer. Not shown here to keep code compact.
  1530. */
  1531. enable: function (depMap) {
  1532. var mod = getOwn(registry, depMap.id);
  1533. if (mod) {
  1534. getModule(depMap).enable();
  1535. }
  1536. },
  1537. /**
  1538. * Internal method used by environment adapters to complete a load event.
  1539. * A load event could be a script load or just a load pass from a synchronous
  1540. * load call.
  1541. * @param {String} moduleName the name of the module to potentially complete.
  1542. */
  1543. completeLoad: function (moduleName) {
  1544. var found, args, mod,
  1545. shim = getOwn(config.shim, moduleName) || {},
  1546. shExports = shim.exports;
  1547. takeGlobalQueue();
  1548. while (defQueue.length) {
  1549. args = defQueue.shift();
  1550. if (args[0] === null) {
  1551. args[0] = moduleName;
  1552. //If already found an anonymous module and bound it
  1553. //to this name, then this is some other anon module
  1554. //waiting for its completeLoad to fire.
  1555. if (found) {
  1556. break;
  1557. }
  1558. found = true;
  1559. } else if (args[0] === moduleName) {
  1560. //Found matching define call for this script!
  1561. found = true;
  1562. }
  1563. callGetModule(args);
  1564. }
  1565. //Do this after the cycle of callGetModule in case the result
  1566. //of those calls/init calls changes the registry.
  1567. mod = getOwn(registry, moduleName);
  1568. if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
  1569. if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
  1570. if (hasPathFallback(moduleName)) {
  1571. return;
  1572. } else {
  1573. return onError(makeError('nodefine',
  1574. 'No define call for ' + moduleName,
  1575. null,
  1576. [moduleName]));
  1577. }
  1578. } else {
  1579. //A script that does not call define(), so just simulate
  1580. //the call for it.
  1581. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
  1582. }
  1583. }
  1584. checkLoaded();
  1585. },
  1586. /**
  1587. * Converts a module name to a file path. Supports cases where
  1588. * moduleName may actually be just an URL.
  1589. * Note that it **does not** call normalize on the moduleName,
  1590. * it is assumed to have already been normalized. This is an
  1591. * internal API, not a public one. Use toUrl for the public API.
  1592. */
  1593. nameToUrl: function (moduleName, ext, skipExt) {
  1594. var paths, syms, i, parentModule, url,
  1595. parentPath, bundleId,
  1596. pkgMain = getOwn(config.pkgs, moduleName);
  1597. if (pkgMain) {
  1598. moduleName = pkgMain;
  1599. }
  1600. bundleId = getOwn(bundlesMap, moduleName);
  1601. if (bundleId) {
  1602. return context.nameToUrl(bundleId, ext, skipExt);
  1603. }
  1604. //If a colon is in the URL, it indicates a protocol is used and it is just
  1605. //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
  1606. //or ends with .js, then assume the user meant to use an url and not a module id.
  1607. //The slash is important for protocol-less URLs as well as full paths.
  1608. if (req.jsExtRegExp.test(moduleName)) {
  1609. //Just a plain path, not module name lookup, so just return it.
  1610. //Add extension if it is included. This is a bit wonky, only non-.js things pass
  1611. //an extension, this method probably needs to be reworked.
  1612. url = moduleName + (ext || '');
  1613. } else {
  1614. //A module that needs to be converted to a path.
  1615. paths = config.paths;
  1616. syms = moduleName.split('/');
  1617. //For each module name segment, see if there is a path
  1618. //registered for it. Start with most specific name
  1619. //and work up from it.
  1620. for (i = syms.length; i > 0; i -= 1) {
  1621. parentModule = syms.slice(0, i).join('/');
  1622. parentPath = getOwn(paths, parentModule);
  1623. if (parentPath) {
  1624. //If an array, it means there are a few choices,
  1625. //Choose the one that is desired
  1626. if (isArray(parentPath)) {
  1627. parentPath = parentPath[0];
  1628. }
  1629. syms.splice(0, i, parentPath);
  1630. break;
  1631. }
  1632. }
  1633. //Join the path parts together, then figure out if baseUrl is needed.
  1634. url = syms.join('/');
  1635. url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
  1636. url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
  1637. }
  1638. return config.urlArgs ? url +
  1639. ((url.indexOf('?') === -1 ? '?' : '&') +
  1640. config.urlArgs) : url;
  1641. },
  1642. //Delegates to req.load. Broken out as a separate function to
  1643. //allow overriding in the optimizer.
  1644. load: function (id, url) {
  1645. req.load(context, id, url);
  1646. },
  1647. /**
  1648. * Executes a module callback function. Broken out as a separate function
  1649. * solely to allow the build system to sequence the files in the built
  1650. * layer in the right sequence.
  1651. *
  1652. * @private
  1653. */
  1654. execCb: function (name, callback, args, exports) {
  1655. return callback.apply(exports, args);
  1656. },
  1657. /**
  1658. * callback for script loads, used to check status of loading.
  1659. *
  1660. * @param {Event} evt the event from the browser for the script
  1661. * that was loaded.
  1662. */
  1663. onScriptLoad: function (evt) {
  1664. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1665. //all old browsers will be supported, but this one was easy enough
  1666. //to support and still makes sense.
  1667. if (evt.type === 'load' ||
  1668. (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
  1669. //Reset interactive script so a script node is not held onto for
  1670. //to long.
  1671. interactiveScript = null;
  1672. //Pull out the name of the module and the context.
  1673. var data = getScriptData(evt);
  1674. context.completeLoad(data.id);
  1675. }
  1676. },
  1677. /**
  1678. * Callback for script errors.
  1679. */
  1680. onScriptError: function (evt) {
  1681. var data = getScriptData(evt);
  1682. if (!hasPathFallback(data.id)) {
  1683. return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
  1684. }
  1685. }
  1686. };
  1687. context.require = context.makeRequire();
  1688. return context;
  1689. }
  1690. /**
  1691. * Main entry point.
  1692. *
  1693. * If the only argument to require is a string, then the module that
  1694. * is represented by that string is fetched for the appropriate context.
  1695. *
  1696. * If the first argument is an array, then it will be treated as an array
  1697. * of dependency string names to fetch. An optional function callback can
  1698. * be specified to execute when all of those dependencies are available.
  1699. *
  1700. * Make a local req variable to help Caja compliance (it assumes things
  1701. * on a require that are not standardized), and to give a short
  1702. * name for minification/local scope use.
  1703. */
  1704. req = requirejs = function (deps, callback, errback, optional) {
  1705. //Find the right context, use default
  1706. var context, config,
  1707. contextName = defContextName;
  1708. // Determine if have config object in the call.
  1709. if (!isArray(deps) && typeof deps !== 'string') {
  1710. // deps is a config object
  1711. config = deps;
  1712. if (isArray(callback)) {
  1713. // Adjust args if there are dependencies
  1714. deps = callback;
  1715. callback = errback;
  1716. errback = optional;
  1717. } else {
  1718. deps = [];
  1719. }
  1720. }
  1721. if (config && config.context) {
  1722. contextName = config.context;
  1723. }
  1724. context = getOwn(contexts, contextName);
  1725. if (!context) {
  1726. context = contexts[contextName] = req.s.newContext(contextName);
  1727. }
  1728. if (config) {
  1729. context.configure(config);
  1730. }
  1731. return context.require(deps, callback, errback);
  1732. };
  1733. /**
  1734. * Support require.config() to make it easier to cooperate with other
  1735. * AMD loaders on globally agreed names.
  1736. */
  1737. req.config = function (config) {
  1738. return req(config);
  1739. };
  1740. /**
  1741. * Execute something after the current tick
  1742. * of the event loop. Override for other envs
  1743. * that have a better solution than setTimeout.
  1744. * @param {Function} fn function to execute later.
  1745. */
  1746. req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
  1747. setTimeout(fn, 4);
  1748. } : function (fn) { fn(); };
  1749. /**
  1750. * Export require as a global, but only if it does not already exist.
  1751. */
  1752. if (!require) {
  1753. require = req;
  1754. }
  1755. req.version = version;
  1756. //Used to filter out dependencies that are already paths.
  1757. req.jsExtRegExp = /^\/|:|\?|\.js$/;
  1758. req.isBrowser = isBrowser;
  1759. s = req.s = {
  1760. contexts: contexts,
  1761. newContext: newContext
  1762. };
  1763. //Create default context.
  1764. req({});
  1765. //Exports some context-sensitive methods on global require.
  1766. each([
  1767. 'toUrl',
  1768. 'undef',
  1769. 'defined',
  1770. 'specified'
  1771. ], function (prop) {
  1772. //Reference from contexts instead of early binding to default context,
  1773. //so that during builds, the latest instance of the default context
  1774. //with its config gets used.
  1775. req[prop] = function () {
  1776. var ctx = contexts[defContextName];
  1777. return ctx.require[prop].apply(ctx, arguments);
  1778. };
  1779. });
  1780. if (isBrowser) {
  1781. head = s.head = document.getElementsByTagName('head')[0];
  1782. //If BASE tag is in play, using appendChild is a problem for IE6.
  1783. //When that browser dies, this can be removed. Details in this jQuery bug:
  1784. //http://dev.jquery.com/ticket/2709
  1785. baseElement = document.getElementsByTagName('base')[0];
  1786. if (baseElement) {
  1787. head = s.head = baseElement.parentNode;
  1788. }
  1789. }
  1790. /**
  1791. * Any errors that require explicitly generates will be passed to this
  1792. * function. Intercept/override it if you want custom error handling.
  1793. * @param {Error} err the error object.
  1794. */
  1795. req.onError = defaultOnError;
  1796. /**
  1797. * Creates the node for the load command. Only used in browser envs.
  1798. */
  1799. req.createNode = function (config, moduleName, url) {
  1800. var node = config.xhtml ?
  1801. document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
  1802. document.createElement('script');
  1803. node.type = config.scriptType || 'text/javascript';
  1804. node.charset = 'utf-8';
  1805. node.async = true;
  1806. return node;
  1807. };
  1808. /**
  1809. * Does the request to load a module for the browser case.
  1810. * Make this a separate function to allow other environments
  1811. * to override it.
  1812. *
  1813. * @param {Object} context the require context to find state.
  1814. * @param {String} moduleName the name of the module.
  1815. * @param {Object} url the URL to the module.
  1816. */
  1817. req.load = function (context, moduleName, url) {
  1818. var config = (context && context.config) || {},
  1819. node;
  1820. if (isBrowser) {
  1821. //In the browser so use a script tag
  1822. node = req.createNode(config, moduleName, url);
  1823. node.setAttribute('data-requirecontext', context.contextName);
  1824. node.setAttribute('data-requiremodule', moduleName);
  1825. //Set up load listener. Test attachEvent first because IE9 has
  1826. //a subtle issue in its addEventListener and script onload firings
  1827. //that do not match the behavior of all other browsers with
  1828. //addEventListener support, which fire the onload event for a
  1829. //script right after the script execution. See:
  1830. //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
  1831. //UNFORTUNATELY Opera implements attachEvent but does not follow the script
  1832. //script execution mode.
  1833. if (node.attachEvent &&
  1834. //Check if node.attachEvent is artificially added by custom script or
  1835. //natively supported by browser
  1836. //read https://github.com/jrburke/requirejs/issues/187
  1837. //if we can NOT find [native code] then it must NOT natively supported.
  1838. //in IE8, node.attachEvent does not have toString()
  1839. //Note the test for "[native code" with no closing brace, see:
  1840. //https://github.com/jrburke/requirejs/issues/273
  1841. !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
  1842. !isOpera) {
  1843. //Probably IE. IE (at least 6-8) do not fire
  1844. //script onload right after executing the script, so
  1845. //we cannot tie the anonymous define call to a name.
  1846. //However, IE reports the script as being in 'interactive'
  1847. //readyState at the time of the define call.
  1848. useInteractive = true;
  1849. node.attachEvent('onreadystatechange', context.onScriptLoad);
  1850. //It would be great to add an error handler here to catch
  1851. //404s in IE9+. However, onreadystatechange will fire before
  1852. //the error handler, so that does not help. If addEventListener
  1853. //is used, then IE will fire error before load, but we cannot
  1854. //use that pathway given the connect.microsoft.com issue
  1855. //mentioned above about not doing the 'script execute,
  1856. //then fire the script load event listener before execute
  1857. //next script' that other browsers do.
  1858. //Best hope: IE10 fixes the issues,
  1859. //and then destroys all installs of IE 6-9.
  1860. //node.attachEvent('onerror', context.onScriptError);
  1861. } else {
  1862. node.addEventListener('load', context.onScriptLoad, false);
  1863. node.addEventListener('error', context.onScriptError, false);
  1864. }
  1865. node.src = url;
  1866. //For some cache cases in IE 6-8, the script executes before the end
  1867. //of the appendChild execution, so to tie an anonymous define
  1868. //call to the module name (which is stored on the node), hold on
  1869. //to a reference to this node, but clear after the DOM insertion.
  1870. currentlyAddingScript = node;
  1871. if (baseElement) {
  1872. head.insertBefore(node, baseElement);
  1873. } else {
  1874. head.appendChild(node);
  1875. }
  1876. currentlyAddingScript = null;
  1877. return node;
  1878. } else if (isWebWorker) {
  1879. try {
  1880. //In a web worker, use importScripts. This is not a very
  1881. //efficient use of importScripts, importScripts will block until
  1882. //its script is downloaded and evaluated. However, if web workers
  1883. //are in play, the expectation that a build has been done so that
  1884. //only one script needs to be loaded anyway. This may need to be
  1885. //reevaluated if other use cases become common.
  1886. importScripts(url);
  1887. //Account for anonymous modules
  1888. context.completeLoad(moduleName);
  1889. } catch (e) {
  1890. context.onError(makeError('importscripts',
  1891. 'importScripts failed for ' +
  1892. moduleName + ' at ' + url,
  1893. e,
  1894. [moduleName]));
  1895. }
  1896. }
  1897. };
  1898. function getInteractiveScript() {
  1899. if (interactiveScript && interactiveScript.readyState === 'interactive') {
  1900. return interactiveScript;
  1901. }
  1902. eachReverse(scripts(), function (script) {
  1903. if (script.readyState === 'interactive') {
  1904. return (interactiveScript = script);
  1905. }
  1906. });
  1907. return interactiveScript;
  1908. }
  1909. //Look for a data-main script attribute, which could also adjust the baseUrl.
  1910. if (isBrowser && !cfg.skipDataMain) {
  1911. //Figure out baseUrl. Get it from the script tag with require.js in it.
  1912. eachReverse(scripts(), function (script) {
  1913. //Set the 'head' where we can append children by
  1914. //using the script's parent.
  1915. if (!head) {
  1916. head = script.parentNode;
  1917. }
  1918. //Look for a data-main attribute to set main script for the page
  1919. //to load. If it is there, the path to data main becomes the
  1920. //baseUrl, if it is not already set.
  1921. dataMain = script.getAttribute('data-main');
  1922. if (dataMain) {
  1923. //Preserve dataMain in case it is a path (i.e. contains '?')
  1924. mainScript = dataMain;
  1925. //Set final baseUrl if there is not already an explicit one.
  1926. if (!cfg.baseUrl) {
  1927. //Pull off the directory of data-main for use as the
  1928. //baseUrl.
  1929. src = mainScript.split('/');
  1930. mainScript = src.pop();
  1931. subPath = src.length ? src.join('/') + '/' : './';
  1932. cfg.baseUrl = subPath;
  1933. }
  1934. //Strip off any trailing .js since mainScript is now
  1935. //like a module name.
  1936. mainScript = mainScript.replace(jsSuffixRegExp, '');
  1937. //If mainScript is still a path, fall back to dataMain
  1938. if (req.jsExtRegExp.test(mainScript)) {
  1939. mainScript = dataMain;
  1940. }
  1941. //Put the data-main script in the files to load.
  1942. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
  1943. return true;
  1944. }
  1945. });
  1946. }
  1947. /**
  1948. * The function that handles definitions of modules. Differs from
  1949. * require() in that a string for the module should be the first argument,
  1950. * and the function to execute after dependencies are loaded should
  1951. * return a value to define the module corresponding to the first argument's
  1952. * name.
  1953. */
  1954. define = function (name, deps, callback) {
  1955. var node, context;
  1956. //Allow for anonymous modules
  1957. if (typeof name !== 'string') {
  1958. //Adjust args appropriately
  1959. callback = deps;
  1960. deps = name;
  1961. name = null;
  1962. }
  1963. //This module may not have dependencies
  1964. if (!isArray(deps)) {
  1965. callback = deps;
  1966. deps = null;
  1967. }
  1968. //If no name, and callback is a function, then figure out if it a
  1969. //CommonJS thing with dependencies.
  1970. if (!deps && isFunction(callback)) {
  1971. deps = [];
  1972. //Remove comments from the callback string,
  1973. //look for require calls, and pull them into the dependencies,
  1974. //but only if there are function args.
  1975. if (callback.length) {
  1976. callback
  1977. .toString()
  1978. .replace(commentRegExp, '')
  1979. .replace(cjsRequireRegExp, function (match, dep) {
  1980. deps.push(dep);
  1981. });
  1982. //May be a CommonJS thing even without require calls, but still
  1983. //could use exports, and module. Avoid doing exports and module
  1984. //work though if it just needs require.
  1985. //REQUIRES the function to expect the CommonJS variables in the
  1986. //order listed below.
  1987. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
  1988. }
  1989. }
  1990. //If in IE 6-8 and hit an anonymous define() call, do the interactive
  1991. //work.
  1992. if (useInteractive) {
  1993. node = currentlyAddingScript || getInteractiveScript();
  1994. if (node) {
  1995. if (!name) {
  1996. name = node.getAttribute('data-requiremodule');
  1997. }
  1998. context = contexts[node.getAttribute('data-requirecontext')];
  1999. }
  2000. }
  2001. //Always save off evaluating the def call until the script onload handler.
  2002. //This allows multiple modules to be in a file without prematurely
  2003. //tracing dependencies, and allows for anonymous module support,
  2004. //where the module name is not known until the script onload event
  2005. //occurs. If no context, use the global queue, and get it processed
  2006. //in the onscript load callback.
  2007. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
  2008. };
  2009. define.amd = {
  2010. jQuery: true
  2011. };
  2012. /**
  2013. * Executes the text. Normally just uses eval, but can be modified
  2014. * to use a better, environment-specific call. Only used for transpiling
  2015. * loader plugins, not for plain JS modules.
  2016. * @param {String} text the text to execute/evaluate.
  2017. */
  2018. req.exec = function (text) {
  2019. /*jslint evil: true */
  2020. return eval(text);
  2021. };
  2022. //Set up with config info.
  2023. req(cfg);
  2024. }(this));
  2025. this.requirejsVars = {
  2026. require: require,
  2027. requirejs: require,
  2028. define: define
  2029. };
  2030. if (env === 'browser') {
  2031. /**
  2032. * @license RequireJS rhino Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2033. * Available via the MIT or new BSD license.
  2034. * see: http://github.com/jrburke/requirejs for details
  2035. */
  2036. //sloppy since eval enclosed with use strict causes problems if the source
  2037. //text is not strict-compliant.
  2038. /*jslint sloppy: true, evil: true */
  2039. /*global require, XMLHttpRequest */
  2040. (function () {
  2041. // Separate function to avoid eval pollution, same with arguments use.
  2042. function exec() {
  2043. eval(arguments[0]);
  2044. }
  2045. require.load = function (context, moduleName, url) {
  2046. var xhr = new XMLHttpRequest();
  2047. xhr.open('GET', url, true);
  2048. xhr.send();
  2049. xhr.onreadystatechange = function () {
  2050. if (xhr.readyState === 4) {
  2051. exec(xhr.responseText);
  2052. //Support anonymous modules.
  2053. context.completeLoad(moduleName);
  2054. }
  2055. };
  2056. };
  2057. }());
  2058. } else if (env === 'rhino') {
  2059. /**
  2060. * @license RequireJS rhino Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2061. * Available via the MIT or new BSD license.
  2062. * see: http://github.com/jrburke/requirejs for details
  2063. */
  2064. /*jslint */
  2065. /*global require: false, java: false, load: false */
  2066. (function () {
  2067. 'use strict';
  2068. require.load = function (context, moduleName, url) {
  2069. load(url);
  2070. //Support anonymous modules.
  2071. context.completeLoad(moduleName);
  2072. };
  2073. }());
  2074. } else if (env === 'node') {
  2075. this.requirejsVars.nodeRequire = nodeRequire;
  2076. require.nodeRequire = nodeRequire;
  2077. /**
  2078. * @license RequireJS node Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2079. * Available via the MIT or new BSD license.
  2080. * see: http://github.com/jrburke/requirejs for details
  2081. */
  2082. //Explicity not strict since this file contains an eval call, and do not want
  2083. //to enforce strict on code evaluated that way. See
  2084. //https://github.com/jrburke/r.js/issues/774
  2085. /*jslint regexp: false, sloppy: true*/
  2086. /*global require: false, define: false, requirejsVars: false, process: false */
  2087. /**
  2088. * This adapter assumes that x.js has loaded it and set up
  2089. * some variables. This adapter just allows limited RequireJS
  2090. * usage from within the requirejs directory. The general
  2091. * node adapater is r.js.
  2092. */
  2093. (function () {
  2094. var nodeReq = requirejsVars.nodeRequire,
  2095. req = requirejsVars.require,
  2096. def = requirejsVars.define,
  2097. fs = nodeReq('fs'),
  2098. path = nodeReq('path'),
  2099. vm = nodeReq('vm'),
  2100. //In Node 0.7+ existsSync is on fs.
  2101. exists = fs.existsSync || path.existsSync,
  2102. hasOwn = Object.prototype.hasOwnProperty;
  2103. function hasProp(obj, prop) {
  2104. return hasOwn.call(obj, prop);
  2105. }
  2106. function syncTick(fn) {
  2107. fn();
  2108. }
  2109. function makeError(message, moduleName) {
  2110. var err = new Error(message);
  2111. err.requireModules = [moduleName];
  2112. return err;
  2113. }
  2114. //Supply an implementation that allows synchronous get of a module.
  2115. req.get = function (context, moduleName, relModuleMap, localRequire) {
  2116. if (moduleName === "require" || moduleName === "exports" || moduleName === "module") {
  2117. context.onError(makeError("Explicit require of " + moduleName + " is not allowed.", moduleName));
  2118. }
  2119. var ret, oldTick,
  2120. moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true);
  2121. //Normalize module name, if it contains . or ..
  2122. moduleName = moduleMap.id;
  2123. if (hasProp(context.defined, moduleName)) {
  2124. ret = context.defined[moduleName];
  2125. } else {
  2126. if (ret === undefined) {
  2127. //Make sure nextTick for this type of call is sync-based.
  2128. oldTick = context.nextTick;
  2129. context.nextTick = syncTick;
  2130. try {
  2131. if (moduleMap.prefix) {
  2132. //A plugin, call requirejs to handle it. Now that
  2133. //nextTick is syncTick, the require will complete
  2134. //synchronously.
  2135. localRequire([moduleMap.originalName]);
  2136. //Now that plugin is loaded, can regenerate the moduleMap
  2137. //to get the final, normalized ID.
  2138. moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true);
  2139. moduleName = moduleMap.id;
  2140. } else {
  2141. //Try to dynamically fetch it.
  2142. req.load(context, moduleName, moduleMap.url);
  2143. //Enable the module
  2144. context.enable(moduleMap, relModuleMap);
  2145. }
  2146. //Break any cycles by requiring it normally, but this will
  2147. //finish synchronously
  2148. context.require([moduleName]);
  2149. //The above calls are sync, so can do the next thing safely.
  2150. ret = context.defined[moduleName];
  2151. } finally {
  2152. context.nextTick = oldTick;
  2153. }
  2154. }
  2155. }
  2156. return ret;
  2157. };
  2158. req.nextTick = function (fn) {
  2159. process.nextTick(fn);
  2160. };
  2161. //Add wrapper around the code so that it gets the requirejs
  2162. //API instead of the Node API, and it is done lexically so
  2163. //that it survives later execution.
  2164. req.makeNodeWrapper = function (contents) {
  2165. return '(function (require, requirejs, define) { ' +
  2166. contents +
  2167. '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));';
  2168. };
  2169. req.load = function (context, moduleName, url) {
  2170. var contents, err,
  2171. config = context.config;
  2172. if (config.shim[moduleName] && (!config.suppress || !config.suppress.nodeShim)) {
  2173. console.warn('Shim config not supported in Node, may or may not work. Detected ' +
  2174. 'for module: ' + moduleName);
  2175. }
  2176. if (exists(url)) {
  2177. contents = fs.readFileSync(url, 'utf8');
  2178. contents = req.makeNodeWrapper(contents);
  2179. try {
  2180. vm.runInThisContext(contents, fs.realpathSync(url));
  2181. } catch (e) {
  2182. err = new Error('Evaluating ' + url + ' as module "' +
  2183. moduleName + '" failed with error: ' + e);
  2184. err.originalError = e;
  2185. err.moduleName = moduleName;
  2186. err.requireModules = [moduleName];
  2187. err.fileName = url;
  2188. return context.onError(err);
  2189. }
  2190. } else {
  2191. def(moduleName, function () {
  2192. //Get the original name, since relative requires may be
  2193. //resolved differently in node (issue #202). Also, if relative,
  2194. //make it relative to the URL of the item requesting it
  2195. //(issue #393)
  2196. var dirName,
  2197. map = hasProp(context.registry, moduleName) &&
  2198. context.registry[moduleName].map,
  2199. parentMap = map && map.parentMap,
  2200. originalName = map && map.originalName;
  2201. if (originalName.charAt(0) === '.' && parentMap) {
  2202. dirName = parentMap.url.split('/');
  2203. dirName.pop();
  2204. originalName = dirName.join('/') + '/' + originalName;
  2205. }
  2206. try {
  2207. return (context.config.nodeRequire || req.nodeRequire)(originalName);
  2208. } catch (e) {
  2209. err = new Error('Tried loading "' + moduleName + '" at ' +
  2210. url + ' then tried node\'s require("' +
  2211. originalName + '") and it failed ' +
  2212. 'with error: ' + e);
  2213. err.originalError = e;
  2214. err.moduleName = originalName;
  2215. err.requireModules = [moduleName];
  2216. throw err;
  2217. }
  2218. });
  2219. }
  2220. //Support anonymous modules.
  2221. context.completeLoad(moduleName);
  2222. };
  2223. //Override to provide the function wrapper for define/require.
  2224. req.exec = function (text) {
  2225. /*jslint evil: true */
  2226. text = req.makeNodeWrapper(text);
  2227. return eval(text);
  2228. };
  2229. }());
  2230. } else if (env === 'xpconnect') {
  2231. /**
  2232. * @license RequireJS xpconnect Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2233. * Available via the MIT or new BSD license.
  2234. * see: http://github.com/jrburke/requirejs for details
  2235. */
  2236. /*jslint */
  2237. /*global require, load */
  2238. (function () {
  2239. 'use strict';
  2240. require.load = function (context, moduleName, url) {
  2241. load(url);
  2242. //Support anonymous modules.
  2243. context.completeLoad(moduleName);
  2244. };
  2245. }());
  2246. }
  2247. //Support a default file name to execute. Useful for hosted envs
  2248. //like Joyent where it defaults to a server.js as the only executed
  2249. //script. But only do it if this is not an optimization run.
  2250. if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) {
  2251. fileName = 'main.js';
  2252. }
  2253. /**
  2254. * Loads the library files that can be used for the optimizer, or for other
  2255. * tasks.
  2256. */
  2257. function loadLib() {
  2258. /**
  2259. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2260. * Available via the MIT or new BSD license.
  2261. * see: http://github.com/jrburke/requirejs for details
  2262. */
  2263. /*jslint strict: false */
  2264. /*global Packages: false, process: false, window: false, navigator: false,
  2265. document: false, define: false */
  2266. /**
  2267. * A plugin that modifies any /env/ path to be the right path based on
  2268. * the host environment. Right now only works for Node, Rhino and browser.
  2269. */
  2270. (function () {
  2271. var pathRegExp = /(\/|^)env\/|\{env\}/,
  2272. env = 'unknown';
  2273. if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  2274. env = 'node';
  2275. } else if (typeof Packages !== 'undefined') {
  2276. env = 'rhino';
  2277. } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  2278. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  2279. env = 'browser';
  2280. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  2281. env = 'xpconnect';
  2282. }
  2283. define('env', {
  2284. get: function () {
  2285. return env;
  2286. },
  2287. load: function (name, req, load, config) {
  2288. //Allow override in the config.
  2289. if (config.env) {
  2290. env = config.env;
  2291. }
  2292. name = name.replace(pathRegExp, function (match, prefix) {
  2293. if (match.indexOf('{') === -1) {
  2294. return prefix + env + '/';
  2295. } else {
  2296. return env;
  2297. }
  2298. });
  2299. req([name], function (mod) {
  2300. load(mod);
  2301. });
  2302. }
  2303. });
  2304. }());
  2305. /**
  2306. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2307. * Available via the MIT or new BSD license.
  2308. * see: http://github.com/jrburke/requirejs for details
  2309. */
  2310. /*jslint plusplus: true */
  2311. /*global define, java */
  2312. define('lang', function () {
  2313. 'use strict';
  2314. var lang, isJavaObj,
  2315. hasOwn = Object.prototype.hasOwnProperty;
  2316. function hasProp(obj, prop) {
  2317. return hasOwn.call(obj, prop);
  2318. }
  2319. isJavaObj = function () {
  2320. return false;
  2321. };
  2322. //Rhino, but not Nashorn (detected by importPackage not existing)
  2323. //Can have some strange foreign objects.
  2324. if (typeof java !== 'undefined' && java.lang && java.lang.Object && typeof importPackage !== 'undefined') {
  2325. isJavaObj = function (obj) {
  2326. return obj instanceof java.lang.Object;
  2327. };
  2328. }
  2329. lang = {
  2330. backSlashRegExp: /\\/g,
  2331. ostring: Object.prototype.toString,
  2332. isArray: Array.isArray || function (it) {
  2333. return lang.ostring.call(it) === "[object Array]";
  2334. },
  2335. isFunction: function(it) {
  2336. return lang.ostring.call(it) === "[object Function]";
  2337. },
  2338. isRegExp: function(it) {
  2339. return it && it instanceof RegExp;
  2340. },
  2341. hasProp: hasProp,
  2342. //returns true if the object does not have an own property prop,
  2343. //or if it does, it is a falsy value.
  2344. falseProp: function (obj, prop) {
  2345. return !hasProp(obj, prop) || !obj[prop];
  2346. },
  2347. //gets own property value for given prop on object
  2348. getOwn: function (obj, prop) {
  2349. return hasProp(obj, prop) && obj[prop];
  2350. },
  2351. _mixin: function(dest, source, override){
  2352. var name;
  2353. for (name in source) {
  2354. if(source.hasOwnProperty(name) &&
  2355. (override || !dest.hasOwnProperty(name))) {
  2356. dest[name] = source[name];
  2357. }
  2358. }
  2359. return dest; // Object
  2360. },
  2361. /**
  2362. * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,
  2363. * then the source objects properties are force copied over to dest.
  2364. */
  2365. mixin: function(dest){
  2366. var parameters = Array.prototype.slice.call(arguments),
  2367. override, i, l;
  2368. if (!dest) { dest = {}; }
  2369. if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {
  2370. override = parameters.pop();
  2371. }
  2372. for (i = 1, l = parameters.length; i < l; i++) {
  2373. lang._mixin(dest, parameters[i], override);
  2374. }
  2375. return dest; // Object
  2376. },
  2377. /**
  2378. * Does a deep mix of source into dest, where source values override
  2379. * dest values if a winner is needed.
  2380. * @param {Object} dest destination object that receives the mixed
  2381. * values.
  2382. * @param {Object} source source object contributing properties to mix
  2383. * in.
  2384. * @return {[Object]} returns dest object with the modification.
  2385. */
  2386. deepMix: function(dest, source) {
  2387. lang.eachProp(source, function (value, prop) {
  2388. if (typeof value === 'object' && value &&
  2389. !lang.isArray(value) && !lang.isFunction(value) &&
  2390. !(value instanceof RegExp)) {
  2391. if (!dest[prop]) {
  2392. dest[prop] = {};
  2393. }
  2394. lang.deepMix(dest[prop], value);
  2395. } else {
  2396. dest[prop] = value;
  2397. }
  2398. });
  2399. return dest;
  2400. },
  2401. /**
  2402. * Does a type of deep copy. Do not give it anything fancy, best
  2403. * for basic object copies of objects that also work well as
  2404. * JSON-serialized things, or has properties pointing to functions.
  2405. * For non-array/object values, just returns the same object.
  2406. * @param {Object} obj copy properties from this object
  2407. * @param {Object} [result] optional result object to use
  2408. * @return {Object}
  2409. */
  2410. deeplikeCopy: function (obj) {
  2411. var type, result;
  2412. if (lang.isArray(obj)) {
  2413. result = [];
  2414. obj.forEach(function(value) {
  2415. result.push(lang.deeplikeCopy(value));
  2416. });
  2417. return result;
  2418. }
  2419. type = typeof obj;
  2420. if (obj === null || obj === undefined || type === 'boolean' ||
  2421. type === 'string' || type === 'number' || lang.isFunction(obj) ||
  2422. lang.isRegExp(obj)|| isJavaObj(obj)) {
  2423. return obj;
  2424. }
  2425. //Anything else is an object, hopefully.
  2426. result = {};
  2427. lang.eachProp(obj, function(value, key) {
  2428. result[key] = lang.deeplikeCopy(value);
  2429. });
  2430. return result;
  2431. },
  2432. delegate: (function () {
  2433. // boodman/crockford delegation w/ cornford optimization
  2434. function TMP() {}
  2435. return function (obj, props) {
  2436. TMP.prototype = obj;
  2437. var tmp = new TMP();
  2438. TMP.prototype = null;
  2439. if (props) {
  2440. lang.mixin(tmp, props);
  2441. }
  2442. return tmp; // Object
  2443. };
  2444. }()),
  2445. /**
  2446. * Helper function for iterating over an array. If the func returns
  2447. * a true value, it will break out of the loop.
  2448. */
  2449. each: function each(ary, func) {
  2450. if (ary) {
  2451. var i;
  2452. for (i = 0; i < ary.length; i += 1) {
  2453. if (func(ary[i], i, ary)) {
  2454. break;
  2455. }
  2456. }
  2457. }
  2458. },
  2459. /**
  2460. * Cycles over properties in an object and calls a function for each
  2461. * property value. If the function returns a truthy value, then the
  2462. * iteration is stopped.
  2463. */
  2464. eachProp: function eachProp(obj, func) {
  2465. var prop;
  2466. for (prop in obj) {
  2467. if (hasProp(obj, prop)) {
  2468. if (func(obj[prop], prop)) {
  2469. break;
  2470. }
  2471. }
  2472. }
  2473. },
  2474. //Similar to Function.prototype.bind, but the "this" object is specified
  2475. //first, since it is easier to read/figure out what "this" will be.
  2476. bind: function bind(obj, fn) {
  2477. return function () {
  2478. return fn.apply(obj, arguments);
  2479. };
  2480. },
  2481. //Escapes a content string to be be a string that has characters escaped
  2482. //for inclusion as part of a JS string.
  2483. jsEscape: function (content) {
  2484. return content.replace(/(["'\\])/g, '\\$1')
  2485. .replace(/[\f]/g, "\\f")
  2486. .replace(/[\b]/g, "\\b")
  2487. .replace(/[\n]/g, "\\n")
  2488. .replace(/[\t]/g, "\\t")
  2489. .replace(/[\r]/g, "\\r");
  2490. }
  2491. };
  2492. return lang;
  2493. });
  2494. /**
  2495. * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2496. * Available via the MIT or new BSD license.
  2497. * see: http://github.com/requirejs/prim for details
  2498. */
  2499. /*global setImmediate, process, setTimeout, define, module */
  2500. //Set prime.hideResolutionConflict = true to allow "resolution-races"
  2501. //in promise-tests to pass.
  2502. //Since the goal of prim is to be a small impl for trusted code, it is
  2503. //more important to normally throw in this case so that we can find
  2504. //logic errors quicker.
  2505. var prim;
  2506. (function () {
  2507. 'use strict';
  2508. var op = Object.prototype,
  2509. hasOwn = op.hasOwnProperty;
  2510. function hasProp(obj, prop) {
  2511. return hasOwn.call(obj, prop);
  2512. }
  2513. /**
  2514. * Helper function for iterating over an array. If the func returns
  2515. * a true value, it will break out of the loop.
  2516. */
  2517. function each(ary, func) {
  2518. if (ary) {
  2519. var i;
  2520. for (i = 0; i < ary.length; i += 1) {
  2521. if (ary[i]) {
  2522. func(ary[i], i, ary);
  2523. }
  2524. }
  2525. }
  2526. }
  2527. function check(p) {
  2528. if (hasProp(p, 'e') || hasProp(p, 'v')) {
  2529. if (!prim.hideResolutionConflict) {
  2530. throw new Error('nope');
  2531. }
  2532. return false;
  2533. }
  2534. return true;
  2535. }
  2536. function notify(ary, value) {
  2537. prim.nextTick(function () {
  2538. each(ary, function (item) {
  2539. item(value);
  2540. });
  2541. });
  2542. }
  2543. prim = function prim() {
  2544. var p,
  2545. ok = [],
  2546. fail = [];
  2547. return (p = {
  2548. callback: function (yes, no) {
  2549. if (no) {
  2550. p.errback(no);
  2551. }
  2552. if (hasProp(p, 'v')) {
  2553. prim.nextTick(function () {
  2554. yes(p.v);
  2555. });
  2556. } else {
  2557. ok.push(yes);
  2558. }
  2559. },
  2560. errback: function (no) {
  2561. if (hasProp(p, 'e')) {
  2562. prim.nextTick(function () {
  2563. no(p.e);
  2564. });
  2565. } else {
  2566. fail.push(no);
  2567. }
  2568. },
  2569. finished: function () {
  2570. return hasProp(p, 'e') || hasProp(p, 'v');
  2571. },
  2572. rejected: function () {
  2573. return hasProp(p, 'e');
  2574. },
  2575. resolve: function (v) {
  2576. if (check(p)) {
  2577. p.v = v;
  2578. notify(ok, v);
  2579. }
  2580. return p;
  2581. },
  2582. reject: function (e) {
  2583. if (check(p)) {
  2584. p.e = e;
  2585. notify(fail, e);
  2586. }
  2587. return p;
  2588. },
  2589. start: function (fn) {
  2590. p.resolve();
  2591. return p.promise.then(fn);
  2592. },
  2593. promise: {
  2594. then: function (yes, no) {
  2595. var next = prim();
  2596. p.callback(function (v) {
  2597. try {
  2598. if (yes && typeof yes === 'function') {
  2599. v = yes(v);
  2600. }
  2601. if (v && v.then) {
  2602. v.then(next.resolve, next.reject);
  2603. } else {
  2604. next.resolve(v);
  2605. }
  2606. } catch (e) {
  2607. next.reject(e);
  2608. }
  2609. }, function (e) {
  2610. var err;
  2611. try {
  2612. if (!no || typeof no !== 'function') {
  2613. next.reject(e);
  2614. } else {
  2615. err = no(e);
  2616. if (err && err.then) {
  2617. err.then(next.resolve, next.reject);
  2618. } else {
  2619. next.resolve(err);
  2620. }
  2621. }
  2622. } catch (e2) {
  2623. next.reject(e2);
  2624. }
  2625. });
  2626. return next.promise;
  2627. },
  2628. fail: function (no) {
  2629. return p.promise.then(null, no);
  2630. },
  2631. end: function () {
  2632. p.errback(function (e) {
  2633. throw e;
  2634. });
  2635. }
  2636. }
  2637. });
  2638. };
  2639. prim.serial = function (ary) {
  2640. var result = prim().resolve().promise;
  2641. each(ary, function (item) {
  2642. result = result.then(function () {
  2643. return item();
  2644. });
  2645. });
  2646. return result;
  2647. };
  2648. prim.nextTick = typeof setImmediate === 'function' ? setImmediate :
  2649. (typeof process !== 'undefined' && process.nextTick ?
  2650. process.nextTick : (typeof setTimeout !== 'undefined' ?
  2651. function (fn) {
  2652. setTimeout(fn, 0);
  2653. } : function (fn) {
  2654. fn();
  2655. }));
  2656. if (typeof define === 'function' && define.amd) {
  2657. define('prim', function () { return prim; });
  2658. } else if (typeof module !== 'undefined' && module.exports) {
  2659. module.exports = prim;
  2660. }
  2661. }());
  2662. if(env === 'browser') {
  2663. /**
  2664. * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2665. * Available via the MIT or new BSD license.
  2666. * see: http://github.com/jrburke/requirejs for details
  2667. */
  2668. /*jslint strict: false */
  2669. /*global define: false, load: false */
  2670. //Just a stub for use with uglify's consolidator.js
  2671. define('browser/assert', function () {
  2672. return {};
  2673. });
  2674. }
  2675. if(env === 'node') {
  2676. /**
  2677. * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2678. * Available via the MIT or new BSD license.
  2679. * see: http://github.com/jrburke/requirejs for details
  2680. */
  2681. /*jslint strict: false */
  2682. /*global define: false, load: false */
  2683. //Needed so that rhino/assert can return a stub for uglify's consolidator.js
  2684. define('node/assert', ['assert'], function (assert) {
  2685. return assert;
  2686. });
  2687. }
  2688. if(env === 'rhino') {
  2689. /**
  2690. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2691. * Available via the MIT or new BSD license.
  2692. * see: http://github.com/jrburke/requirejs for details
  2693. */
  2694. /*jslint strict: false */
  2695. /*global define: false, load: false */
  2696. //Just a stub for use with uglify's consolidator.js
  2697. define('rhino/assert', function () {
  2698. return {};
  2699. });
  2700. }
  2701. if(env === 'xpconnect') {
  2702. /**
  2703. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2704. * Available via the MIT or new BSD license.
  2705. * see: http://github.com/jrburke/requirejs for details
  2706. */
  2707. /*jslint strict: false */
  2708. /*global define: false, load: false */
  2709. //Just a stub for use with uglify's consolidator.js
  2710. define('xpconnect/assert', function () {
  2711. return {};
  2712. });
  2713. }
  2714. if(env === 'browser') {
  2715. /**
  2716. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2717. * Available via the MIT or new BSD license.
  2718. * see: http://github.com/jrburke/requirejs for details
  2719. */
  2720. /*jslint strict: false */
  2721. /*global define: false, process: false */
  2722. define('browser/args', function () {
  2723. //Always expect config via an API call
  2724. return [];
  2725. });
  2726. }
  2727. if(env === 'node') {
  2728. /**
  2729. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2730. * Available via the MIT or new BSD license.
  2731. * see: http://github.com/jrburke/requirejs for details
  2732. */
  2733. /*jslint strict: false */
  2734. /*global define: false, process: false */
  2735. define('node/args', function () {
  2736. //Do not return the "node" or "r.js" arguments
  2737. var args = process.argv.slice(2);
  2738. //Ignore any command option used for main x.js branching
  2739. if (args[0] && args[0].indexOf('-') === 0) {
  2740. args = args.slice(1);
  2741. }
  2742. return args;
  2743. });
  2744. }
  2745. if(env === 'rhino') {
  2746. /**
  2747. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2748. * Available via the MIT or new BSD license.
  2749. * see: http://github.com/jrburke/requirejs for details
  2750. */
  2751. /*jslint strict: false */
  2752. /*global define: false, process: false */
  2753. var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2754. define('rhino/args', function () {
  2755. var args = jsLibRhinoArgs;
  2756. //Ignore any command option used for main x.js branching
  2757. if (args[0] && args[0].indexOf('-') === 0) {
  2758. args = args.slice(1);
  2759. }
  2760. return args;
  2761. });
  2762. }
  2763. if(env === 'xpconnect') {
  2764. /**
  2765. * @license Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2766. * Available via the MIT or new BSD license.
  2767. * see: http://github.com/jrburke/requirejs for details
  2768. */
  2769. /*jslint strict: false */
  2770. /*global define, xpconnectArgs */
  2771. var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2772. define('xpconnect/args', function () {
  2773. var args = jsLibXpConnectArgs;
  2774. //Ignore any command option used for main x.js branching
  2775. if (args[0] && args[0].indexOf('-') === 0) {
  2776. args = args.slice(1);
  2777. }
  2778. return args;
  2779. });
  2780. }
  2781. if(env === 'browser') {
  2782. /**
  2783. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2784. * Available via the MIT or new BSD license.
  2785. * see: http://github.com/jrburke/requirejs for details
  2786. */
  2787. /*jslint strict: false */
  2788. /*global define: false, console: false */
  2789. define('browser/load', ['./file'], function (file) {
  2790. function load(fileName) {
  2791. eval(file.readFile(fileName));
  2792. }
  2793. return load;
  2794. });
  2795. }
  2796. if(env === 'node') {
  2797. /**
  2798. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2799. * Available via the MIT or new BSD license.
  2800. * see: http://github.com/jrburke/requirejs for details
  2801. */
  2802. /*jslint strict: false */
  2803. /*global define: false, console: false */
  2804. define('node/load', ['fs'], function (fs) {
  2805. function load(fileName) {
  2806. var contents = fs.readFileSync(fileName, 'utf8');
  2807. process.compile(contents, fileName);
  2808. }
  2809. return load;
  2810. });
  2811. }
  2812. if(env === 'rhino') {
  2813. /**
  2814. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2815. * Available via the MIT or new BSD license.
  2816. * see: http://github.com/jrburke/requirejs for details
  2817. */
  2818. /*jslint strict: false */
  2819. /*global define: false, load: false */
  2820. define('rhino/load', function () {
  2821. return load;
  2822. });
  2823. }
  2824. if(env === 'xpconnect') {
  2825. /**
  2826. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  2827. * Available via the MIT or new BSD license.
  2828. * see: http://github.com/jrburke/requirejs for details
  2829. */
  2830. /*jslint strict: false */
  2831. /*global define: false, load: false */
  2832. define('xpconnect/load', function () {
  2833. return load;
  2834. });
  2835. }
  2836. if(env === 'browser') {
  2837. /**
  2838. * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2839. * Available via the MIT or new BSD license.
  2840. * see: http://github.com/jrburke/requirejs for details
  2841. */
  2842. /*jslint sloppy: true, nomen: true */
  2843. /*global require, define, console, XMLHttpRequest, requirejs, location */
  2844. define('browser/file', ['prim'], function (prim) {
  2845. var file,
  2846. currDirRegExp = /^\.(\/|$)/;
  2847. function frontSlash(path) {
  2848. return path.replace(/\\/g, '/');
  2849. }
  2850. function exists(path) {
  2851. var status, xhr = new XMLHttpRequest();
  2852. //Oh yeah, that is right SYNC IO. Behold its glory
  2853. //and horrible blocking behavior.
  2854. xhr.open('HEAD', path, false);
  2855. xhr.send();
  2856. status = xhr.status;
  2857. return status === 200 || status === 304;
  2858. }
  2859. function mkDir(dir) {
  2860. console.log('mkDir is no-op in browser');
  2861. }
  2862. function mkFullDir(dir) {
  2863. console.log('mkFullDir is no-op in browser');
  2864. }
  2865. file = {
  2866. backSlashRegExp: /\\/g,
  2867. exclusionRegExp: /^\./,
  2868. getLineSeparator: function () {
  2869. return '/';
  2870. },
  2871. exists: function (fileName) {
  2872. return exists(fileName);
  2873. },
  2874. parent: function (fileName) {
  2875. var parts = fileName.split('/');
  2876. parts.pop();
  2877. return parts.join('/');
  2878. },
  2879. /**
  2880. * Gets the absolute file path as a string, normalized
  2881. * to using front slashes for path separators.
  2882. * @param {String} fileName
  2883. */
  2884. absPath: function (fileName) {
  2885. var dir;
  2886. if (currDirRegExp.test(fileName)) {
  2887. dir = frontSlash(location.href);
  2888. if (dir.indexOf('/') !== -1) {
  2889. dir = dir.split('/');
  2890. //Pull off protocol and host, just want
  2891. //to allow paths (other build parts, like
  2892. //require._isSupportedBuildUrl do not support
  2893. //full URLs), but a full path from
  2894. //the root.
  2895. dir.splice(0, 3);
  2896. dir.pop();
  2897. dir = '/' + dir.join('/');
  2898. }
  2899. fileName = dir + fileName.substring(1);
  2900. }
  2901. return fileName;
  2902. },
  2903. normalize: function (fileName) {
  2904. return fileName;
  2905. },
  2906. isFile: function (path) {
  2907. return true;
  2908. },
  2909. isDirectory: function (path) {
  2910. return false;
  2911. },
  2912. getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) {
  2913. console.log('file.getFilteredFileList is no-op in browser');
  2914. },
  2915. copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) {
  2916. console.log('file.copyDir is no-op in browser');
  2917. },
  2918. copyFile: function (srcFileName, destFileName, onlyCopyNew) {
  2919. console.log('file.copyFile is no-op in browser');
  2920. },
  2921. /**
  2922. * Renames a file. May fail if "to" already exists or is on another drive.
  2923. */
  2924. renameFile: function (from, to) {
  2925. console.log('file.renameFile is no-op in browser');
  2926. },
  2927. /**
  2928. * Reads a *text* file.
  2929. */
  2930. readFile: function (path, encoding) {
  2931. var xhr = new XMLHttpRequest();
  2932. //Oh yeah, that is right SYNC IO. Behold its glory
  2933. //and horrible blocking behavior.
  2934. xhr.open('GET', path, false);
  2935. xhr.send();
  2936. return xhr.responseText;
  2937. },
  2938. readFileAsync: function (path, encoding) {
  2939. var xhr = new XMLHttpRequest(),
  2940. d = prim();
  2941. xhr.open('GET', path, true);
  2942. xhr.send();
  2943. xhr.onreadystatechange = function () {
  2944. if (xhr.readyState === 4) {
  2945. if (xhr.status > 400) {
  2946. d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText));
  2947. } else {
  2948. d.resolve(xhr.responseText);
  2949. }
  2950. }
  2951. };
  2952. return d.promise;
  2953. },
  2954. saveUtf8File: function (fileName, fileContents) {
  2955. //summary: saves a *text* file using UTF-8 encoding.
  2956. file.saveFile(fileName, fileContents, "utf8");
  2957. },
  2958. saveFile: function (fileName, fileContents, encoding) {
  2959. requirejs.browser.saveFile(fileName, fileContents, encoding);
  2960. },
  2961. deleteFile: function (fileName) {
  2962. console.log('file.deleteFile is no-op in browser');
  2963. },
  2964. /**
  2965. * Deletes any empty directories under the given directory.
  2966. */
  2967. deleteEmptyDirs: function (startDir) {
  2968. console.log('file.deleteEmptyDirs is no-op in browser');
  2969. }
  2970. };
  2971. return file;
  2972. });
  2973. }
  2974. if(env === 'node') {
  2975. /**
  2976. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  2977. * Available via the MIT or new BSD license.
  2978. * see: http://github.com/jrburke/requirejs for details
  2979. */
  2980. /*jslint plusplus: false, octal:false, strict: false */
  2981. /*global define: false, process: false */
  2982. define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) {
  2983. var isWindows = process.platform === 'win32',
  2984. windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
  2985. file;
  2986. function frontSlash(path) {
  2987. return path.replace(/\\/g, '/');
  2988. }
  2989. function exists(path) {
  2990. if (isWindows && path.charAt(path.length - 1) === '/' &&
  2991. path.charAt(path.length - 2) !== ':') {
  2992. path = path.substring(0, path.length - 1);
  2993. }
  2994. try {
  2995. fs.statSync(path);
  2996. return true;
  2997. } catch (e) {
  2998. return false;
  2999. }
  3000. }
  3001. function mkDir(dir) {
  3002. if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {
  3003. fs.mkdirSync(dir, 511);
  3004. }
  3005. }
  3006. function mkFullDir(dir) {
  3007. var parts = dir.split('/'),
  3008. currDir = '',
  3009. first = true;
  3010. parts.forEach(function (part) {
  3011. //First part may be empty string if path starts with a slash.
  3012. currDir += part + '/';
  3013. first = false;
  3014. if (part) {
  3015. mkDir(currDir);
  3016. }
  3017. });
  3018. }
  3019. file = {
  3020. backSlashRegExp: /\\/g,
  3021. exclusionRegExp: /^\./,
  3022. getLineSeparator: function () {
  3023. return '/';
  3024. },
  3025. exists: function (fileName) {
  3026. return exists(fileName);
  3027. },
  3028. parent: function (fileName) {
  3029. var parts = fileName.split('/');
  3030. parts.pop();
  3031. return parts.join('/');
  3032. },
  3033. /**
  3034. * Gets the absolute file path as a string, normalized
  3035. * to using front slashes for path separators.
  3036. * @param {String} fileName
  3037. */
  3038. absPath: function (fileName) {
  3039. return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));
  3040. },
  3041. normalize: function (fileName) {
  3042. return frontSlash(path.normalize(fileName));
  3043. },
  3044. isFile: function (path) {
  3045. return fs.statSync(path).isFile();
  3046. },
  3047. isDirectory: function (path) {
  3048. return fs.statSync(path).isDirectory();
  3049. },
  3050. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {
  3051. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3052. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3053. //and it will be treated as the "include" case.
  3054. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3055. //is set to another value.
  3056. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3057. i, stat, filePath, ok, dirFiles, fileName;
  3058. topDir = startDir;
  3059. regExpInclude = regExpFilters.include || regExpFilters;
  3060. regExpExclude = regExpFilters.exclude || null;
  3061. if (file.exists(topDir)) {
  3062. dirFileArray = fs.readdirSync(topDir);
  3063. for (i = 0; i < dirFileArray.length; i++) {
  3064. fileName = dirFileArray[i];
  3065. filePath = path.join(topDir, fileName);
  3066. stat = fs.statSync(filePath);
  3067. if (stat.isFile()) {
  3068. if (makeUnixPaths) {
  3069. //Make sure we have a JS string.
  3070. if (filePath.indexOf("/") === -1) {
  3071. filePath = frontSlash(filePath);
  3072. }
  3073. }
  3074. ok = true;
  3075. if (regExpInclude) {
  3076. ok = filePath.match(regExpInclude);
  3077. }
  3078. if (ok && regExpExclude) {
  3079. ok = !filePath.match(regExpExclude);
  3080. }
  3081. if (ok && (!file.exclusionRegExp ||
  3082. !file.exclusionRegExp.test(fileName))) {
  3083. files.push(filePath);
  3084. }
  3085. } else if (stat.isDirectory() &&
  3086. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {
  3087. dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);
  3088. files.push.apply(files, dirFiles);
  3089. }
  3090. }
  3091. }
  3092. return files; //Array
  3093. },
  3094. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3095. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3096. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3097. regExpFilter = regExpFilter || /\w/;
  3098. //Normalize th directory names, but keep front slashes.
  3099. //path module on windows now returns backslashed paths.
  3100. srcDir = frontSlash(path.normalize(srcDir));
  3101. destDir = frontSlash(path.normalize(destDir));
  3102. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3103. copiedFiles = [], i, srcFileName, destFileName;
  3104. for (i = 0; i < fileNames.length; i++) {
  3105. srcFileName = fileNames[i];
  3106. destFileName = srcFileName.replace(srcDir, destDir);
  3107. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3108. copiedFiles.push(destFileName);
  3109. }
  3110. }
  3111. return copiedFiles.length ? copiedFiles : null; //Array or null
  3112. },
  3113. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3114. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3115. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3116. var parentDir;
  3117. //logger.trace("Src filename: " + srcFileName);
  3118. //logger.trace("Dest filename: " + destFileName);
  3119. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3120. //than dest.
  3121. if (onlyCopyNew) {
  3122. if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {
  3123. return false; //Boolean
  3124. }
  3125. }
  3126. //Make sure destination dir exists.
  3127. parentDir = path.dirname(destFileName);
  3128. if (!file.exists(parentDir)) {
  3129. mkFullDir(parentDir);
  3130. }
  3131. fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');
  3132. return true; //Boolean
  3133. },
  3134. /**
  3135. * Renames a file. May fail if "to" already exists or is on another drive.
  3136. */
  3137. renameFile: function (from, to) {
  3138. return fs.renameSync(from, to);
  3139. },
  3140. /**
  3141. * Reads a *text* file.
  3142. */
  3143. readFile: function (/*String*/path, /*String?*/encoding) {
  3144. if (encoding === 'utf-8') {
  3145. encoding = 'utf8';
  3146. }
  3147. if (!encoding) {
  3148. encoding = 'utf8';
  3149. }
  3150. var text = fs.readFileSync(path, encoding);
  3151. //Hmm, would not expect to get A BOM, but it seems to happen,
  3152. //remove it just in case.
  3153. if (text.indexOf('\uFEFF') === 0) {
  3154. text = text.substring(1, text.length);
  3155. }
  3156. return text;
  3157. },
  3158. readFileAsync: function (path, encoding) {
  3159. var d = prim();
  3160. try {
  3161. d.resolve(file.readFile(path, encoding));
  3162. } catch (e) {
  3163. d.reject(e);
  3164. }
  3165. return d.promise;
  3166. },
  3167. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3168. //summary: saves a *text* file using UTF-8 encoding.
  3169. file.saveFile(fileName, fileContents, "utf8");
  3170. },
  3171. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3172. //summary: saves a *text* file.
  3173. var parentDir;
  3174. if (encoding === 'utf-8') {
  3175. encoding = 'utf8';
  3176. }
  3177. if (!encoding) {
  3178. encoding = 'utf8';
  3179. }
  3180. //Make sure destination directories exist.
  3181. parentDir = path.dirname(fileName);
  3182. if (!file.exists(parentDir)) {
  3183. mkFullDir(parentDir);
  3184. }
  3185. fs.writeFileSync(fileName, fileContents, encoding);
  3186. },
  3187. deleteFile: function (/*String*/fileName) {
  3188. //summary: deletes a file or directory if it exists.
  3189. var files, i, stat;
  3190. if (file.exists(fileName)) {
  3191. stat = fs.lstatSync(fileName);
  3192. if (stat.isDirectory()) {
  3193. files = fs.readdirSync(fileName);
  3194. for (i = 0; i < files.length; i++) {
  3195. this.deleteFile(path.join(fileName, files[i]));
  3196. }
  3197. fs.rmdirSync(fileName);
  3198. } else {
  3199. fs.unlinkSync(fileName);
  3200. }
  3201. }
  3202. },
  3203. /**
  3204. * Deletes any empty directories under the given directory.
  3205. */
  3206. deleteEmptyDirs: function (startDir) {
  3207. var dirFileArray, i, fileName, filePath, stat;
  3208. if (file.exists(startDir)) {
  3209. dirFileArray = fs.readdirSync(startDir);
  3210. for (i = 0; i < dirFileArray.length; i++) {
  3211. fileName = dirFileArray[i];
  3212. filePath = path.join(startDir, fileName);
  3213. stat = fs.lstatSync(filePath);
  3214. if (stat.isDirectory()) {
  3215. file.deleteEmptyDirs(filePath);
  3216. }
  3217. }
  3218. //If directory is now empty, remove it.
  3219. if (fs.readdirSync(startDir).length === 0) {
  3220. file.deleteFile(startDir);
  3221. }
  3222. }
  3223. }
  3224. };
  3225. return file;
  3226. });
  3227. }
  3228. if(env === 'rhino') {
  3229. /**
  3230. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3231. * Available via the MIT or new BSD license.
  3232. * see: http://github.com/jrburke/requirejs for details
  3233. */
  3234. //Helper functions to deal with file I/O.
  3235. /*jslint plusplus: false */
  3236. /*global java: false, define: false */
  3237. define('rhino/file', ['prim'], function (prim) {
  3238. var file = {
  3239. backSlashRegExp: /\\/g,
  3240. exclusionRegExp: /^\./,
  3241. getLineSeparator: function () {
  3242. return file.lineSeparator;
  3243. },
  3244. lineSeparator: java.lang.System.getProperty("line.separator"), //Java String
  3245. exists: function (fileName) {
  3246. return (new java.io.File(fileName)).exists();
  3247. },
  3248. parent: function (fileName) {
  3249. return file.absPath((new java.io.File(fileName)).getParentFile());
  3250. },
  3251. normalize: function (fileName) {
  3252. return file.absPath(fileName);
  3253. },
  3254. isFile: function (path) {
  3255. return (new java.io.File(path)).isFile();
  3256. },
  3257. isDirectory: function (path) {
  3258. return (new java.io.File(path)).isDirectory();
  3259. },
  3260. /**
  3261. * Gets the absolute file path as a string, normalized
  3262. * to using front slashes for path separators.
  3263. * @param {java.io.File||String} file
  3264. */
  3265. absPath: function (fileObj) {
  3266. if (typeof fileObj === "string") {
  3267. fileObj = new java.io.File(fileObj);
  3268. }
  3269. return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
  3270. },
  3271. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {
  3272. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3273. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3274. //and it will be treated as the "include" case.
  3275. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3276. //is set to another value.
  3277. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3278. i, fileObj, filePath, ok, dirFiles;
  3279. topDir = startDir;
  3280. if (!startDirIsJavaObject) {
  3281. topDir = new java.io.File(startDir);
  3282. }
  3283. regExpInclude = regExpFilters.include || regExpFilters;
  3284. regExpExclude = regExpFilters.exclude || null;
  3285. if (topDir.exists()) {
  3286. dirFileArray = topDir.listFiles();
  3287. for (i = 0; i < dirFileArray.length; i++) {
  3288. fileObj = dirFileArray[i];
  3289. if (fileObj.isFile()) {
  3290. filePath = fileObj.getPath();
  3291. if (makeUnixPaths) {
  3292. //Make sure we have a JS string.
  3293. filePath = String(filePath);
  3294. if (filePath.indexOf("/") === -1) {
  3295. filePath = filePath.replace(/\\/g, "/");
  3296. }
  3297. }
  3298. ok = true;
  3299. if (regExpInclude) {
  3300. ok = filePath.match(regExpInclude);
  3301. }
  3302. if (ok && regExpExclude) {
  3303. ok = !filePath.match(regExpExclude);
  3304. }
  3305. if (ok && (!file.exclusionRegExp ||
  3306. !file.exclusionRegExp.test(fileObj.getName()))) {
  3307. files.push(filePath);
  3308. }
  3309. } else if (fileObj.isDirectory() &&
  3310. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {
  3311. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3312. files.push.apply(files, dirFiles);
  3313. }
  3314. }
  3315. }
  3316. return files; //Array
  3317. },
  3318. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3319. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3320. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3321. regExpFilter = regExpFilter || /\w/;
  3322. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3323. copiedFiles = [], i, srcFileName, destFileName;
  3324. for (i = 0; i < fileNames.length; i++) {
  3325. srcFileName = fileNames[i];
  3326. destFileName = srcFileName.replace(srcDir, destDir);
  3327. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3328. copiedFiles.push(destFileName);
  3329. }
  3330. }
  3331. return copiedFiles.length ? copiedFiles : null; //Array or null
  3332. },
  3333. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3334. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3335. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3336. var destFile = new java.io.File(destFileName), srcFile, parentDir,
  3337. srcChannel, destChannel;
  3338. //logger.trace("Src filename: " + srcFileName);
  3339. //logger.trace("Dest filename: " + destFileName);
  3340. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3341. //than dest.
  3342. if (onlyCopyNew) {
  3343. srcFile = new java.io.File(srcFileName);
  3344. if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {
  3345. return false; //Boolean
  3346. }
  3347. }
  3348. //Make sure destination dir exists.
  3349. parentDir = destFile.getParentFile();
  3350. if (!parentDir.exists()) {
  3351. if (!parentDir.mkdirs()) {
  3352. throw "Could not create directory: " + parentDir.getCanonicalPath();
  3353. }
  3354. }
  3355. //Java's version of copy file.
  3356. srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
  3357. destChannel = new java.io.FileOutputStream(destFileName).getChannel();
  3358. destChannel.transferFrom(srcChannel, 0, srcChannel.size());
  3359. srcChannel.close();
  3360. destChannel.close();
  3361. return true; //Boolean
  3362. },
  3363. /**
  3364. * Renames a file. May fail if "to" already exists or is on another drive.
  3365. */
  3366. renameFile: function (from, to) {
  3367. return (new java.io.File(from)).renameTo((new java.io.File(to)));
  3368. },
  3369. readFile: function (/*String*/path, /*String?*/encoding) {
  3370. //A file read function that can deal with BOMs
  3371. encoding = encoding || "utf-8";
  3372. var fileObj = new java.io.File(path),
  3373. input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),
  3374. stringBuffer, line;
  3375. try {
  3376. stringBuffer = new java.lang.StringBuffer();
  3377. line = input.readLine();
  3378. // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
  3379. // http://www.unicode.org/faq/utf_bom.html
  3380. // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
  3381. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
  3382. if (line && line.length() && line.charAt(0) === 0xfeff) {
  3383. // Eat the BOM, since we've already found the encoding on this file,
  3384. // and we plan to concatenating this buffer with others; the BOM should
  3385. // only appear at the top of a file.
  3386. line = line.substring(1);
  3387. }
  3388. while (line !== null) {
  3389. stringBuffer.append(line);
  3390. stringBuffer.append(file.lineSeparator);
  3391. line = input.readLine();
  3392. }
  3393. //Make sure we return a JavaScript string and not a Java string.
  3394. return String(stringBuffer.toString()); //String
  3395. } finally {
  3396. input.close();
  3397. }
  3398. },
  3399. readFileAsync: function (path, encoding) {
  3400. var d = prim();
  3401. try {
  3402. d.resolve(file.readFile(path, encoding));
  3403. } catch (e) {
  3404. d.reject(e);
  3405. }
  3406. return d.promise;
  3407. },
  3408. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3409. //summary: saves a file using UTF-8 encoding.
  3410. file.saveFile(fileName, fileContents, "utf-8");
  3411. },
  3412. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3413. //summary: saves a file.
  3414. var outFile = new java.io.File(fileName), outWriter, parentDir, os;
  3415. parentDir = outFile.getAbsoluteFile().getParentFile();
  3416. if (!parentDir.exists()) {
  3417. if (!parentDir.mkdirs()) {
  3418. throw "Could not create directory: " + parentDir.getAbsolutePath();
  3419. }
  3420. }
  3421. if (encoding) {
  3422. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  3423. } else {
  3424. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  3425. }
  3426. os = new java.io.BufferedWriter(outWriter);
  3427. try {
  3428. //If in Nashorn, need to coerce the JS string to a Java string so that
  3429. //writer.write method dispatch correctly detects the type.
  3430. if (typeof importPackage !== 'undefined') {
  3431. os.write(fileContents);
  3432. } else {
  3433. os.write(new java.lang.String(fileContents));
  3434. }
  3435. } finally {
  3436. os.close();
  3437. }
  3438. },
  3439. deleteFile: function (/*String*/fileName) {
  3440. //summary: deletes a file or directory if it exists.
  3441. var fileObj = new java.io.File(fileName), files, i;
  3442. if (fileObj.exists()) {
  3443. if (fileObj.isDirectory()) {
  3444. files = fileObj.listFiles();
  3445. for (i = 0; i < files.length; i++) {
  3446. this.deleteFile(files[i]);
  3447. }
  3448. }
  3449. fileObj["delete"]();
  3450. }
  3451. },
  3452. /**
  3453. * Deletes any empty directories under the given directory.
  3454. * The startDirIsJavaObject is private to this implementation's
  3455. * recursion needs.
  3456. */
  3457. deleteEmptyDirs: function (startDir, startDirIsJavaObject) {
  3458. var topDir = startDir,
  3459. dirFileArray, i, fileObj;
  3460. if (!startDirIsJavaObject) {
  3461. topDir = new java.io.File(startDir);
  3462. }
  3463. if (topDir.exists()) {
  3464. dirFileArray = topDir.listFiles();
  3465. for (i = 0; i < dirFileArray.length; i++) {
  3466. fileObj = dirFileArray[i];
  3467. if (fileObj.isDirectory()) {
  3468. file.deleteEmptyDirs(fileObj, true);
  3469. }
  3470. }
  3471. //If the directory is empty now, delete it.
  3472. if (topDir.listFiles().length === 0) {
  3473. file.deleteFile(String(topDir.getPath()));
  3474. }
  3475. }
  3476. }
  3477. };
  3478. return file;
  3479. });
  3480. }
  3481. if(env === 'xpconnect') {
  3482. /**
  3483. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  3484. * Available via the MIT or new BSD license.
  3485. * see: http://github.com/jrburke/requirejs for details
  3486. */
  3487. //Helper functions to deal with file I/O.
  3488. /*jslint plusplus: false */
  3489. /*global define, Components, xpcUtil */
  3490. define('xpconnect/file', ['prim'], function (prim) {
  3491. var file,
  3492. Cc = Components.classes,
  3493. Ci = Components.interfaces,
  3494. //Depends on xpcUtil which is set up in x.js
  3495. xpfile = xpcUtil.xpfile;
  3496. function mkFullDir(dirObj) {
  3497. //1 is DIRECTORY_TYPE, 511 is 0777 permissions
  3498. if (!dirObj.exists()) {
  3499. dirObj.create(1, 511);
  3500. }
  3501. }
  3502. file = {
  3503. backSlashRegExp: /\\/g,
  3504. exclusionRegExp: /^\./,
  3505. getLineSeparator: function () {
  3506. return file.lineSeparator;
  3507. },
  3508. lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ?
  3509. '\r\n' : '\n',
  3510. exists: function (fileName) {
  3511. return xpfile(fileName).exists();
  3512. },
  3513. parent: function (fileName) {
  3514. return xpfile(fileName).parent;
  3515. },
  3516. normalize: function (fileName) {
  3517. return file.absPath(fileName);
  3518. },
  3519. isFile: function (path) {
  3520. return xpfile(path).isFile();
  3521. },
  3522. isDirectory: function (path) {
  3523. return xpfile(path).isDirectory();
  3524. },
  3525. /**
  3526. * Gets the absolute file path as a string, normalized
  3527. * to using front slashes for path separators.
  3528. * @param {java.io.File||String} file
  3529. */
  3530. absPath: function (fileObj) {
  3531. if (typeof fileObj === "string") {
  3532. fileObj = xpfile(fileObj);
  3533. }
  3534. return fileObj.path;
  3535. },
  3536. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) {
  3537. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3538. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3539. //and it will be treated as the "include" case.
  3540. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3541. //is set to another value.
  3542. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3543. fileObj, filePath, ok, dirFiles;
  3544. topDir = startDir;
  3545. if (!startDirIsObject) {
  3546. topDir = xpfile(startDir);
  3547. }
  3548. regExpInclude = regExpFilters.include || regExpFilters;
  3549. regExpExclude = regExpFilters.exclude || null;
  3550. if (topDir.exists()) {
  3551. dirFileArray = topDir.directoryEntries;
  3552. while (dirFileArray.hasMoreElements()) {
  3553. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3554. if (fileObj.isFile()) {
  3555. filePath = fileObj.path;
  3556. if (makeUnixPaths) {
  3557. if (filePath.indexOf("/") === -1) {
  3558. filePath = filePath.replace(/\\/g, "/");
  3559. }
  3560. }
  3561. ok = true;
  3562. if (regExpInclude) {
  3563. ok = filePath.match(regExpInclude);
  3564. }
  3565. if (ok && regExpExclude) {
  3566. ok = !filePath.match(regExpExclude);
  3567. }
  3568. if (ok && (!file.exclusionRegExp ||
  3569. !file.exclusionRegExp.test(fileObj.leafName))) {
  3570. files.push(filePath);
  3571. }
  3572. } else if (fileObj.isDirectory() &&
  3573. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) {
  3574. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3575. files.push.apply(files, dirFiles);
  3576. }
  3577. }
  3578. }
  3579. return files; //Array
  3580. },
  3581. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3582. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3583. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3584. regExpFilter = regExpFilter || /\w/;
  3585. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3586. copiedFiles = [], i, srcFileName, destFileName;
  3587. for (i = 0; i < fileNames.length; i += 1) {
  3588. srcFileName = fileNames[i];
  3589. destFileName = srcFileName.replace(srcDir, destDir);
  3590. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3591. copiedFiles.push(destFileName);
  3592. }
  3593. }
  3594. return copiedFiles.length ? copiedFiles : null; //Array or null
  3595. },
  3596. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3597. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3598. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3599. var destFile = xpfile(destFileName),
  3600. srcFile = xpfile(srcFileName);
  3601. //logger.trace("Src filename: " + srcFileName);
  3602. //logger.trace("Dest filename: " + destFileName);
  3603. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3604. //than dest.
  3605. if (onlyCopyNew) {
  3606. if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) {
  3607. return false; //Boolean
  3608. }
  3609. }
  3610. srcFile.copyTo(destFile.parent, destFile.leafName);
  3611. return true; //Boolean
  3612. },
  3613. /**
  3614. * Renames a file. May fail if "to" already exists or is on another drive.
  3615. */
  3616. renameFile: function (from, to) {
  3617. var toFile = xpfile(to);
  3618. return xpfile(from).moveTo(toFile.parent, toFile.leafName);
  3619. },
  3620. readFile: xpcUtil.readFile,
  3621. readFileAsync: function (path, encoding) {
  3622. var d = prim();
  3623. try {
  3624. d.resolve(file.readFile(path, encoding));
  3625. } catch (e) {
  3626. d.reject(e);
  3627. }
  3628. return d.promise;
  3629. },
  3630. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3631. //summary: saves a file using UTF-8 encoding.
  3632. file.saveFile(fileName, fileContents, "utf-8");
  3633. },
  3634. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3635. var outStream, convertStream,
  3636. fileObj = xpfile(fileName);
  3637. mkFullDir(fileObj.parent);
  3638. try {
  3639. outStream = Cc['@mozilla.org/network/file-output-stream;1']
  3640. .createInstance(Ci.nsIFileOutputStream);
  3641. //438 is decimal for 0777
  3642. outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0);
  3643. convertStream = Cc['@mozilla.org/intl/converter-output-stream;1']
  3644. .createInstance(Ci.nsIConverterOutputStream);
  3645. convertStream.init(outStream, encoding, 0, 0);
  3646. convertStream.writeString(fileContents);
  3647. } catch (e) {
  3648. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  3649. } finally {
  3650. if (convertStream) {
  3651. convertStream.close();
  3652. }
  3653. if (outStream) {
  3654. outStream.close();
  3655. }
  3656. }
  3657. },
  3658. deleteFile: function (/*String*/fileName) {
  3659. //summary: deletes a file or directory if it exists.
  3660. var fileObj = xpfile(fileName);
  3661. if (fileObj.exists()) {
  3662. fileObj.remove(true);
  3663. }
  3664. },
  3665. /**
  3666. * Deletes any empty directories under the given directory.
  3667. * The startDirIsJavaObject is private to this implementation's
  3668. * recursion needs.
  3669. */
  3670. deleteEmptyDirs: function (startDir, startDirIsObject) {
  3671. var topDir = startDir,
  3672. dirFileArray, fileObj;
  3673. if (!startDirIsObject) {
  3674. topDir = xpfile(startDir);
  3675. }
  3676. if (topDir.exists()) {
  3677. dirFileArray = topDir.directoryEntries;
  3678. while (dirFileArray.hasMoreElements()) {
  3679. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3680. if (fileObj.isDirectory()) {
  3681. file.deleteEmptyDirs(fileObj, true);
  3682. }
  3683. }
  3684. //If the directory is empty now, delete it.
  3685. dirFileArray = topDir.directoryEntries;
  3686. if (!dirFileArray.hasMoreElements()) {
  3687. file.deleteFile(topDir.path);
  3688. }
  3689. }
  3690. }
  3691. };
  3692. return file;
  3693. });
  3694. }
  3695. if(env === 'browser') {
  3696. /*global process */
  3697. define('browser/quit', function () {
  3698. 'use strict';
  3699. return function (code) {
  3700. };
  3701. });
  3702. }
  3703. if(env === 'node') {
  3704. /*global process */
  3705. define('node/quit', function () {
  3706. 'use strict';
  3707. return function (code) {
  3708. var draining = 0;
  3709. var exit = function () {
  3710. if (draining === 0) {
  3711. process.exit(code);
  3712. } else {
  3713. draining -= 1;
  3714. }
  3715. };
  3716. if (process.stdout.bufferSize) {
  3717. draining += 1;
  3718. process.stdout.once('drain', exit);
  3719. }
  3720. if (process.stderr.bufferSize) {
  3721. draining += 1;
  3722. process.stderr.once('drain', exit);
  3723. }
  3724. exit();
  3725. };
  3726. });
  3727. }
  3728. if(env === 'rhino') {
  3729. /*global quit */
  3730. define('rhino/quit', function () {
  3731. 'use strict';
  3732. return function (code) {
  3733. return quit(code);
  3734. };
  3735. });
  3736. }
  3737. if(env === 'xpconnect') {
  3738. /*global quit */
  3739. define('xpconnect/quit', function () {
  3740. 'use strict';
  3741. return function (code) {
  3742. return quit(code);
  3743. };
  3744. });
  3745. }
  3746. if(env === 'browser') {
  3747. /**
  3748. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3749. * Available via the MIT or new BSD license.
  3750. * see: http://github.com/jrburke/requirejs for details
  3751. */
  3752. /*jslint strict: false */
  3753. /*global define: false, console: false */
  3754. define('browser/print', function () {
  3755. function print(msg) {
  3756. console.log(msg);
  3757. }
  3758. return print;
  3759. });
  3760. }
  3761. if(env === 'node') {
  3762. /**
  3763. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3764. * Available via the MIT or new BSD license.
  3765. * see: http://github.com/jrburke/requirejs for details
  3766. */
  3767. /*jslint strict: false */
  3768. /*global define: false, console: false */
  3769. define('node/print', function () {
  3770. function print(msg) {
  3771. console.log(msg);
  3772. }
  3773. return print;
  3774. });
  3775. }
  3776. if(env === 'rhino') {
  3777. /**
  3778. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3779. * Available via the MIT or new BSD license.
  3780. * see: http://github.com/jrburke/requirejs for details
  3781. */
  3782. /*jslint strict: false */
  3783. /*global define: false, print: false */
  3784. define('rhino/print', function () {
  3785. return print;
  3786. });
  3787. }
  3788. if(env === 'xpconnect') {
  3789. /**
  3790. * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
  3791. * Available via the MIT or new BSD license.
  3792. * see: http://github.com/jrburke/requirejs for details
  3793. */
  3794. /*jslint strict: false */
  3795. /*global define: false, print: false */
  3796. define('xpconnect/print', function () {
  3797. return print;
  3798. });
  3799. }
  3800. /**
  3801. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  3802. * Available via the MIT or new BSD license.
  3803. * see: http://github.com/jrburke/requirejs for details
  3804. */
  3805. /*jslint nomen: false, strict: false */
  3806. /*global define: false */
  3807. define('logger', ['env!env/print'], function (print) {
  3808. var logger = {
  3809. TRACE: 0,
  3810. INFO: 1,
  3811. WARN: 2,
  3812. ERROR: 3,
  3813. SILENT: 4,
  3814. level: 0,
  3815. logPrefix: "",
  3816. logLevel: function( level ) {
  3817. this.level = level;
  3818. },
  3819. trace: function (message) {
  3820. if (this.level <= this.TRACE) {
  3821. this._print(message);
  3822. }
  3823. },
  3824. info: function (message) {
  3825. if (this.level <= this.INFO) {
  3826. this._print(message);
  3827. }
  3828. },
  3829. warn: function (message) {
  3830. if (this.level <= this.WARN) {
  3831. this._print(message);
  3832. }
  3833. },
  3834. error: function (message) {
  3835. if (this.level <= this.ERROR) {
  3836. this._print(message);
  3837. }
  3838. },
  3839. _print: function (message) {
  3840. this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message);
  3841. },
  3842. _sysPrint: function (message) {
  3843. print(message);
  3844. }
  3845. };
  3846. return logger;
  3847. });
  3848. //Just a blank file to use when building the optimizer with the optimizer,
  3849. //so that the build does not attempt to inline some env modules,
  3850. //like Node's fs and path.
  3851. /*
  3852. Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
  3853. Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
  3854. Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be>
  3855. Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  3856. Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
  3857. Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  3858. Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  3859. Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
  3860. Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  3861. Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
  3862. Redistribution and use in source and binary forms, with or without
  3863. modification, are permitted provided that the following conditions are met:
  3864. * Redistributions of source code must retain the above copyright
  3865. notice, this list of conditions and the following disclaimer.
  3866. * Redistributions in binary form must reproduce the above copyright
  3867. notice, this list of conditions and the following disclaimer in the
  3868. documentation and/or other materials provided with the distribution.
  3869. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3870. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3871. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3872. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  3873. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  3874. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  3875. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  3876. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  3877. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  3878. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3879. */
  3880. (function (root, factory) {
  3881. 'use strict';
  3882. // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
  3883. // Rhino, and plain browser loading.
  3884. /* istanbul ignore next */
  3885. if (typeof define === 'function' && define.amd) {
  3886. define('esprima', ['exports'], factory);
  3887. } else if (typeof exports !== 'undefined') {
  3888. factory(exports);
  3889. } else {
  3890. factory((root.esprima = {}));
  3891. }
  3892. }(this, function (exports) {
  3893. 'use strict';
  3894. var Token,
  3895. TokenName,
  3896. FnExprTokens,
  3897. Syntax,
  3898. PlaceHolders,
  3899. Messages,
  3900. Regex,
  3901. source,
  3902. strict,
  3903. index,
  3904. lineNumber,
  3905. lineStart,
  3906. hasLineTerminator,
  3907. lastIndex,
  3908. lastLineNumber,
  3909. lastLineStart,
  3910. startIndex,
  3911. startLineNumber,
  3912. startLineStart,
  3913. scanning,
  3914. length,
  3915. lookahead,
  3916. state,
  3917. extra;
  3918. Token = {
  3919. BooleanLiteral: 1,
  3920. EOF: 2,
  3921. Identifier: 3,
  3922. Keyword: 4,
  3923. NullLiteral: 5,
  3924. NumericLiteral: 6,
  3925. Punctuator: 7,
  3926. StringLiteral: 8,
  3927. RegularExpression: 9
  3928. };
  3929. TokenName = {};
  3930. TokenName[Token.BooleanLiteral] = 'Boolean';
  3931. TokenName[Token.EOF] = '<end>';
  3932. TokenName[Token.Identifier] = 'Identifier';
  3933. TokenName[Token.Keyword] = 'Keyword';
  3934. TokenName[Token.NullLiteral] = 'Null';
  3935. TokenName[Token.NumericLiteral] = 'Numeric';
  3936. TokenName[Token.Punctuator] = 'Punctuator';
  3937. TokenName[Token.StringLiteral] = 'String';
  3938. TokenName[Token.RegularExpression] = 'RegularExpression';
  3939. // A function following one of those tokens is an expression.
  3940. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
  3941. 'return', 'case', 'delete', 'throw', 'void',
  3942. // assignment operators
  3943. '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
  3944. '&=', '|=', '^=', ',',
  3945. // binary/unary operators
  3946. '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
  3947. '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
  3948. '<=', '<', '>', '!=', '!=='];
  3949. Syntax = {
  3950. AssignmentExpression: 'AssignmentExpression',
  3951. ArrayExpression: 'ArrayExpression',
  3952. ArrowFunctionExpression: 'ArrowFunctionExpression',
  3953. BlockStatement: 'BlockStatement',
  3954. BinaryExpression: 'BinaryExpression',
  3955. BreakStatement: 'BreakStatement',
  3956. CallExpression: 'CallExpression',
  3957. CatchClause: 'CatchClause',
  3958. ClassBody: 'ClassBody',
  3959. ClassDeclaration: 'ClassDeclaration',
  3960. ClassExpression: 'ClassExpression',
  3961. ConditionalExpression: 'ConditionalExpression',
  3962. ContinueStatement: 'ContinueStatement',
  3963. DoWhileStatement: 'DoWhileStatement',
  3964. DebuggerStatement: 'DebuggerStatement',
  3965. EmptyStatement: 'EmptyStatement',
  3966. ExpressionStatement: 'ExpressionStatement',
  3967. ForStatement: 'ForStatement',
  3968. ForInStatement: 'ForInStatement',
  3969. FunctionDeclaration: 'FunctionDeclaration',
  3970. FunctionExpression: 'FunctionExpression',
  3971. Identifier: 'Identifier',
  3972. IfStatement: 'IfStatement',
  3973. Literal: 'Literal',
  3974. LabeledStatement: 'LabeledStatement',
  3975. LogicalExpression: 'LogicalExpression',
  3976. MemberExpression: 'MemberExpression',
  3977. MethodDefinition: 'MethodDefinition',
  3978. NewExpression: 'NewExpression',
  3979. ObjectExpression: 'ObjectExpression',
  3980. Program: 'Program',
  3981. Property: 'Property',
  3982. RestElement: 'RestElement',
  3983. ReturnStatement: 'ReturnStatement',
  3984. SequenceExpression: 'SequenceExpression',
  3985. SwitchStatement: 'SwitchStatement',
  3986. SwitchCase: 'SwitchCase',
  3987. ThisExpression: 'ThisExpression',
  3988. ThrowStatement: 'ThrowStatement',
  3989. TryStatement: 'TryStatement',
  3990. UnaryExpression: 'UnaryExpression',
  3991. UpdateExpression: 'UpdateExpression',
  3992. VariableDeclaration: 'VariableDeclaration',
  3993. VariableDeclarator: 'VariableDeclarator',
  3994. WhileStatement: 'WhileStatement',
  3995. WithStatement: 'WithStatement'
  3996. };
  3997. PlaceHolders = {
  3998. ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder'
  3999. };
  4000. // Error messages should be identical to V8.
  4001. Messages = {
  4002. UnexpectedToken: 'Unexpected token %0',
  4003. UnexpectedNumber: 'Unexpected number',
  4004. UnexpectedString: 'Unexpected string',
  4005. UnexpectedIdentifier: 'Unexpected identifier',
  4006. UnexpectedReserved: 'Unexpected reserved word',
  4007. UnexpectedEOS: 'Unexpected end of input',
  4008. NewlineAfterThrow: 'Illegal newline after throw',
  4009. InvalidRegExp: 'Invalid regular expression',
  4010. UnterminatedRegExp: 'Invalid regular expression: missing /',
  4011. InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  4012. InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  4013. MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
  4014. NoCatchOrFinally: 'Missing catch or finally after try',
  4015. UnknownLabel: 'Undefined label \'%0\'',
  4016. Redeclaration: '%0 \'%1\' has already been declared',
  4017. IllegalContinue: 'Illegal continue statement',
  4018. IllegalBreak: 'Illegal break statement',
  4019. IllegalReturn: 'Illegal return statement',
  4020. StrictModeWith: 'Strict mode code may not include a with statement',
  4021. StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  4022. StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  4023. StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  4024. StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  4025. StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  4026. StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  4027. StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  4028. StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  4029. StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  4030. StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  4031. StrictReservedWord: 'Use of future reserved word in strict mode',
  4032. ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
  4033. DefaultRestParameter: 'Unexpected token =',
  4034. ObjectPatternAsRestParameter: 'Unexpected token {',
  4035. DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
  4036. ConstructorSpecialMethod: 'Class constructor may not be an accessor',
  4037. DuplicateConstructor: 'A class may only have one constructor',
  4038. StaticPrototype: 'Classes may not have static property named prototype'
  4039. };
  4040. // See also tools/generate-unicode-regex.py.
  4041. Regex = {
  4042. NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\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-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\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-\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-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\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-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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]'),
  4043. NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\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-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\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\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\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\u0D01-\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\u0DE6-\u0DEF\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-\u16F8\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-\u191E\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\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\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-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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-\uFE2D\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]')
  4044. };
  4045. // Ensure the condition is true, otherwise throw an error.
  4046. // This is only to have a better contract semantic, i.e. another safety net
  4047. // to catch a logic error. The condition shall be fulfilled in normal case.
  4048. // Do NOT use this to enforce a certain condition on any user input.
  4049. function assert(condition, message) {
  4050. /* istanbul ignore if */
  4051. if (!condition) {
  4052. throw new Error('ASSERT: ' + message);
  4053. }
  4054. }
  4055. function isDecimalDigit(ch) {
  4056. return (ch >= 0x30 && ch <= 0x39); // 0..9
  4057. }
  4058. function isHexDigit(ch) {
  4059. return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
  4060. }
  4061. function isOctalDigit(ch) {
  4062. return '01234567'.indexOf(ch) >= 0;
  4063. }
  4064. // 7.2 White Space
  4065. function isWhiteSpace(ch) {
  4066. return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
  4067. (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
  4068. }
  4069. // 7.3 Line Terminators
  4070. function isLineTerminator(ch) {
  4071. return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
  4072. }
  4073. // 7.6 Identifier Names and Identifiers
  4074. function isIdentifierStart(ch) {
  4075. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  4076. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  4077. (ch >= 0x61 && ch <= 0x7A) || // a..z
  4078. (ch === 0x5C) || // \ (backslash)
  4079. ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
  4080. }
  4081. function isIdentifierPart(ch) {
  4082. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  4083. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  4084. (ch >= 0x61 && ch <= 0x7A) || // a..z
  4085. (ch >= 0x30 && ch <= 0x39) || // 0..9
  4086. (ch === 0x5C) || // \ (backslash)
  4087. ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
  4088. }
  4089. // 7.6.1.2 Future Reserved Words
  4090. function isFutureReservedWord(id) {
  4091. switch (id) {
  4092. case 'enum':
  4093. case 'export':
  4094. case 'import':
  4095. case 'super':
  4096. return true;
  4097. default:
  4098. return false;
  4099. }
  4100. }
  4101. // 11.6.2.2 Future Reserved Words
  4102. function isStrictModeReservedWord(id) {
  4103. switch (id) {
  4104. case 'implements':
  4105. case 'interface':
  4106. case 'package':
  4107. case 'private':
  4108. case 'protected':
  4109. case 'public':
  4110. case 'static':
  4111. case 'yield':
  4112. case 'let':
  4113. return true;
  4114. default:
  4115. return false;
  4116. }
  4117. }
  4118. function isRestrictedWord(id) {
  4119. return id === 'eval' || id === 'arguments';
  4120. }
  4121. // 7.6.1.1 Keywords
  4122. function isKeyword(id) {
  4123. if (strict && isStrictModeReservedWord(id)) {
  4124. return true;
  4125. }
  4126. // 'const' is specialized as Keyword in V8.
  4127. // 'yield' and 'let' are for compatibility with SpiderMonkey and ES.next.
  4128. // Some others are from future reserved words.
  4129. switch (id.length) {
  4130. case 2:
  4131. return (id === 'if') || (id === 'in') || (id === 'do');
  4132. case 3:
  4133. return (id === 'var') || (id === 'for') || (id === 'new') ||
  4134. (id === 'try') || (id === 'let');
  4135. case 4:
  4136. return (id === 'this') || (id === 'else') || (id === 'case') ||
  4137. (id === 'void') || (id === 'with') || (id === 'enum');
  4138. case 5:
  4139. return (id === 'while') || (id === 'break') || (id === 'catch') ||
  4140. (id === 'throw') || (id === 'const') || (id === 'yield') ||
  4141. (id === 'class') || (id === 'super');
  4142. case 6:
  4143. return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
  4144. (id === 'switch') || (id === 'export') || (id === 'import');
  4145. case 7:
  4146. return (id === 'default') || (id === 'finally') || (id === 'extends');
  4147. case 8:
  4148. return (id === 'function') || (id === 'continue') || (id === 'debugger');
  4149. case 10:
  4150. return (id === 'instanceof');
  4151. default:
  4152. return false;
  4153. }
  4154. }
  4155. // 7.4 Comments
  4156. function addComment(type, value, start, end, loc) {
  4157. var comment;
  4158. assert(typeof start === 'number', 'Comment must have valid position');
  4159. state.lastCommentStart = start;
  4160. comment = {
  4161. type: type,
  4162. value: value
  4163. };
  4164. if (extra.range) {
  4165. comment.range = [start, end];
  4166. }
  4167. if (extra.loc) {
  4168. comment.loc = loc;
  4169. }
  4170. extra.comments.push(comment);
  4171. if (extra.attachComment) {
  4172. extra.leadingComments.push(comment);
  4173. extra.trailingComments.push(comment);
  4174. }
  4175. }
  4176. function skipSingleLineComment(offset) {
  4177. var start, loc, ch, comment;
  4178. start = index - offset;
  4179. loc = {
  4180. start: {
  4181. line: lineNumber,
  4182. column: index - lineStart - offset
  4183. }
  4184. };
  4185. while (index < length) {
  4186. ch = source.charCodeAt(index);
  4187. ++index;
  4188. if (isLineTerminator(ch)) {
  4189. hasLineTerminator = true;
  4190. if (extra.comments) {
  4191. comment = source.slice(start + offset, index - 1);
  4192. loc.end = {
  4193. line: lineNumber,
  4194. column: index - lineStart - 1
  4195. };
  4196. addComment('Line', comment, start, index - 1, loc);
  4197. }
  4198. if (ch === 13 && source.charCodeAt(index) === 10) {
  4199. ++index;
  4200. }
  4201. ++lineNumber;
  4202. lineStart = index;
  4203. return;
  4204. }
  4205. }
  4206. if (extra.comments) {
  4207. comment = source.slice(start + offset, index);
  4208. loc.end = {
  4209. line: lineNumber,
  4210. column: index - lineStart
  4211. };
  4212. addComment('Line', comment, start, index, loc);
  4213. }
  4214. }
  4215. function skipMultiLineComment() {
  4216. var start, loc, ch, comment;
  4217. if (extra.comments) {
  4218. start = index - 2;
  4219. loc = {
  4220. start: {
  4221. line: lineNumber,
  4222. column: index - lineStart - 2
  4223. }
  4224. };
  4225. }
  4226. while (index < length) {
  4227. ch = source.charCodeAt(index);
  4228. if (isLineTerminator(ch)) {
  4229. if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
  4230. ++index;
  4231. }
  4232. hasLineTerminator = true;
  4233. ++lineNumber;
  4234. ++index;
  4235. lineStart = index;
  4236. } else if (ch === 0x2A) {
  4237. // Block comment ends with '*/'.
  4238. if (source.charCodeAt(index + 1) === 0x2F) {
  4239. ++index;
  4240. ++index;
  4241. if (extra.comments) {
  4242. comment = source.slice(start + 2, index - 2);
  4243. loc.end = {
  4244. line: lineNumber,
  4245. column: index - lineStart
  4246. };
  4247. addComment('Block', comment, start, index, loc);
  4248. }
  4249. return;
  4250. }
  4251. ++index;
  4252. } else {
  4253. ++index;
  4254. }
  4255. }
  4256. if (extra.errors && index >= length) {
  4257. //ran off the end of the file - the whole thing is a comment
  4258. if (extra.comments) {
  4259. loc.end = {
  4260. line: lineNumber,
  4261. column: index - lineStart
  4262. };
  4263. comment = source.slice(start + 2, index);
  4264. addComment('Block', comment, start, index, loc);
  4265. }
  4266. tolerateUnexpectedToken();
  4267. } else {
  4268. throwUnexpectedToken();
  4269. }
  4270. }
  4271. function skipComment() {
  4272. var ch, start;
  4273. hasLineTerminator = false;
  4274. start = (index === 0);
  4275. while (index < length) {
  4276. ch = source.charCodeAt(index);
  4277. if (isWhiteSpace(ch)) {
  4278. ++index;
  4279. } else if (isLineTerminator(ch)) {
  4280. hasLineTerminator = true;
  4281. ++index;
  4282. if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
  4283. ++index;
  4284. }
  4285. ++lineNumber;
  4286. lineStart = index;
  4287. start = true;
  4288. } else if (ch === 0x2F) { // U+002F is '/'
  4289. ch = source.charCodeAt(index + 1);
  4290. if (ch === 0x2F) {
  4291. ++index;
  4292. ++index;
  4293. skipSingleLineComment(2);
  4294. start = true;
  4295. } else if (ch === 0x2A) { // U+002A is '*'
  4296. ++index;
  4297. ++index;
  4298. skipMultiLineComment();
  4299. } else {
  4300. break;
  4301. }
  4302. } else if (start && ch === 0x2D) { // U+002D is '-'
  4303. // U+003E is '>'
  4304. if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
  4305. // '-->' is a single-line comment
  4306. index += 3;
  4307. skipSingleLineComment(3);
  4308. } else {
  4309. break;
  4310. }
  4311. } else if (ch === 0x3C) { // U+003C is '<'
  4312. if (source.slice(index + 1, index + 4) === '!--') {
  4313. ++index; // `<`
  4314. ++index; // `!`
  4315. ++index; // `-`
  4316. ++index; // `-`
  4317. skipSingleLineComment(4);
  4318. } else {
  4319. break;
  4320. }
  4321. } else {
  4322. break;
  4323. }
  4324. }
  4325. }
  4326. function scanHexEscape(prefix) {
  4327. var i, len, ch, code = 0;
  4328. len = (prefix === 'u') ? 4 : 2;
  4329. for (i = 0; i < len; ++i) {
  4330. if (index < length && isHexDigit(source[index])) {
  4331. ch = source[index++];
  4332. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  4333. } else {
  4334. return '';
  4335. }
  4336. }
  4337. return String.fromCharCode(code);
  4338. }
  4339. function scanUnicodeCodePointEscape() {
  4340. var ch, code, cu1, cu2;
  4341. ch = source[index];
  4342. code = 0;
  4343. // At least, one hex digit is required.
  4344. if (ch === '}') {
  4345. throwUnexpectedToken();
  4346. }
  4347. while (index < length) {
  4348. ch = source[index++];
  4349. if (!isHexDigit(ch)) {
  4350. break;
  4351. }
  4352. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  4353. }
  4354. if (code > 0x10FFFF || ch !== '}') {
  4355. throwUnexpectedToken();
  4356. }
  4357. // UTF-16 Encoding
  4358. if (code <= 0xFFFF) {
  4359. return String.fromCharCode(code);
  4360. }
  4361. cu1 = ((code - 0x10000) >> 10) + 0xD800;
  4362. cu2 = ((code - 0x10000) & 1023) + 0xDC00;
  4363. return String.fromCharCode(cu1, cu2);
  4364. }
  4365. function getEscapedIdentifier() {
  4366. var ch, id;
  4367. ch = source.charCodeAt(index++);
  4368. id = String.fromCharCode(ch);
  4369. // '\u' (U+005C, U+0075) denotes an escaped character.
  4370. if (ch === 0x5C) {
  4371. if (source.charCodeAt(index) !== 0x75) {
  4372. throwUnexpectedToken();
  4373. }
  4374. ++index;
  4375. ch = scanHexEscape('u');
  4376. if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
  4377. throwUnexpectedToken();
  4378. }
  4379. id = ch;
  4380. }
  4381. while (index < length) {
  4382. ch = source.charCodeAt(index);
  4383. if (!isIdentifierPart(ch)) {
  4384. break;
  4385. }
  4386. ++index;
  4387. id += String.fromCharCode(ch);
  4388. // '\u' (U+005C, U+0075) denotes an escaped character.
  4389. if (ch === 0x5C) {
  4390. id = id.substr(0, id.length - 1);
  4391. if (source.charCodeAt(index) !== 0x75) {
  4392. throwUnexpectedToken();
  4393. }
  4394. ++index;
  4395. ch = scanHexEscape('u');
  4396. if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
  4397. throwUnexpectedToken();
  4398. }
  4399. id += ch;
  4400. }
  4401. }
  4402. return id;
  4403. }
  4404. function getIdentifier() {
  4405. var start, ch;
  4406. start = index++;
  4407. while (index < length) {
  4408. ch = source.charCodeAt(index);
  4409. if (ch === 0x5C) {
  4410. // Blackslash (U+005C) marks Unicode escape sequence.
  4411. index = start;
  4412. return getEscapedIdentifier();
  4413. }
  4414. if (isIdentifierPart(ch)) {
  4415. ++index;
  4416. } else {
  4417. break;
  4418. }
  4419. }
  4420. return source.slice(start, index);
  4421. }
  4422. function scanIdentifier() {
  4423. var start, id, type;
  4424. start = index;
  4425. // Backslash (U+005C) starts an escaped character.
  4426. id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier();
  4427. // There is no keyword or literal with only one character.
  4428. // Thus, it must be an identifier.
  4429. if (id.length === 1) {
  4430. type = Token.Identifier;
  4431. } else if (isKeyword(id)) {
  4432. type = Token.Keyword;
  4433. } else if (id === 'null') {
  4434. type = Token.NullLiteral;
  4435. } else if (id === 'true' || id === 'false') {
  4436. type = Token.BooleanLiteral;
  4437. } else {
  4438. type = Token.Identifier;
  4439. }
  4440. return {
  4441. type: type,
  4442. value: id,
  4443. lineNumber: lineNumber,
  4444. lineStart: lineStart,
  4445. start: start,
  4446. end: index
  4447. };
  4448. }
  4449. // 7.7 Punctuators
  4450. function scanPunctuator() {
  4451. var token, str;
  4452. token = {
  4453. type: Token.Punctuator,
  4454. value: '',
  4455. lineNumber: lineNumber,
  4456. lineStart: lineStart,
  4457. start: index,
  4458. end: index
  4459. };
  4460. // Check for most common single-character punctuators.
  4461. str = source[index];
  4462. switch (str) {
  4463. case '(':
  4464. if (extra.tokenize) {
  4465. extra.openParenToken = extra.tokens.length;
  4466. }
  4467. ++index;
  4468. break;
  4469. case '{':
  4470. if (extra.tokenize) {
  4471. extra.openCurlyToken = extra.tokens.length;
  4472. }
  4473. ++index;
  4474. break;
  4475. case '.':
  4476. ++index;
  4477. if (source[index] === '.' && source[index + 1] === '.') {
  4478. // Spread operator: ...
  4479. index += 2;
  4480. str = '...';
  4481. }
  4482. break;
  4483. case ')':
  4484. case ';':
  4485. case ',':
  4486. case '}':
  4487. case '[':
  4488. case ']':
  4489. case ':':
  4490. case '?':
  4491. case '~':
  4492. ++index;
  4493. break;
  4494. default:
  4495. // 4-character punctuator.
  4496. str = source.substr(index, 4);
  4497. if (str === '>>>=') {
  4498. index += 4;
  4499. } else {
  4500. // 3-character punctuators.
  4501. str = str.substr(0, 3);
  4502. if (str === '===' || str === '!==' || str === '>>>' ||
  4503. str === '<<=' || str === '>>=') {
  4504. index += 3;
  4505. } else {
  4506. // 2-character punctuators.
  4507. str = str.substr(0, 2);
  4508. if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
  4509. str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
  4510. str === '++' || str === '--' || str === '<<' || str === '>>' ||
  4511. str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
  4512. str === '<=' || str === '>=' || str === '=>') {
  4513. index += 2;
  4514. } else {
  4515. // 1-character punctuators.
  4516. str = source[index];
  4517. if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
  4518. ++index;
  4519. }
  4520. }
  4521. }
  4522. }
  4523. }
  4524. if (index === token.start) {
  4525. throwUnexpectedToken();
  4526. }
  4527. token.end = index;
  4528. token.value = str;
  4529. return token;
  4530. }
  4531. // 7.8.3 Numeric Literals
  4532. function scanHexLiteral(start) {
  4533. var number = '';
  4534. while (index < length) {
  4535. if (!isHexDigit(source[index])) {
  4536. break;
  4537. }
  4538. number += source[index++];
  4539. }
  4540. if (number.length === 0) {
  4541. throwUnexpectedToken();
  4542. }
  4543. if (isIdentifierStart(source.charCodeAt(index))) {
  4544. throwUnexpectedToken();
  4545. }
  4546. return {
  4547. type: Token.NumericLiteral,
  4548. value: parseInt('0x' + number, 16),
  4549. lineNumber: lineNumber,
  4550. lineStart: lineStart,
  4551. start: start,
  4552. end: index
  4553. };
  4554. }
  4555. function scanBinaryLiteral(start) {
  4556. var ch, number;
  4557. number = '';
  4558. while (index < length) {
  4559. ch = source[index];
  4560. if (ch !== '0' && ch !== '1') {
  4561. break;
  4562. }
  4563. number += source[index++];
  4564. }
  4565. if (number.length === 0) {
  4566. // only 0b or 0B
  4567. throwUnexpectedToken();
  4568. }
  4569. if (index < length) {
  4570. ch = source.charCodeAt(index);
  4571. /* istanbul ignore else */
  4572. if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
  4573. throwUnexpectedToken();
  4574. }
  4575. }
  4576. return {
  4577. type: Token.NumericLiteral,
  4578. value: parseInt(number, 2),
  4579. lineNumber: lineNumber,
  4580. lineStart: lineStart,
  4581. start: start,
  4582. end: index
  4583. };
  4584. }
  4585. function scanOctalLiteral(prefix, start) {
  4586. var number, octal;
  4587. if (isOctalDigit(prefix)) {
  4588. octal = true;
  4589. number = '0' + source[index++];
  4590. } else {
  4591. octal = false;
  4592. ++index;
  4593. number = '';
  4594. }
  4595. while (index < length) {
  4596. if (!isOctalDigit(source[index])) {
  4597. break;
  4598. }
  4599. number += source[index++];
  4600. }
  4601. if (!octal && number.length === 0) {
  4602. // only 0o or 0O
  4603. throwUnexpectedToken();
  4604. }
  4605. if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
  4606. throwUnexpectedToken();
  4607. }
  4608. return {
  4609. type: Token.NumericLiteral,
  4610. value: parseInt(number, 8),
  4611. octal: octal,
  4612. lineNumber: lineNumber,
  4613. lineStart: lineStart,
  4614. start: start,
  4615. end: index
  4616. };
  4617. }
  4618. function isImplicitOctalLiteral() {
  4619. var i, ch;
  4620. // Implicit octal, unless there is a non-octal digit.
  4621. // (Annex B.1.1 on Numeric Literals)
  4622. for (i = index + 1; i < length; ++i) {
  4623. ch = source[i];
  4624. if (ch === '8' || ch === '9') {
  4625. return false;
  4626. }
  4627. if (!isOctalDigit(ch)) {
  4628. return true;
  4629. }
  4630. }
  4631. return true;
  4632. }
  4633. function scanNumericLiteral() {
  4634. var number, start, ch;
  4635. ch = source[index];
  4636. assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
  4637. 'Numeric literal must start with a decimal digit or a decimal point');
  4638. start = index;
  4639. number = '';
  4640. if (ch !== '.') {
  4641. number = source[index++];
  4642. ch = source[index];
  4643. // Hex number starts with '0x'.
  4644. // Octal number starts with '0'.
  4645. // Octal number in ES6 starts with '0o'.
  4646. // Binary number in ES6 starts with '0b'.
  4647. if (number === '0') {
  4648. if (ch === 'x' || ch === 'X') {
  4649. ++index;
  4650. return scanHexLiteral(start);
  4651. }
  4652. if (ch === 'b' || ch === 'B') {
  4653. ++index;
  4654. return scanBinaryLiteral(start);
  4655. }
  4656. if (ch === 'o' || ch === 'O') {
  4657. return scanOctalLiteral(ch, start);
  4658. }
  4659. if (isOctalDigit(ch)) {
  4660. if (isImplicitOctalLiteral()) {
  4661. return scanOctalLiteral(ch, start);
  4662. }
  4663. }
  4664. }
  4665. while (isDecimalDigit(source.charCodeAt(index))) {
  4666. number += source[index++];
  4667. }
  4668. ch = source[index];
  4669. }
  4670. if (ch === '.') {
  4671. number += source[index++];
  4672. while (isDecimalDigit(source.charCodeAt(index))) {
  4673. number += source[index++];
  4674. }
  4675. ch = source[index];
  4676. }
  4677. if (ch === 'e' || ch === 'E') {
  4678. number += source[index++];
  4679. ch = source[index];
  4680. if (ch === '+' || ch === '-') {
  4681. number += source[index++];
  4682. }
  4683. if (isDecimalDigit(source.charCodeAt(index))) {
  4684. while (isDecimalDigit(source.charCodeAt(index))) {
  4685. number += source[index++];
  4686. }
  4687. } else {
  4688. throwUnexpectedToken();
  4689. }
  4690. }
  4691. if (isIdentifierStart(source.charCodeAt(index))) {
  4692. throwUnexpectedToken();
  4693. }
  4694. return {
  4695. type: Token.NumericLiteral,
  4696. value: parseFloat(number),
  4697. lineNumber: lineNumber,
  4698. lineStart: lineStart,
  4699. start: start,
  4700. end: index
  4701. };
  4702. }
  4703. // 7.8.4 String Literals
  4704. function scanStringLiteral() {
  4705. var str = '', quote, start, ch, code, unescaped, restore, octal = false;
  4706. quote = source[index];
  4707. assert((quote === '\'' || quote === '"'),
  4708. 'String literal must starts with a quote');
  4709. start = index;
  4710. ++index;
  4711. while (index < length) {
  4712. ch = source[index++];
  4713. if (ch === quote) {
  4714. quote = '';
  4715. break;
  4716. } else if (ch === '\\') {
  4717. ch = source[index++];
  4718. if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
  4719. switch (ch) {
  4720. case 'u':
  4721. case 'x':
  4722. if (source[index] === '{') {
  4723. ++index;
  4724. str += scanUnicodeCodePointEscape();
  4725. } else {
  4726. restore = index;
  4727. unescaped = scanHexEscape(ch);
  4728. if (unescaped) {
  4729. str += unescaped;
  4730. } else {
  4731. index = restore;
  4732. str += ch;
  4733. }
  4734. }
  4735. break;
  4736. case 'n':
  4737. str += '\n';
  4738. break;
  4739. case 'r':
  4740. str += '\r';
  4741. break;
  4742. case 't':
  4743. str += '\t';
  4744. break;
  4745. case 'b':
  4746. str += '\b';
  4747. break;
  4748. case 'f':
  4749. str += '\f';
  4750. break;
  4751. case 'v':
  4752. str += '\x0B';
  4753. break;
  4754. default:
  4755. if (isOctalDigit(ch)) {
  4756. code = '01234567'.indexOf(ch);
  4757. // \0 is not octal escape sequence
  4758. if (code !== 0) {
  4759. octal = true;
  4760. }
  4761. if (index < length && isOctalDigit(source[index])) {
  4762. octal = true;
  4763. code = code * 8 + '01234567'.indexOf(source[index++]);
  4764. // 3 digits are only allowed when string starts
  4765. // with 0, 1, 2, 3
  4766. if ('0123'.indexOf(ch) >= 0 &&
  4767. index < length &&
  4768. isOctalDigit(source[index])) {
  4769. code = code * 8 + '01234567'.indexOf(source[index++]);
  4770. }
  4771. }
  4772. str += String.fromCharCode(code);
  4773. } else {
  4774. str += ch;
  4775. }
  4776. break;
  4777. }
  4778. } else {
  4779. ++lineNumber;
  4780. if (ch === '\r' && source[index] === '\n') {
  4781. ++index;
  4782. }
  4783. lineStart = index;
  4784. }
  4785. } else if (isLineTerminator(ch.charCodeAt(0))) {
  4786. break;
  4787. } else {
  4788. str += ch;
  4789. }
  4790. }
  4791. if (quote !== '') {
  4792. throwUnexpectedToken();
  4793. }
  4794. return {
  4795. type: Token.StringLiteral,
  4796. value: str,
  4797. octal: octal,
  4798. lineNumber: startLineNumber,
  4799. lineStart: startLineStart,
  4800. start: start,
  4801. end: index
  4802. };
  4803. }
  4804. function testRegExp(pattern, flags) {
  4805. var tmp = pattern;
  4806. if (flags.indexOf('u') >= 0) {
  4807. // Replace each astral symbol and every Unicode code point
  4808. // escape sequence with a single ASCII symbol to avoid throwing on
  4809. // regular expressions that are only valid in combination with the
  4810. // `/u` flag.
  4811. // Note: replacing with the ASCII symbol `x` might cause false
  4812. // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
  4813. // perfectly valid pattern that is equivalent to `[a-b]`, but it
  4814. // would be replaced by `[x-b]` which throws an error.
  4815. tmp = tmp
  4816. .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) {
  4817. if (parseInt($1, 16) <= 0x10FFFF) {
  4818. return 'x';
  4819. }
  4820. throwUnexpectedToken(null, Messages.InvalidRegExp);
  4821. })
  4822. .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
  4823. }
  4824. // First, detect invalid regular expressions.
  4825. try {
  4826. RegExp(tmp);
  4827. } catch (e) {
  4828. throwUnexpectedToken(null, Messages.InvalidRegExp);
  4829. }
  4830. // Return a regular expression object for this pattern-flag pair, or
  4831. // `null` in case the current environment doesn't support the flags it
  4832. // uses.
  4833. try {
  4834. return new RegExp(pattern, flags);
  4835. } catch (exception) {
  4836. return null;
  4837. }
  4838. }
  4839. function scanRegExpBody() {
  4840. var ch, str, classMarker, terminated, body;
  4841. ch = source[index];
  4842. assert(ch === '/', 'Regular expression literal must start with a slash');
  4843. str = source[index++];
  4844. classMarker = false;
  4845. terminated = false;
  4846. while (index < length) {
  4847. ch = source[index++];
  4848. str += ch;
  4849. if (ch === '\\') {
  4850. ch = source[index++];
  4851. // ECMA-262 7.8.5
  4852. if (isLineTerminator(ch.charCodeAt(0))) {
  4853. throwUnexpectedToken(null, Messages.UnterminatedRegExp);
  4854. }
  4855. str += ch;
  4856. } else if (isLineTerminator(ch.charCodeAt(0))) {
  4857. throwUnexpectedToken(null, Messages.UnterminatedRegExp);
  4858. } else if (classMarker) {
  4859. if (ch === ']') {
  4860. classMarker = false;
  4861. }
  4862. } else {
  4863. if (ch === '/') {
  4864. terminated = true;
  4865. break;
  4866. } else if (ch === '[') {
  4867. classMarker = true;
  4868. }
  4869. }
  4870. }
  4871. if (!terminated) {
  4872. throwUnexpectedToken(null, Messages.UnterminatedRegExp);
  4873. }
  4874. // Exclude leading and trailing slash.
  4875. body = str.substr(1, str.length - 2);
  4876. return {
  4877. value: body,
  4878. literal: str
  4879. };
  4880. }
  4881. function scanRegExpFlags() {
  4882. var ch, str, flags, restore;
  4883. str = '';
  4884. flags = '';
  4885. while (index < length) {
  4886. ch = source[index];
  4887. if (!isIdentifierPart(ch.charCodeAt(0))) {
  4888. break;
  4889. }
  4890. ++index;
  4891. if (ch === '\\' && index < length) {
  4892. ch = source[index];
  4893. if (ch === 'u') {
  4894. ++index;
  4895. restore = index;
  4896. ch = scanHexEscape('u');
  4897. if (ch) {
  4898. flags += ch;
  4899. for (str += '\\u'; restore < index; ++restore) {
  4900. str += source[restore];
  4901. }
  4902. } else {
  4903. index = restore;
  4904. flags += 'u';
  4905. str += '\\u';
  4906. }
  4907. tolerateUnexpectedToken();
  4908. } else {
  4909. str += '\\';
  4910. tolerateUnexpectedToken();
  4911. }
  4912. } else {
  4913. flags += ch;
  4914. str += ch;
  4915. }
  4916. }
  4917. return {
  4918. value: flags,
  4919. literal: str
  4920. };
  4921. }
  4922. function scanRegExp() {
  4923. scanning = true;
  4924. var start, body, flags, value;
  4925. lookahead = null;
  4926. skipComment();
  4927. start = index;
  4928. body = scanRegExpBody();
  4929. flags = scanRegExpFlags();
  4930. value = testRegExp(body.value, flags.value);
  4931. scanning = false;
  4932. if (extra.tokenize) {
  4933. return {
  4934. type: Token.RegularExpression,
  4935. value: value,
  4936. regex: {
  4937. pattern: body.value,
  4938. flags: flags.value
  4939. },
  4940. lineNumber: lineNumber,
  4941. lineStart: lineStart,
  4942. start: start,
  4943. end: index
  4944. };
  4945. }
  4946. return {
  4947. literal: body.literal + flags.literal,
  4948. value: value,
  4949. regex: {
  4950. pattern: body.value,
  4951. flags: flags.value
  4952. },
  4953. start: start,
  4954. end: index
  4955. };
  4956. }
  4957. function collectRegex() {
  4958. var pos, loc, regex, token;
  4959. skipComment();
  4960. pos = index;
  4961. loc = {
  4962. start: {
  4963. line: lineNumber,
  4964. column: index - lineStart
  4965. }
  4966. };
  4967. regex = scanRegExp();
  4968. loc.end = {
  4969. line: lineNumber,
  4970. column: index - lineStart
  4971. };
  4972. /* istanbul ignore next */
  4973. if (!extra.tokenize) {
  4974. // Pop the previous token, which is likely '/' or '/='
  4975. if (extra.tokens.length > 0) {
  4976. token = extra.tokens[extra.tokens.length - 1];
  4977. if (token.range[0] === pos && token.type === 'Punctuator') {
  4978. if (token.value === '/' || token.value === '/=') {
  4979. extra.tokens.pop();
  4980. }
  4981. }
  4982. }
  4983. extra.tokens.push({
  4984. type: 'RegularExpression',
  4985. value: regex.literal,
  4986. regex: regex.regex,
  4987. range: [pos, index],
  4988. loc: loc
  4989. });
  4990. }
  4991. return regex;
  4992. }
  4993. function isIdentifierName(token) {
  4994. return token.type === Token.Identifier ||
  4995. token.type === Token.Keyword ||
  4996. token.type === Token.BooleanLiteral ||
  4997. token.type === Token.NullLiteral;
  4998. }
  4999. function advanceSlash() {
  5000. var prevToken,
  5001. checkToken;
  5002. // Using the following algorithm:
  5003. // https://github.com/mozilla/sweet.js/wiki/design
  5004. prevToken = extra.tokens[extra.tokens.length - 1];
  5005. if (!prevToken) {
  5006. // Nothing before that: it cannot be a division.
  5007. return collectRegex();
  5008. }
  5009. if (prevToken.type === 'Punctuator') {
  5010. if (prevToken.value === ']') {
  5011. return scanPunctuator();
  5012. }
  5013. if (prevToken.value === ')') {
  5014. checkToken = extra.tokens[extra.openParenToken - 1];
  5015. if (checkToken &&
  5016. checkToken.type === 'Keyword' &&
  5017. (checkToken.value === 'if' ||
  5018. checkToken.value === 'while' ||
  5019. checkToken.value === 'for' ||
  5020. checkToken.value === 'with')) {
  5021. return collectRegex();
  5022. }
  5023. return scanPunctuator();
  5024. }
  5025. if (prevToken.value === '}') {
  5026. // Dividing a function by anything makes little sense,
  5027. // but we have to check for that.
  5028. if (extra.tokens[extra.openCurlyToken - 3] &&
  5029. extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
  5030. // Anonymous function.
  5031. checkToken = extra.tokens[extra.openCurlyToken - 4];
  5032. if (!checkToken) {
  5033. return scanPunctuator();
  5034. }
  5035. } else if (extra.tokens[extra.openCurlyToken - 4] &&
  5036. extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
  5037. // Named function.
  5038. checkToken = extra.tokens[extra.openCurlyToken - 5];
  5039. if (!checkToken) {
  5040. return collectRegex();
  5041. }
  5042. } else {
  5043. return scanPunctuator();
  5044. }
  5045. // checkToken determines whether the function is
  5046. // a declaration or an expression.
  5047. if (FnExprTokens.indexOf(checkToken.value) >= 0) {
  5048. // It is an expression.
  5049. return scanPunctuator();
  5050. }
  5051. // It is a declaration.
  5052. return collectRegex();
  5053. }
  5054. return collectRegex();
  5055. }
  5056. if (prevToken.type === 'Keyword' && prevToken.value !== 'this') {
  5057. return collectRegex();
  5058. }
  5059. return scanPunctuator();
  5060. }
  5061. function advance() {
  5062. var ch;
  5063. if (index >= length) {
  5064. return {
  5065. type: Token.EOF,
  5066. lineNumber: lineNumber,
  5067. lineStart: lineStart,
  5068. start: index,
  5069. end: index
  5070. };
  5071. }
  5072. ch = source.charCodeAt(index);
  5073. if (isIdentifierStart(ch)) {
  5074. return scanIdentifier();
  5075. }
  5076. // Very common: ( and ) and ;
  5077. if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
  5078. return scanPunctuator();
  5079. }
  5080. // String literal starts with single quote (U+0027) or double quote (U+0022).
  5081. if (ch === 0x27 || ch === 0x22) {
  5082. return scanStringLiteral();
  5083. }
  5084. // Dot (.) U+002E can also start a floating-point number, hence the need
  5085. // to check the next character.
  5086. if (ch === 0x2E) {
  5087. if (isDecimalDigit(source.charCodeAt(index + 1))) {
  5088. return scanNumericLiteral();
  5089. }
  5090. return scanPunctuator();
  5091. }
  5092. if (isDecimalDigit(ch)) {
  5093. return scanNumericLiteral();
  5094. }
  5095. // Slash (/) U+002F can also start a regex.
  5096. if (extra.tokenize && ch === 0x2F) {
  5097. return advanceSlash();
  5098. }
  5099. return scanPunctuator();
  5100. }
  5101. function collectToken() {
  5102. var loc, token, value, entry;
  5103. loc = {
  5104. start: {
  5105. line: lineNumber,
  5106. column: index - lineStart
  5107. }
  5108. };
  5109. token = advance();
  5110. loc.end = {
  5111. line: lineNumber,
  5112. column: index - lineStart
  5113. };
  5114. if (token.type !== Token.EOF) {
  5115. value = source.slice(token.start, token.end);
  5116. entry = {
  5117. type: TokenName[token.type],
  5118. value: value,
  5119. range: [token.start, token.end],
  5120. loc: loc
  5121. };
  5122. if (token.regex) {
  5123. entry.regex = {
  5124. pattern: token.regex.pattern,
  5125. flags: token.regex.flags
  5126. };
  5127. }
  5128. extra.tokens.push(entry);
  5129. }
  5130. return token;
  5131. }
  5132. function lex() {
  5133. var token;
  5134. scanning = true;
  5135. lastIndex = index;
  5136. lastLineNumber = lineNumber;
  5137. lastLineStart = lineStart;
  5138. skipComment();
  5139. token = lookahead;
  5140. startIndex = index;
  5141. startLineNumber = lineNumber;
  5142. startLineStart = lineStart;
  5143. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  5144. scanning = false;
  5145. return token;
  5146. }
  5147. function peek() {
  5148. scanning = true;
  5149. skipComment();
  5150. lastIndex = index;
  5151. lastLineNumber = lineNumber;
  5152. lastLineStart = lineStart;
  5153. startIndex = index;
  5154. startLineNumber = lineNumber;
  5155. startLineStart = lineStart;
  5156. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  5157. scanning = false;
  5158. }
  5159. function Position() {
  5160. this.line = startLineNumber;
  5161. this.column = startIndex - startLineStart;
  5162. }
  5163. function SourceLocation() {
  5164. this.start = new Position();
  5165. this.end = null;
  5166. }
  5167. function WrappingSourceLocation(startToken) {
  5168. this.start = {
  5169. line: startToken.lineNumber,
  5170. column: startToken.start - startToken.lineStart
  5171. };
  5172. this.end = null;
  5173. }
  5174. function Node() {
  5175. if (extra.range) {
  5176. this.range = [startIndex, 0];
  5177. }
  5178. if (extra.loc) {
  5179. this.loc = new SourceLocation();
  5180. }
  5181. }
  5182. function WrappingNode(startToken) {
  5183. if (extra.range) {
  5184. this.range = [startToken.start, 0];
  5185. }
  5186. if (extra.loc) {
  5187. this.loc = new WrappingSourceLocation(startToken);
  5188. }
  5189. }
  5190. WrappingNode.prototype = Node.prototype = {
  5191. processComment: function () {
  5192. var lastChild,
  5193. leadingComments,
  5194. trailingComments,
  5195. bottomRight = extra.bottomRightStack,
  5196. i,
  5197. comment,
  5198. last = bottomRight[bottomRight.length - 1];
  5199. if (this.type === Syntax.Program) {
  5200. if (this.body.length > 0) {
  5201. return;
  5202. }
  5203. }
  5204. if (extra.trailingComments.length > 0) {
  5205. trailingComments = [];
  5206. for (i = extra.trailingComments.length - 1; i >= 0; --i) {
  5207. comment = extra.trailingComments[i];
  5208. if (comment.range[0] >= this.range[1]) {
  5209. trailingComments.unshift(comment);
  5210. extra.trailingComments.splice(i, 1);
  5211. }
  5212. }
  5213. extra.trailingComments = [];
  5214. } else {
  5215. if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) {
  5216. trailingComments = last.trailingComments;
  5217. delete last.trailingComments;
  5218. }
  5219. }
  5220. // Eating the stack.
  5221. if (last) {
  5222. while (last && last.range[0] >= this.range[0]) {
  5223. lastChild = last;
  5224. last = bottomRight.pop();
  5225. }
  5226. }
  5227. if (lastChild) {
  5228. if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= this.range[0]) {
  5229. this.leadingComments = lastChild.leadingComments;
  5230. lastChild.leadingComments = undefined;
  5231. }
  5232. } else if (extra.leadingComments.length > 0) {
  5233. leadingComments = [];
  5234. for (i = extra.leadingComments.length - 1; i >= 0; --i) {
  5235. comment = extra.leadingComments[i];
  5236. if (comment.range[1] <= this.range[0]) {
  5237. leadingComments.unshift(comment);
  5238. extra.leadingComments.splice(i, 1);
  5239. }
  5240. }
  5241. }
  5242. if (leadingComments && leadingComments.length > 0) {
  5243. this.leadingComments = leadingComments;
  5244. }
  5245. if (trailingComments && trailingComments.length > 0) {
  5246. this.trailingComments = trailingComments;
  5247. }
  5248. bottomRight.push(this);
  5249. },
  5250. finish: function () {
  5251. if (extra.range) {
  5252. this.range[1] = lastIndex;
  5253. }
  5254. if (extra.loc) {
  5255. this.loc.end = {
  5256. line: lastLineNumber,
  5257. column: lastIndex - lastLineStart
  5258. };
  5259. if (extra.source) {
  5260. this.loc.source = extra.source;
  5261. }
  5262. }
  5263. if (extra.attachComment) {
  5264. this.processComment();
  5265. }
  5266. },
  5267. finishArrayExpression: function (elements) {
  5268. this.type = Syntax.ArrayExpression;
  5269. this.elements = elements;
  5270. this.finish();
  5271. return this;
  5272. },
  5273. finishArrowFunctionExpression: function (params, defaults, body, expression) {
  5274. this.type = Syntax.ArrowFunctionExpression;
  5275. this.id = null;
  5276. this.params = params;
  5277. this.defaults = defaults;
  5278. this.body = body;
  5279. this.generator = false;
  5280. this.expression = expression;
  5281. this.finish();
  5282. return this;
  5283. },
  5284. finishAssignmentExpression: function (operator, left, right) {
  5285. this.type = Syntax.AssignmentExpression;
  5286. this.operator = operator;
  5287. this.left = left;
  5288. this.right = right;
  5289. this.finish();
  5290. return this;
  5291. },
  5292. finishBinaryExpression: function (operator, left, right) {
  5293. this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression;
  5294. this.operator = operator;
  5295. this.left = left;
  5296. this.right = right;
  5297. this.finish();
  5298. return this;
  5299. },
  5300. finishBlockStatement: function (body) {
  5301. this.type = Syntax.BlockStatement;
  5302. this.body = body;
  5303. this.finish();
  5304. return this;
  5305. },
  5306. finishBreakStatement: function (label) {
  5307. this.type = Syntax.BreakStatement;
  5308. this.label = label;
  5309. this.finish();
  5310. return this;
  5311. },
  5312. finishCallExpression: function (callee, args) {
  5313. this.type = Syntax.CallExpression;
  5314. this.callee = callee;
  5315. this.arguments = args;
  5316. this.finish();
  5317. return this;
  5318. },
  5319. finishCatchClause: function (param, body) {
  5320. this.type = Syntax.CatchClause;
  5321. this.param = param;
  5322. this.body = body;
  5323. this.finish();
  5324. return this;
  5325. },
  5326. finishClassBody: function (body) {
  5327. this.type = Syntax.ClassBody;
  5328. this.body = body;
  5329. this.finish();
  5330. return this;
  5331. },
  5332. finishClassDeclaration: function (id, superClass, body) {
  5333. this.type = Syntax.ClassDeclaration;
  5334. this.id = id;
  5335. this.superClass = superClass;
  5336. this.body = body;
  5337. this.finish();
  5338. return this;
  5339. },
  5340. finishClassExpression: function (id, superClass, body) {
  5341. this.type = Syntax.ClassExpression;
  5342. this.id = id;
  5343. this.superClass = superClass;
  5344. this.body = body;
  5345. this.finish();
  5346. return this;
  5347. },
  5348. finishConditionalExpression: function (test, consequent, alternate) {
  5349. this.type = Syntax.ConditionalExpression;
  5350. this.test = test;
  5351. this.consequent = consequent;
  5352. this.alternate = alternate;
  5353. this.finish();
  5354. return this;
  5355. },
  5356. finishContinueStatement: function (label) {
  5357. this.type = Syntax.ContinueStatement;
  5358. this.label = label;
  5359. this.finish();
  5360. return this;
  5361. },
  5362. finishDebuggerStatement: function () {
  5363. this.type = Syntax.DebuggerStatement;
  5364. this.finish();
  5365. return this;
  5366. },
  5367. finishDoWhileStatement: function (body, test) {
  5368. this.type = Syntax.DoWhileStatement;
  5369. this.body = body;
  5370. this.test = test;
  5371. this.finish();
  5372. return this;
  5373. },
  5374. finishEmptyStatement: function () {
  5375. this.type = Syntax.EmptyStatement;
  5376. this.finish();
  5377. return this;
  5378. },
  5379. finishExpressionStatement: function (expression) {
  5380. this.type = Syntax.ExpressionStatement;
  5381. this.expression = expression;
  5382. this.finish();
  5383. return this;
  5384. },
  5385. finishForStatement: function (init, test, update, body) {
  5386. this.type = Syntax.ForStatement;
  5387. this.init = init;
  5388. this.test = test;
  5389. this.update = update;
  5390. this.body = body;
  5391. this.finish();
  5392. return this;
  5393. },
  5394. finishForInStatement: function (left, right, body) {
  5395. this.type = Syntax.ForInStatement;
  5396. this.left = left;
  5397. this.right = right;
  5398. this.body = body;
  5399. this.each = false;
  5400. this.finish();
  5401. return this;
  5402. },
  5403. finishFunctionDeclaration: function (id, params, defaults, body) {
  5404. this.type = Syntax.FunctionDeclaration;
  5405. this.id = id;
  5406. this.params = params;
  5407. this.defaults = defaults;
  5408. this.body = body;
  5409. this.generator = false;
  5410. this.expression = false;
  5411. this.finish();
  5412. return this;
  5413. },
  5414. finishFunctionExpression: function (id, params, defaults, body) {
  5415. this.type = Syntax.FunctionExpression;
  5416. this.id = id;
  5417. this.params = params;
  5418. this.defaults = defaults;
  5419. this.body = body;
  5420. this.generator = false;
  5421. this.expression = false;
  5422. this.finish();
  5423. return this;
  5424. },
  5425. finishIdentifier: function (name) {
  5426. this.type = Syntax.Identifier;
  5427. this.name = name;
  5428. this.finish();
  5429. return this;
  5430. },
  5431. finishIfStatement: function (test, consequent, alternate) {
  5432. this.type = Syntax.IfStatement;
  5433. this.test = test;
  5434. this.consequent = consequent;
  5435. this.alternate = alternate;
  5436. this.finish();
  5437. return this;
  5438. },
  5439. finishLabeledStatement: function (label, body) {
  5440. this.type = Syntax.LabeledStatement;
  5441. this.label = label;
  5442. this.body = body;
  5443. this.finish();
  5444. return this;
  5445. },
  5446. finishLiteral: function (token) {
  5447. this.type = Syntax.Literal;
  5448. this.value = token.value;
  5449. this.raw = source.slice(token.start, token.end);
  5450. if (token.regex) {
  5451. this.regex = token.regex;
  5452. }
  5453. this.finish();
  5454. return this;
  5455. },
  5456. finishMemberExpression: function (accessor, object, property) {
  5457. this.type = Syntax.MemberExpression;
  5458. this.computed = accessor === '[';
  5459. this.object = object;
  5460. this.property = property;
  5461. this.finish();
  5462. return this;
  5463. },
  5464. finishNewExpression: function (callee, args) {
  5465. this.type = Syntax.NewExpression;
  5466. this.callee = callee;
  5467. this.arguments = args;
  5468. this.finish();
  5469. return this;
  5470. },
  5471. finishObjectExpression: function (properties) {
  5472. this.type = Syntax.ObjectExpression;
  5473. this.properties = properties;
  5474. this.finish();
  5475. return this;
  5476. },
  5477. finishPostfixExpression: function (operator, argument) {
  5478. this.type = Syntax.UpdateExpression;
  5479. this.operator = operator;
  5480. this.argument = argument;
  5481. this.prefix = false;
  5482. this.finish();
  5483. return this;
  5484. },
  5485. finishProgram: function (body) {
  5486. this.type = Syntax.Program;
  5487. this.body = body;
  5488. this.finish();
  5489. return this;
  5490. },
  5491. finishProperty: function (kind, key, computed, value, method, shorthand) {
  5492. this.type = Syntax.Property;
  5493. this.key = key;
  5494. this.computed = computed;
  5495. this.value = value;
  5496. this.kind = kind;
  5497. this.method = method;
  5498. this.shorthand = shorthand;
  5499. this.finish();
  5500. return this;
  5501. },
  5502. finishRestElement: function (argument) {
  5503. this.type = Syntax.RestElement;
  5504. this.argument = argument;
  5505. this.finish();
  5506. return this;
  5507. },
  5508. finishReturnStatement: function (argument) {
  5509. this.type = Syntax.ReturnStatement;
  5510. this.argument = argument;
  5511. this.finish();
  5512. return this;
  5513. },
  5514. finishSequenceExpression: function (expressions) {
  5515. this.type = Syntax.SequenceExpression;
  5516. this.expressions = expressions;
  5517. this.finish();
  5518. return this;
  5519. },
  5520. finishSwitchCase: function (test, consequent) {
  5521. this.type = Syntax.SwitchCase;
  5522. this.test = test;
  5523. this.consequent = consequent;
  5524. this.finish();
  5525. return this;
  5526. },
  5527. finishSwitchStatement: function (discriminant, cases) {
  5528. this.type = Syntax.SwitchStatement;
  5529. this.discriminant = discriminant;
  5530. this.cases = cases;
  5531. this.finish();
  5532. return this;
  5533. },
  5534. finishThisExpression: function () {
  5535. this.type = Syntax.ThisExpression;
  5536. this.finish();
  5537. return this;
  5538. },
  5539. finishThrowStatement: function (argument) {
  5540. this.type = Syntax.ThrowStatement;
  5541. this.argument = argument;
  5542. this.finish();
  5543. return this;
  5544. },
  5545. finishTryStatement: function (block, handler, finalizer) {
  5546. this.type = Syntax.TryStatement;
  5547. this.block = block;
  5548. this.guardedHandlers = [];
  5549. this.handlers = handler ? [ handler ] : [];
  5550. this.handler = handler;
  5551. this.finalizer = finalizer;
  5552. this.finish();
  5553. return this;
  5554. },
  5555. finishUnaryExpression: function (operator, argument) {
  5556. this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression;
  5557. this.operator = operator;
  5558. this.argument = argument;
  5559. this.prefix = true;
  5560. this.finish();
  5561. return this;
  5562. },
  5563. finishVariableDeclaration: function (declarations) {
  5564. this.type = Syntax.VariableDeclaration;
  5565. this.declarations = declarations;
  5566. this.kind = 'var';
  5567. this.finish();
  5568. return this;
  5569. },
  5570. finishLexicalDeclaration: function (declarations, kind) {
  5571. this.type = Syntax.VariableDeclaration;
  5572. this.declarations = declarations;
  5573. this.kind = kind;
  5574. this.finish();
  5575. return this;
  5576. },
  5577. finishVariableDeclarator: function (id, init) {
  5578. this.type = Syntax.VariableDeclarator;
  5579. this.id = id;
  5580. this.init = init;
  5581. this.finish();
  5582. return this;
  5583. },
  5584. finishWhileStatement: function (test, body) {
  5585. this.type = Syntax.WhileStatement;
  5586. this.test = test;
  5587. this.body = body;
  5588. this.finish();
  5589. return this;
  5590. },
  5591. finishWithStatement: function (object, body) {
  5592. this.type = Syntax.WithStatement;
  5593. this.object = object;
  5594. this.body = body;
  5595. this.finish();
  5596. return this;
  5597. }
  5598. };
  5599. function recordError(error) {
  5600. var e, existing;
  5601. for (e = 0; e < extra.errors.length; e++) {
  5602. existing = extra.errors[e];
  5603. // Prevent duplicated error.
  5604. /* istanbul ignore next */
  5605. if (existing.index === error.index && existing.message === error.message) {
  5606. return;
  5607. }
  5608. }
  5609. extra.errors.push(error);
  5610. }
  5611. function createError(line, pos, description) {
  5612. var error = new Error('Line ' + line + ': ' + description);
  5613. error.index = pos;
  5614. error.lineNumber = line;
  5615. error.column = pos - (scanning ? lineStart : lastLineStart) + 1;
  5616. error.description = description;
  5617. return error;
  5618. }
  5619. // Throw an exception
  5620. function throwError(messageFormat) {
  5621. var args, msg;
  5622. args = Array.prototype.slice.call(arguments, 1);
  5623. msg = messageFormat.replace(/%(\d)/g,
  5624. function (whole, idx) {
  5625. assert(idx < args.length, 'Message reference must be in range');
  5626. return args[idx];
  5627. }
  5628. );
  5629. throw createError(lastLineNumber, lastIndex, msg);
  5630. }
  5631. function tolerateError(messageFormat) {
  5632. var args, msg, error;
  5633. args = Array.prototype.slice.call(arguments, 1);
  5634. /* istanbul ignore next */
  5635. msg = messageFormat.replace(/%(\d)/g,
  5636. function (whole, idx) {
  5637. assert(idx < args.length, 'Message reference must be in range');
  5638. return args[idx];
  5639. }
  5640. );
  5641. error = createError(lineNumber, lastIndex, msg);
  5642. if (extra.errors) {
  5643. recordError(error);
  5644. } else {
  5645. throw error;
  5646. }
  5647. }
  5648. // Throw an exception because of the token.
  5649. function unexpectedTokenError(token, message) {
  5650. var msg = message || Messages.UnexpectedToken;
  5651. if (token && !message) {
  5652. msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
  5653. (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
  5654. (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
  5655. (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
  5656. Messages.UnexpectedToken;
  5657. if (token.type === Token.Keyword) {
  5658. if (isFutureReservedWord(token.value)) {
  5659. msg = Messages.UnexpectedReserved;
  5660. } else if (strict && isStrictModeReservedWord(token.value)) {
  5661. msg = Messages.StrictReservedWord;
  5662. }
  5663. }
  5664. }
  5665. msg = msg.replace('%0', token ? token.value : 'ILLEGAL');
  5666. return (token && typeof token.lineNumber === 'number') ?
  5667. createError(token.lineNumber, token.start, msg) :
  5668. createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
  5669. }
  5670. function throwUnexpectedToken(token, message) {
  5671. throw unexpectedTokenError(token, message);
  5672. }
  5673. function tolerateUnexpectedToken(token, message) {
  5674. var error = unexpectedTokenError(token, message);
  5675. if (extra.errors) {
  5676. recordError(error);
  5677. } else {
  5678. throw error;
  5679. }
  5680. }
  5681. // Expect the next token to match the specified punctuator.
  5682. // If not, an exception will be thrown.
  5683. function expect(value) {
  5684. var token = lex();
  5685. if (token.type !== Token.Punctuator || token.value !== value) {
  5686. throwUnexpectedToken(token);
  5687. }
  5688. }
  5689. /**
  5690. * @name expectCommaSeparator
  5691. * @description Quietly expect a comma when in tolerant mode, otherwise delegates
  5692. * to <code>expect(value)</code>
  5693. * @since 2.0
  5694. */
  5695. function expectCommaSeparator() {
  5696. var token;
  5697. if (extra.errors) {
  5698. token = lookahead;
  5699. if (token.type === Token.Punctuator && token.value === ',') {
  5700. lex();
  5701. } else if (token.type === Token.Punctuator && token.value === ';') {
  5702. lex();
  5703. tolerateUnexpectedToken(token);
  5704. } else {
  5705. tolerateUnexpectedToken(token, Messages.UnexpectedToken);
  5706. }
  5707. } else {
  5708. expect(',');
  5709. }
  5710. }
  5711. // Expect the next token to match the specified keyword.
  5712. // If not, an exception will be thrown.
  5713. function expectKeyword(keyword) {
  5714. var token = lex();
  5715. if (token.type !== Token.Keyword || token.value !== keyword) {
  5716. throwUnexpectedToken(token);
  5717. }
  5718. }
  5719. // Return true if the next token matches the specified punctuator.
  5720. function match(value) {
  5721. return lookahead.type === Token.Punctuator && lookahead.value === value;
  5722. }
  5723. // Return true if the next token matches the specified keyword
  5724. function matchKeyword(keyword) {
  5725. return lookahead.type === Token.Keyword && lookahead.value === keyword;
  5726. }
  5727. // Return true if the next token is an assignment operator
  5728. function matchAssign() {
  5729. var op;
  5730. if (lookahead.type !== Token.Punctuator) {
  5731. return false;
  5732. }
  5733. op = lookahead.value;
  5734. return op === '=' ||
  5735. op === '*=' ||
  5736. op === '/=' ||
  5737. op === '%=' ||
  5738. op === '+=' ||
  5739. op === '-=' ||
  5740. op === '<<=' ||
  5741. op === '>>=' ||
  5742. op === '>>>=' ||
  5743. op === '&=' ||
  5744. op === '^=' ||
  5745. op === '|=';
  5746. }
  5747. function consumeSemicolon() {
  5748. // Catch the very common case first: immediately a semicolon (U+003B).
  5749. if (source.charCodeAt(startIndex) === 0x3B || match(';')) {
  5750. lex();
  5751. return;
  5752. }
  5753. if (hasLineTerminator) {
  5754. return;
  5755. }
  5756. // FIXME(ikarienator): this is seemingly an issue in the previous location info convention.
  5757. lastIndex = startIndex;
  5758. lastLineNumber = startLineNumber;
  5759. lastLineStart = startLineStart;
  5760. if (lookahead.type !== Token.EOF && !match('}')) {
  5761. throwUnexpectedToken(lookahead);
  5762. }
  5763. }
  5764. // Return true if provided expression is LeftHandSideExpression
  5765. function isLeftHandSide(expr) {
  5766. return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
  5767. }
  5768. // 11.1.4 Array Initialiser
  5769. function parseArrayInitialiser() {
  5770. var elements = [], node = new Node();
  5771. expect('[');
  5772. while (!match(']')) {
  5773. if (match(',')) {
  5774. lex();
  5775. elements.push(null);
  5776. } else {
  5777. elements.push(parseAssignmentExpression());
  5778. if (!match(']')) {
  5779. expect(',');
  5780. }
  5781. }
  5782. }
  5783. lex();
  5784. return node.finishArrayExpression(elements);
  5785. }
  5786. // 11.1.5 Object Initialiser
  5787. function parsePropertyFunction(node, paramInfo) {
  5788. var previousStrict, body;
  5789. previousStrict = strict;
  5790. body = parseFunctionSourceElements();
  5791. if (strict && paramInfo.firstRestricted) {
  5792. tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message);
  5793. }
  5794. if (strict && paramInfo.stricted) {
  5795. tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message);
  5796. }
  5797. strict = previousStrict;
  5798. return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body);
  5799. }
  5800. function parsePropertyMethodFunction() {
  5801. var params, method, node = new Node();
  5802. params = parseParams();
  5803. method = parsePropertyFunction(node, params);
  5804. return method;
  5805. }
  5806. // This function returns a tuple `[PropertyName, boolean]` where the PropertyName is the key being consumed and the second
  5807. // element indicate whether its a computed PropertyName or a static PropertyName.
  5808. function parseObjectPropertyKey() {
  5809. var token, node = new Node(), expr;
  5810. token = lex();
  5811. // Note: This function is called only from parseObjectProperty(), where
  5812. // EOF and Punctuator tokens are already filtered out.
  5813. switch (token.type) {
  5814. case Token.StringLiteral:
  5815. case Token.NumericLiteral:
  5816. if (strict && token.octal) {
  5817. tolerateUnexpectedToken(token, Messages.StrictOctalLiteral);
  5818. }
  5819. return node.finishLiteral(token);
  5820. case Token.Identifier:
  5821. case Token.BooleanLiteral:
  5822. case Token.NullLiteral:
  5823. case Token.Keyword:
  5824. return node.finishIdentifier(token.value);
  5825. case Token.Punctuator:
  5826. if (token.value === '[') {
  5827. expr = parseAssignmentExpression();
  5828. expect(']');
  5829. return expr;
  5830. }
  5831. break;
  5832. }
  5833. throwUnexpectedToken(token);
  5834. }
  5835. function lookaheadPropertyName() {
  5836. switch (lookahead.type) {
  5837. case Token.Identifier:
  5838. case Token.StringLiteral:
  5839. case Token.BooleanLiteral:
  5840. case Token.NullLiteral:
  5841. case Token.NumericLiteral:
  5842. case Token.Keyword:
  5843. return true;
  5844. case Token.Punctuator:
  5845. return lookahead.value === '[';
  5846. }
  5847. return false;
  5848. }
  5849. // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals,
  5850. // it might be called at a position where there is in fact a short hand identifier pattern or a data property.
  5851. // This can only be determined after we consumed up to the left parentheses.
  5852. //
  5853. // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller
  5854. // is responsible to visit other options.
  5855. function tryParseMethodDefinition(token, key, computed, node) {
  5856. var value, options, methodNode;
  5857. if (token.type === Token.Identifier) {
  5858. // check for `get` and `set`;
  5859. if (token.value === 'get' && lookaheadPropertyName()) {
  5860. computed = match('[');
  5861. key = parseObjectPropertyKey();
  5862. methodNode = new Node();
  5863. expect('(');
  5864. expect(')');
  5865. value = parsePropertyFunction(methodNode, {
  5866. params: [],
  5867. defaults: [],
  5868. stricted: null,
  5869. firstRestricted: null,
  5870. message: null
  5871. });
  5872. return node.finishProperty('get', key, computed, value, false, false);
  5873. } else if (token.value === 'set' && lookaheadPropertyName()) {
  5874. computed = match('[');
  5875. key = parseObjectPropertyKey();
  5876. methodNode = new Node();
  5877. expect('(');
  5878. options = {
  5879. params: [],
  5880. defaultCount: 0,
  5881. defaults: [],
  5882. firstRestricted: null,
  5883. paramSet: {}
  5884. };
  5885. if (match(')')) {
  5886. tolerateUnexpectedToken(lookahead);
  5887. } else {
  5888. parseParam(options);
  5889. if (options.defaultCount === 0) {
  5890. options.defaults = [];
  5891. }
  5892. }
  5893. expect(')');
  5894. value = parsePropertyFunction(methodNode, options);
  5895. return node.finishProperty('set', key, computed, value, false, false);
  5896. }
  5897. }
  5898. if (match('(')) {
  5899. value = parsePropertyMethodFunction();
  5900. return node.finishProperty('init', key, computed, value, true, false);
  5901. }
  5902. // Not a MethodDefinition.
  5903. return null;
  5904. }
  5905. function checkProto(key, computed, hasProto) {
  5906. if (computed === false && (key.type === Syntax.Identifier && key.name === '__proto__' ||
  5907. key.type === Syntax.Literal && key.value === '__proto__')) {
  5908. if (hasProto.value) {
  5909. tolerateError(Messages.DuplicateProtoProperty);
  5910. } else {
  5911. hasProto.value = true;
  5912. }
  5913. }
  5914. }
  5915. function parseObjectProperty(hasProto) {
  5916. var token = lookahead, node = new Node(), computed, key, maybeMethod, value;
  5917. computed = match('[');
  5918. key = parseObjectPropertyKey();
  5919. maybeMethod = tryParseMethodDefinition(token, key, computed, node);
  5920. if (maybeMethod) {
  5921. checkProto(maybeMethod.key, maybeMethod.computed, hasProto);
  5922. // finished
  5923. return maybeMethod;
  5924. }
  5925. // init property or short hand property.
  5926. checkProto(key, computed, hasProto);
  5927. if (match(':')) {
  5928. lex();
  5929. value = parseAssignmentExpression();
  5930. return node.finishProperty('init', key, computed, value, false, false);
  5931. }
  5932. if (token.type === Token.Identifier) {
  5933. return node.finishProperty('init', key, computed, key, false, true);
  5934. }
  5935. throwUnexpectedToken(lookahead);
  5936. }
  5937. function parseObjectInitialiser() {
  5938. var properties = [], hasProto = {value: false}, node = new Node();
  5939. expect('{');
  5940. while (!match('}')) {
  5941. properties.push(parseObjectProperty(hasProto));
  5942. if (!match('}')) {
  5943. expectCommaSeparator();
  5944. }
  5945. }
  5946. expect('}');
  5947. return node.finishObjectExpression(properties);
  5948. }
  5949. // 11.1.6 The Grouping Operator
  5950. function parseGroupExpression() {
  5951. var expr, expressions, startToken, isValidArrowParameter = true;
  5952. expect('(');
  5953. if (match(')')) {
  5954. lex();
  5955. if (!match('=>')) {
  5956. expect('=>');
  5957. }
  5958. return {
  5959. type: PlaceHolders.ArrowParameterPlaceHolder,
  5960. params: []
  5961. };
  5962. }
  5963. startToken = lookahead;
  5964. if (match('...')) {
  5965. expr = parseRestElement();
  5966. expect(')');
  5967. if (!match('=>')) {
  5968. expect('=>');
  5969. }
  5970. return {
  5971. type: PlaceHolders.ArrowParameterPlaceHolder,
  5972. params: [expr]
  5973. };
  5974. }
  5975. if (match('(')) {
  5976. isValidArrowParameter = false;
  5977. }
  5978. expr = parseAssignmentExpression();
  5979. if (match(',')) {
  5980. expressions = [expr];
  5981. while (startIndex < length) {
  5982. if (!match(',')) {
  5983. break;
  5984. }
  5985. lex();
  5986. if (match('...')) {
  5987. if (!isValidArrowParameter) {
  5988. throwUnexpectedToken(lookahead);
  5989. }
  5990. expressions.push(parseRestElement());
  5991. expect(')');
  5992. if (!match('=>')) {
  5993. expect('=>');
  5994. }
  5995. return {
  5996. type: PlaceHolders.ArrowParameterPlaceHolder,
  5997. params: expressions
  5998. };
  5999. } else if (match('(')) {
  6000. isValidArrowParameter = false;
  6001. }
  6002. expressions.push(parseAssignmentExpression());
  6003. }
  6004. expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
  6005. }
  6006. expect(')');
  6007. if (match('=>') && !isValidArrowParameter) {
  6008. throwUnexpectedToken(lookahead);
  6009. }
  6010. return expr;
  6011. }
  6012. // 11.1 Primary Expressions
  6013. function parsePrimaryExpression() {
  6014. var type, token, expr, node;
  6015. if (match('(')) {
  6016. return parseGroupExpression();
  6017. }
  6018. if (match('[')) {
  6019. return parseArrayInitialiser();
  6020. }
  6021. if (match('{')) {
  6022. return parseObjectInitialiser();
  6023. }
  6024. type = lookahead.type;
  6025. node = new Node();
  6026. if (type === Token.Identifier) {
  6027. expr = node.finishIdentifier(lex().value);
  6028. } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
  6029. if (strict && lookahead.octal) {
  6030. tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral);
  6031. }
  6032. expr = node.finishLiteral(lex());
  6033. } else if (type === Token.Keyword) {
  6034. if (matchKeyword('function')) {
  6035. return parseFunctionExpression();
  6036. }
  6037. if (matchKeyword('this')) {
  6038. lex();
  6039. return node.finishThisExpression();
  6040. }
  6041. if (matchKeyword('class')) {
  6042. return parseClassExpression();
  6043. }
  6044. throwUnexpectedToken(lex());
  6045. } else if (type === Token.BooleanLiteral) {
  6046. token = lex();
  6047. token.value = (token.value === 'true');
  6048. expr = node.finishLiteral(token);
  6049. } else if (type === Token.NullLiteral) {
  6050. token = lex();
  6051. token.value = null;
  6052. expr = node.finishLiteral(token);
  6053. } else if (match('/') || match('/=')) {
  6054. index = startIndex;
  6055. if (typeof extra.tokens !== 'undefined') {
  6056. token = collectRegex();
  6057. } else {
  6058. token = scanRegExp();
  6059. }
  6060. lex();
  6061. expr = node.finishLiteral(token);
  6062. } else {
  6063. throwUnexpectedToken(lex());
  6064. }
  6065. return expr;
  6066. }
  6067. // 11.2 Left-Hand-Side Expressions
  6068. function parseArguments() {
  6069. var args = [];
  6070. expect('(');
  6071. if (!match(')')) {
  6072. while (startIndex < length) {
  6073. args.push(parseAssignmentExpression());
  6074. if (match(')')) {
  6075. break;
  6076. }
  6077. expectCommaSeparator();
  6078. }
  6079. }
  6080. expect(')');
  6081. return args;
  6082. }
  6083. function parseNonComputedProperty() {
  6084. var token, node = new Node();
  6085. token = lex();
  6086. if (!isIdentifierName(token)) {
  6087. throwUnexpectedToken(token);
  6088. }
  6089. return node.finishIdentifier(token.value);
  6090. }
  6091. function parseNonComputedMember() {
  6092. expect('.');
  6093. return parseNonComputedProperty();
  6094. }
  6095. function parseComputedMember() {
  6096. var expr;
  6097. expect('[');
  6098. expr = parseExpression();
  6099. expect(']');
  6100. return expr;
  6101. }
  6102. function parseNewExpression() {
  6103. var callee, args, node = new Node();
  6104. expectKeyword('new');
  6105. callee = parseLeftHandSideExpression();
  6106. args = match('(') ? parseArguments() : [];
  6107. return node.finishNewExpression(callee, args);
  6108. }
  6109. function parseLeftHandSideExpressionAllowCall() {
  6110. var expr, args, property, startToken, previousAllowIn = state.allowIn;
  6111. startToken = lookahead;
  6112. state.allowIn = true;
  6113. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  6114. for (;;) {
  6115. if (match('.')) {
  6116. property = parseNonComputedMember();
  6117. expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
  6118. } else if (match('(')) {
  6119. args = parseArguments();
  6120. expr = new WrappingNode(startToken).finishCallExpression(expr, args);
  6121. } else if (match('[')) {
  6122. property = parseComputedMember();
  6123. expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
  6124. } else {
  6125. break;
  6126. }
  6127. }
  6128. state.allowIn = previousAllowIn;
  6129. return expr;
  6130. }
  6131. function parseLeftHandSideExpression() {
  6132. var expr, property, startToken;
  6133. assert(state.allowIn, 'callee of new expression always allow in keyword.');
  6134. startToken = lookahead;
  6135. expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
  6136. for (;;) {
  6137. if (match('[')) {
  6138. property = parseComputedMember();
  6139. expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
  6140. } else if (match('.')) {
  6141. property = parseNonComputedMember();
  6142. expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
  6143. } else {
  6144. break;
  6145. }
  6146. }
  6147. return expr;
  6148. }
  6149. // 11.3 Postfix Expressions
  6150. function parsePostfixExpression() {
  6151. var expr, token, startToken = lookahead;
  6152. expr = parseLeftHandSideExpressionAllowCall();
  6153. if (!hasLineTerminator && lookahead.type === Token.Punctuator) {
  6154. if (match('++') || match('--')) {
  6155. // 11.3.1, 11.3.2
  6156. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  6157. tolerateError(Messages.StrictLHSPostfix);
  6158. }
  6159. if (!isLeftHandSide(expr)) {
  6160. tolerateError(Messages.InvalidLHSInAssignment);
  6161. }
  6162. token = lex();
  6163. expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr);
  6164. }
  6165. }
  6166. return expr;
  6167. }
  6168. // 11.4 Unary Operators
  6169. function parseUnaryExpression() {
  6170. var token, expr, startToken;
  6171. if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
  6172. expr = parsePostfixExpression();
  6173. } else if (match('++') || match('--')) {
  6174. startToken = lookahead;
  6175. token = lex();
  6176. expr = parseUnaryExpression();
  6177. // 11.4.4, 11.4.5
  6178. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  6179. tolerateError(Messages.StrictLHSPrefix);
  6180. }
  6181. if (!isLeftHandSide(expr)) {
  6182. tolerateError(Messages.InvalidLHSInAssignment);
  6183. }
  6184. expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
  6185. } else if (match('+') || match('-') || match('~') || match('!')) {
  6186. startToken = lookahead;
  6187. token = lex();
  6188. expr = parseUnaryExpression();
  6189. expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
  6190. } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
  6191. startToken = lookahead;
  6192. token = lex();
  6193. expr = parseUnaryExpression();
  6194. expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
  6195. if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
  6196. tolerateError(Messages.StrictDelete);
  6197. }
  6198. } else {
  6199. expr = parsePostfixExpression();
  6200. }
  6201. return expr;
  6202. }
  6203. function binaryPrecedence(token, allowIn) {
  6204. var prec = 0;
  6205. if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
  6206. return 0;
  6207. }
  6208. switch (token.value) {
  6209. case '||':
  6210. prec = 1;
  6211. break;
  6212. case '&&':
  6213. prec = 2;
  6214. break;
  6215. case '|':
  6216. prec = 3;
  6217. break;
  6218. case '^':
  6219. prec = 4;
  6220. break;
  6221. case '&':
  6222. prec = 5;
  6223. break;
  6224. case '==':
  6225. case '!=':
  6226. case '===':
  6227. case '!==':
  6228. prec = 6;
  6229. break;
  6230. case '<':
  6231. case '>':
  6232. case '<=':
  6233. case '>=':
  6234. case 'instanceof':
  6235. prec = 7;
  6236. break;
  6237. case 'in':
  6238. prec = allowIn ? 7 : 0;
  6239. break;
  6240. case '<<':
  6241. case '>>':
  6242. case '>>>':
  6243. prec = 8;
  6244. break;
  6245. case '+':
  6246. case '-':
  6247. prec = 9;
  6248. break;
  6249. case '*':
  6250. case '/':
  6251. case '%':
  6252. prec = 11;
  6253. break;
  6254. default:
  6255. break;
  6256. }
  6257. return prec;
  6258. }
  6259. // 11.5 Multiplicative Operators
  6260. // 11.6 Additive Operators
  6261. // 11.7 Bitwise Shift Operators
  6262. // 11.8 Relational Operators
  6263. // 11.9 Equality Operators
  6264. // 11.10 Binary Bitwise Operators
  6265. // 11.11 Binary Logical Operators
  6266. function parseBinaryExpression() {
  6267. var marker, markers, expr, token, prec, stack, right, operator, left, i;
  6268. marker = lookahead;
  6269. left = parseUnaryExpression();
  6270. token = lookahead;
  6271. prec = binaryPrecedence(token, state.allowIn);
  6272. if (prec === 0) {
  6273. return left;
  6274. }
  6275. token.prec = prec;
  6276. lex();
  6277. markers = [marker, lookahead];
  6278. right = parseUnaryExpression();
  6279. stack = [left, token, right];
  6280. while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {
  6281. // Reduce: make a binary expression from the three topmost entries.
  6282. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
  6283. right = stack.pop();
  6284. operator = stack.pop().value;
  6285. left = stack.pop();
  6286. markers.pop();
  6287. expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right);
  6288. stack.push(expr);
  6289. }
  6290. // Shift.
  6291. token = lex();
  6292. token.prec = prec;
  6293. stack.push(token);
  6294. markers.push(lookahead);
  6295. expr = parseUnaryExpression();
  6296. stack.push(expr);
  6297. }
  6298. // Final reduce to clean-up the stack.
  6299. i = stack.length - 1;
  6300. expr = stack[i];
  6301. markers.pop();
  6302. while (i > 1) {
  6303. expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
  6304. i -= 2;
  6305. }
  6306. return expr;
  6307. }
  6308. // 11.12 Conditional Operator
  6309. function parseConditionalExpression() {
  6310. var expr, previousAllowIn, consequent, alternate, startToken;
  6311. startToken = lookahead;
  6312. expr = parseBinaryExpression();
  6313. if (match('?')) {
  6314. lex();
  6315. previousAllowIn = state.allowIn;
  6316. state.allowIn = true;
  6317. consequent = parseAssignmentExpression();
  6318. state.allowIn = previousAllowIn;
  6319. expect(':');
  6320. alternate = parseAssignmentExpression();
  6321. expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
  6322. }
  6323. return expr;
  6324. }
  6325. // [ES6] 14.2 Arrow Function
  6326. function parseConciseBody() {
  6327. if (match('{')) {
  6328. return parseFunctionSourceElements();
  6329. }
  6330. return parseAssignmentExpression();
  6331. }
  6332. function reinterpretAsCoverFormalsList(expr) {
  6333. var i, len, param, params, defaults, defaultCount, options, token;
  6334. defaults = [];
  6335. defaultCount = 0;
  6336. params = [expr];
  6337. switch (expr.type) {
  6338. case Syntax.Identifier:
  6339. case Syntax.AssignmentExpression:
  6340. break;
  6341. case Syntax.SequenceExpression:
  6342. params = expr.expressions;
  6343. break;
  6344. case PlaceHolders.ArrowParameterPlaceHolder:
  6345. params = expr.params;
  6346. break;
  6347. default:
  6348. return null;
  6349. }
  6350. options = {
  6351. paramSet: {}
  6352. };
  6353. for (i = 0, len = params.length; i < len; i += 1) {
  6354. param = params[i];
  6355. if (param.type === Syntax.Identifier) {
  6356. params[i] = param;
  6357. defaults.push(null);
  6358. validateParam(options, param, param.name);
  6359. } else if (param.type === Syntax.RestElement) {
  6360. params[i] = param;
  6361. defaults.push(null);
  6362. validateParam(options, param.argument, param.argument.name);
  6363. } else if (param.type === Syntax.AssignmentExpression) {
  6364. params[i] = param.left;
  6365. defaults.push(param.right);
  6366. ++defaultCount;
  6367. validateParam(options, param.left, param.left.name);
  6368. } else {
  6369. return null;
  6370. }
  6371. }
  6372. if (options.message === Messages.StrictParamDupe) {
  6373. token = strict ? options.stricted : options.firstRestricted;
  6374. throwUnexpectedToken(token, options.message);
  6375. }
  6376. if (defaultCount === 0) {
  6377. defaults = [];
  6378. }
  6379. return {
  6380. params: params,
  6381. defaults: defaults,
  6382. stricted: options.stricted,
  6383. firstRestricted: options.firstRestricted,
  6384. message: options.message
  6385. };
  6386. }
  6387. function parseArrowFunctionExpression(options, node) {
  6388. var previousStrict, body;
  6389. expect('=>');
  6390. previousStrict = strict;
  6391. body = parseConciseBody();
  6392. if (strict && options.firstRestricted) {
  6393. throwUnexpectedToken(options.firstRestricted, options.message);
  6394. }
  6395. if (strict && options.stricted) {
  6396. tolerateUnexpectedToken(options.stricted, options.message);
  6397. }
  6398. strict = previousStrict;
  6399. return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement);
  6400. }
  6401. // 11.13 Assignment Operators
  6402. function parseAssignmentExpression() {
  6403. var token, expr, right, list, startToken;
  6404. startToken = lookahead;
  6405. token = lookahead;
  6406. expr = parseConditionalExpression();
  6407. if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
  6408. list = reinterpretAsCoverFormalsList(expr);
  6409. if (list) {
  6410. return parseArrowFunctionExpression(list, new WrappingNode(startToken));
  6411. }
  6412. }
  6413. if (matchAssign()) {
  6414. // LeftHandSideExpression
  6415. if (!isLeftHandSide(expr)) {
  6416. tolerateError(Messages.InvalidLHSInAssignment);
  6417. }
  6418. // 11.13.1
  6419. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  6420. tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
  6421. }
  6422. token = lex();
  6423. right = parseAssignmentExpression();
  6424. expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
  6425. }
  6426. return expr;
  6427. }
  6428. // 11.14 Comma Operator
  6429. function parseExpression() {
  6430. var expr, startToken = lookahead, expressions;
  6431. expr = parseAssignmentExpression();
  6432. if (match(',')) {
  6433. expressions = [expr];
  6434. while (startIndex < length) {
  6435. if (!match(',')) {
  6436. break;
  6437. }
  6438. lex();
  6439. expressions.push(parseAssignmentExpression());
  6440. }
  6441. expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
  6442. }
  6443. return expr;
  6444. }
  6445. // 12.1 Block
  6446. function parseStatementListItem() {
  6447. if (lookahead.type === Token.Keyword) {
  6448. switch (lookahead.value) {
  6449. case 'const':
  6450. case 'let':
  6451. return parseLexicalDeclaration();
  6452. case 'function':
  6453. return parseFunctionDeclaration(new Node());
  6454. case 'class':
  6455. return parseClassDeclaration();
  6456. }
  6457. }
  6458. return parseStatement();
  6459. }
  6460. function parseStatementList() {
  6461. var list = [];
  6462. while (startIndex < length) {
  6463. if (match('}')) {
  6464. break;
  6465. }
  6466. list.push(parseStatementListItem());
  6467. }
  6468. return list;
  6469. }
  6470. function parseBlock() {
  6471. var block, node = new Node();
  6472. expect('{');
  6473. block = parseStatementList();
  6474. expect('}');
  6475. return node.finishBlockStatement(block);
  6476. }
  6477. // 12.2 Variable Statement
  6478. function parseVariableIdentifier() {
  6479. var token, node = new Node();
  6480. token = lex();
  6481. if (token.type !== Token.Identifier) {
  6482. if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {
  6483. tolerateUnexpectedToken(token, Messages.StrictReservedWord);
  6484. } else {
  6485. throwUnexpectedToken(token);
  6486. }
  6487. }
  6488. return node.finishIdentifier(token.value);
  6489. }
  6490. function parseVariableDeclaration() {
  6491. var init = null, id, node = new Node();
  6492. id = parseVariableIdentifier();
  6493. // 12.2.1
  6494. if (strict && isRestrictedWord(id.name)) {
  6495. tolerateError(Messages.StrictVarName);
  6496. }
  6497. if (match('=')) {
  6498. lex();
  6499. init = parseAssignmentExpression();
  6500. }
  6501. return node.finishVariableDeclarator(id, init);
  6502. }
  6503. function parseVariableDeclarationList() {
  6504. var list = [];
  6505. do {
  6506. list.push(parseVariableDeclaration());
  6507. if (!match(',')) {
  6508. break;
  6509. }
  6510. lex();
  6511. } while (startIndex < length);
  6512. return list;
  6513. }
  6514. function parseVariableStatement(node) {
  6515. var declarations;
  6516. expectKeyword('var');
  6517. declarations = parseVariableDeclarationList();
  6518. consumeSemicolon();
  6519. return node.finishVariableDeclaration(declarations);
  6520. }
  6521. function parseLexicalBinding(kind) {
  6522. var init = null, id, node = new Node();
  6523. id = parseVariableIdentifier();
  6524. // 12.2.1
  6525. if (strict && isRestrictedWord(id.name)) {
  6526. tolerateError(Messages.StrictVarName);
  6527. }
  6528. if (kind === 'const') {
  6529. if (!matchKeyword('in')) {
  6530. expect('=');
  6531. init = parseAssignmentExpression();
  6532. }
  6533. } else if (match('=')) {
  6534. lex();
  6535. init = parseAssignmentExpression();
  6536. }
  6537. return node.finishVariableDeclarator(id, init);
  6538. }
  6539. function parseBindingList(kind) {
  6540. var list = [];
  6541. do {
  6542. list.push(parseLexicalBinding(kind));
  6543. if (!match(',')) {
  6544. break;
  6545. }
  6546. lex();
  6547. } while (startIndex < length);
  6548. return list;
  6549. }
  6550. function parseLexicalDeclaration() {
  6551. var kind, declarations, node = new Node();
  6552. kind = lex().value;
  6553. assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
  6554. declarations = parseBindingList(kind);
  6555. consumeSemicolon();
  6556. return node.finishLexicalDeclaration(declarations, kind);
  6557. }
  6558. function parseRestElement() {
  6559. var param, node = new Node();
  6560. lex();
  6561. if (match('{')) {
  6562. throwError(Messages.ObjectPatternAsRestParameter);
  6563. }
  6564. param = parseVariableIdentifier();
  6565. if (match('=')) {
  6566. throwError(Messages.DefaultRestParameter);
  6567. }
  6568. if (!match(')')) {
  6569. throwError(Messages.ParameterAfterRestParameter);
  6570. }
  6571. return node.finishRestElement(param);
  6572. }
  6573. // 12.3 Empty Statement
  6574. function parseEmptyStatement(node) {
  6575. expect(';');
  6576. return node.finishEmptyStatement();
  6577. }
  6578. // 12.4 Expression Statement
  6579. function parseExpressionStatement(node) {
  6580. var expr = parseExpression();
  6581. consumeSemicolon();
  6582. return node.finishExpressionStatement(expr);
  6583. }
  6584. // 12.5 If statement
  6585. function parseIfStatement(node) {
  6586. var test, consequent, alternate;
  6587. expectKeyword('if');
  6588. expect('(');
  6589. test = parseExpression();
  6590. expect(')');
  6591. consequent = parseStatement();
  6592. if (matchKeyword('else')) {
  6593. lex();
  6594. alternate = parseStatement();
  6595. } else {
  6596. alternate = null;
  6597. }
  6598. return node.finishIfStatement(test, consequent, alternate);
  6599. }
  6600. // 12.6 Iteration Statements
  6601. function parseDoWhileStatement(node) {
  6602. var body, test, oldInIteration;
  6603. expectKeyword('do');
  6604. oldInIteration = state.inIteration;
  6605. state.inIteration = true;
  6606. body = parseStatement();
  6607. state.inIteration = oldInIteration;
  6608. expectKeyword('while');
  6609. expect('(');
  6610. test = parseExpression();
  6611. expect(')');
  6612. if (match(';')) {
  6613. lex();
  6614. }
  6615. return node.finishDoWhileStatement(body, test);
  6616. }
  6617. function parseWhileStatement(node) {
  6618. var test, body, oldInIteration;
  6619. expectKeyword('while');
  6620. expect('(');
  6621. test = parseExpression();
  6622. expect(')');
  6623. oldInIteration = state.inIteration;
  6624. state.inIteration = true;
  6625. body = parseStatement();
  6626. state.inIteration = oldInIteration;
  6627. return node.finishWhileStatement(test, body);
  6628. }
  6629. function parseForStatement(node) {
  6630. var init, test, update, left, right, kind, declarations,
  6631. body, oldInIteration, previousAllowIn = state.allowIn;
  6632. init = test = update = null;
  6633. expectKeyword('for');
  6634. expect('(');
  6635. if (match(';')) {
  6636. lex();
  6637. } else {
  6638. if (matchKeyword('var')) {
  6639. init = new Node();
  6640. lex();
  6641. state.allowIn = false;
  6642. init = init.finishVariableDeclaration(parseVariableDeclarationList());
  6643. state.allowIn = previousAllowIn;
  6644. if (init.declarations.length === 1 && matchKeyword('in')) {
  6645. lex();
  6646. left = init;
  6647. right = parseExpression();
  6648. init = null;
  6649. } else {
  6650. expect(';');
  6651. }
  6652. } else if (matchKeyword('const') || matchKeyword('let')) {
  6653. init = new Node();
  6654. kind = lex().value;
  6655. state.allowIn = false;
  6656. declarations = parseBindingList(kind);
  6657. state.allowIn = previousAllowIn;
  6658. if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) {
  6659. init = init.finishLexicalDeclaration(declarations, kind);
  6660. lex();
  6661. left = init;
  6662. right = parseExpression();
  6663. init = null;
  6664. } else {
  6665. consumeSemicolon();
  6666. init = init.finishLexicalDeclaration(declarations, kind);
  6667. }
  6668. } else {
  6669. state.allowIn = false;
  6670. init = parseExpression();
  6671. state.allowIn = previousAllowIn;
  6672. if (matchKeyword('in')) {
  6673. // LeftHandSideExpression
  6674. if (!isLeftHandSide(init)) {
  6675. tolerateError(Messages.InvalidLHSInForIn);
  6676. }
  6677. lex();
  6678. left = init;
  6679. right = parseExpression();
  6680. init = null;
  6681. } else {
  6682. expect(';');
  6683. }
  6684. }
  6685. }
  6686. if (typeof left === 'undefined') {
  6687. if (!match(';')) {
  6688. test = parseExpression();
  6689. }
  6690. expect(';');
  6691. if (!match(')')) {
  6692. update = parseExpression();
  6693. }
  6694. }
  6695. expect(')');
  6696. oldInIteration = state.inIteration;
  6697. state.inIteration = true;
  6698. body = parseStatement();
  6699. state.inIteration = oldInIteration;
  6700. return (typeof left === 'undefined') ?
  6701. node.finishForStatement(init, test, update, body) :
  6702. node.finishForInStatement(left, right, body);
  6703. }
  6704. // 12.7 The continue statement
  6705. function parseContinueStatement(node) {
  6706. var label = null, key;
  6707. expectKeyword('continue');
  6708. // Optimize the most common form: 'continue;'.
  6709. if (source.charCodeAt(startIndex) === 0x3B) {
  6710. lex();
  6711. if (!state.inIteration) {
  6712. throwError(Messages.IllegalContinue);
  6713. }
  6714. return node.finishContinueStatement(null);
  6715. }
  6716. if (hasLineTerminator) {
  6717. if (!state.inIteration) {
  6718. throwError(Messages.IllegalContinue);
  6719. }
  6720. return node.finishContinueStatement(null);
  6721. }
  6722. if (lookahead.type === Token.Identifier) {
  6723. label = parseVariableIdentifier();
  6724. key = '$' + label.name;
  6725. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  6726. throwError(Messages.UnknownLabel, label.name);
  6727. }
  6728. }
  6729. consumeSemicolon();
  6730. if (label === null && !state.inIteration) {
  6731. throwError(Messages.IllegalContinue);
  6732. }
  6733. return node.finishContinueStatement(label);
  6734. }
  6735. // 12.8 The break statement
  6736. function parseBreakStatement(node) {
  6737. var label = null, key;
  6738. expectKeyword('break');
  6739. // Catch the very common case first: immediately a semicolon (U+003B).
  6740. if (source.charCodeAt(lastIndex) === 0x3B) {
  6741. lex();
  6742. if (!(state.inIteration || state.inSwitch)) {
  6743. throwError(Messages.IllegalBreak);
  6744. }
  6745. return node.finishBreakStatement(null);
  6746. }
  6747. if (hasLineTerminator) {
  6748. if (!(state.inIteration || state.inSwitch)) {
  6749. throwError(Messages.IllegalBreak);
  6750. }
  6751. return node.finishBreakStatement(null);
  6752. }
  6753. if (lookahead.type === Token.Identifier) {
  6754. label = parseVariableIdentifier();
  6755. key = '$' + label.name;
  6756. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  6757. throwError(Messages.UnknownLabel, label.name);
  6758. }
  6759. }
  6760. consumeSemicolon();
  6761. if (label === null && !(state.inIteration || state.inSwitch)) {
  6762. throwError(Messages.IllegalBreak);
  6763. }
  6764. return node.finishBreakStatement(label);
  6765. }
  6766. // 12.9 The return statement
  6767. function parseReturnStatement(node) {
  6768. var argument = null;
  6769. expectKeyword('return');
  6770. if (!state.inFunctionBody) {
  6771. tolerateError(Messages.IllegalReturn);
  6772. }
  6773. // 'return' followed by a space and an identifier is very common.
  6774. if (source.charCodeAt(lastIndex) === 0x20) {
  6775. if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) {
  6776. argument = parseExpression();
  6777. consumeSemicolon();
  6778. return node.finishReturnStatement(argument);
  6779. }
  6780. }
  6781. if (hasLineTerminator) {
  6782. // HACK
  6783. return node.finishReturnStatement(null);
  6784. }
  6785. if (!match(';')) {
  6786. if (!match('}') && lookahead.type !== Token.EOF) {
  6787. argument = parseExpression();
  6788. }
  6789. }
  6790. consumeSemicolon();
  6791. return node.finishReturnStatement(argument);
  6792. }
  6793. // 12.10 The with statement
  6794. function parseWithStatement(node) {
  6795. var object, body;
  6796. if (strict) {
  6797. tolerateError(Messages.StrictModeWith);
  6798. }
  6799. expectKeyword('with');
  6800. expect('(');
  6801. object = parseExpression();
  6802. expect(')');
  6803. body = parseStatement();
  6804. return node.finishWithStatement(object, body);
  6805. }
  6806. // 12.10 The swith statement
  6807. function parseSwitchCase() {
  6808. var test, consequent = [], statement, node = new Node();
  6809. if (matchKeyword('default')) {
  6810. lex();
  6811. test = null;
  6812. } else {
  6813. expectKeyword('case');
  6814. test = parseExpression();
  6815. }
  6816. expect(':');
  6817. while (startIndex < length) {
  6818. if (match('}') || matchKeyword('default') || matchKeyword('case')) {
  6819. break;
  6820. }
  6821. statement = parseStatementListItem();
  6822. consequent.push(statement);
  6823. }
  6824. return node.finishSwitchCase(test, consequent);
  6825. }
  6826. function parseSwitchStatement(node) {
  6827. var discriminant, cases, clause, oldInSwitch, defaultFound;
  6828. expectKeyword('switch');
  6829. expect('(');
  6830. discriminant = parseExpression();
  6831. expect(')');
  6832. expect('{');
  6833. cases = [];
  6834. if (match('}')) {
  6835. lex();
  6836. return node.finishSwitchStatement(discriminant, cases);
  6837. }
  6838. oldInSwitch = state.inSwitch;
  6839. state.inSwitch = true;
  6840. defaultFound = false;
  6841. while (startIndex < length) {
  6842. if (match('}')) {
  6843. break;
  6844. }
  6845. clause = parseSwitchCase();
  6846. if (clause.test === null) {
  6847. if (defaultFound) {
  6848. throwError(Messages.MultipleDefaultsInSwitch);
  6849. }
  6850. defaultFound = true;
  6851. }
  6852. cases.push(clause);
  6853. }
  6854. state.inSwitch = oldInSwitch;
  6855. expect('}');
  6856. return node.finishSwitchStatement(discriminant, cases);
  6857. }
  6858. // 12.13 The throw statement
  6859. function parseThrowStatement(node) {
  6860. var argument;
  6861. expectKeyword('throw');
  6862. if (hasLineTerminator) {
  6863. throwError(Messages.NewlineAfterThrow);
  6864. }
  6865. argument = parseExpression();
  6866. consumeSemicolon();
  6867. return node.finishThrowStatement(argument);
  6868. }
  6869. // 12.14 The try statement
  6870. function parseCatchClause() {
  6871. var param, body, node = new Node();
  6872. expectKeyword('catch');
  6873. expect('(');
  6874. if (match(')')) {
  6875. throwUnexpectedToken(lookahead);
  6876. }
  6877. param = parseVariableIdentifier();
  6878. // 12.14.1
  6879. if (strict && isRestrictedWord(param.name)) {
  6880. tolerateError(Messages.StrictCatchVariable);
  6881. }
  6882. expect(')');
  6883. body = parseBlock();
  6884. return node.finishCatchClause(param, body);
  6885. }
  6886. function parseTryStatement(node) {
  6887. var block, handler = null, finalizer = null;
  6888. expectKeyword('try');
  6889. block = parseBlock();
  6890. if (matchKeyword('catch')) {
  6891. handler = parseCatchClause();
  6892. }
  6893. if (matchKeyword('finally')) {
  6894. lex();
  6895. finalizer = parseBlock();
  6896. }
  6897. if (!handler && !finalizer) {
  6898. throwError(Messages.NoCatchOrFinally);
  6899. }
  6900. return node.finishTryStatement(block, handler, finalizer);
  6901. }
  6902. // 12.15 The debugger statement
  6903. function parseDebuggerStatement(node) {
  6904. expectKeyword('debugger');
  6905. consumeSemicolon();
  6906. return node.finishDebuggerStatement();
  6907. }
  6908. // 12 Statements
  6909. function parseStatement() {
  6910. var type = lookahead.type,
  6911. expr,
  6912. labeledBody,
  6913. key,
  6914. node;
  6915. if (type === Token.EOF) {
  6916. throwUnexpectedToken(lookahead);
  6917. }
  6918. if (type === Token.Punctuator && lookahead.value === '{') {
  6919. return parseBlock();
  6920. }
  6921. node = new Node();
  6922. if (type === Token.Punctuator) {
  6923. switch (lookahead.value) {
  6924. case ';':
  6925. return parseEmptyStatement(node);
  6926. case '(':
  6927. return parseExpressionStatement(node);
  6928. default:
  6929. break;
  6930. }
  6931. } else if (type === Token.Keyword) {
  6932. switch (lookahead.value) {
  6933. case 'break':
  6934. return parseBreakStatement(node);
  6935. case 'continue':
  6936. return parseContinueStatement(node);
  6937. case 'debugger':
  6938. return parseDebuggerStatement(node);
  6939. case 'do':
  6940. return parseDoWhileStatement(node);
  6941. case 'for':
  6942. return parseForStatement(node);
  6943. case 'function':
  6944. return parseFunctionDeclaration(node);
  6945. case 'if':
  6946. return parseIfStatement(node);
  6947. case 'return':
  6948. return parseReturnStatement(node);
  6949. case 'switch':
  6950. return parseSwitchStatement(node);
  6951. case 'throw':
  6952. return parseThrowStatement(node);
  6953. case 'try':
  6954. return parseTryStatement(node);
  6955. case 'var':
  6956. return parseVariableStatement(node);
  6957. case 'while':
  6958. return parseWhileStatement(node);
  6959. case 'with':
  6960. return parseWithStatement(node);
  6961. default:
  6962. break;
  6963. }
  6964. }
  6965. expr = parseExpression();
  6966. // 12.12 Labelled Statements
  6967. if ((expr.type === Syntax.Identifier) && match(':')) {
  6968. lex();
  6969. key = '$' + expr.name;
  6970. if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  6971. throwError(Messages.Redeclaration, 'Label', expr.name);
  6972. }
  6973. state.labelSet[key] = true;
  6974. labeledBody = parseStatement();
  6975. delete state.labelSet[key];
  6976. return node.finishLabeledStatement(expr, labeledBody);
  6977. }
  6978. consumeSemicolon();
  6979. return node.finishExpressionStatement(expr);
  6980. }
  6981. // 13 Function Definition
  6982. function parseFunctionSourceElements() {
  6983. var statement, body = [], token, directive, firstRestricted,
  6984. oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount,
  6985. node = new Node();
  6986. expect('{');
  6987. while (startIndex < length) {
  6988. if (lookahead.type !== Token.StringLiteral) {
  6989. break;
  6990. }
  6991. token = lookahead;
  6992. statement = parseStatementListItem();
  6993. body.push(statement);
  6994. if (statement.expression.type !== Syntax.Literal) {
  6995. // this is not directive
  6996. break;
  6997. }
  6998. directive = source.slice(token.start + 1, token.end - 1);
  6999. if (directive === 'use strict') {
  7000. strict = true;
  7001. if (firstRestricted) {
  7002. tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
  7003. }
  7004. } else {
  7005. if (!firstRestricted && token.octal) {
  7006. firstRestricted = token;
  7007. }
  7008. }
  7009. }
  7010. oldLabelSet = state.labelSet;
  7011. oldInIteration = state.inIteration;
  7012. oldInSwitch = state.inSwitch;
  7013. oldInFunctionBody = state.inFunctionBody;
  7014. oldParenthesisCount = state.parenthesizedCount;
  7015. state.labelSet = {};
  7016. state.inIteration = false;
  7017. state.inSwitch = false;
  7018. state.inFunctionBody = true;
  7019. state.parenthesizedCount = 0;
  7020. while (startIndex < length) {
  7021. if (match('}')) {
  7022. break;
  7023. }
  7024. body.push(parseStatementListItem());
  7025. }
  7026. expect('}');
  7027. state.labelSet = oldLabelSet;
  7028. state.inIteration = oldInIteration;
  7029. state.inSwitch = oldInSwitch;
  7030. state.inFunctionBody = oldInFunctionBody;
  7031. state.parenthesizedCount = oldParenthesisCount;
  7032. return node.finishBlockStatement(body);
  7033. }
  7034. function validateParam(options, param, name) {
  7035. var key = '$' + name;
  7036. if (strict) {
  7037. if (isRestrictedWord(name)) {
  7038. options.stricted = param;
  7039. options.message = Messages.StrictParamName;
  7040. }
  7041. if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  7042. options.stricted = param;
  7043. options.message = Messages.StrictParamDupe;
  7044. }
  7045. } else if (!options.firstRestricted) {
  7046. if (isRestrictedWord(name)) {
  7047. options.firstRestricted = param;
  7048. options.message = Messages.StrictParamName;
  7049. } else if (isStrictModeReservedWord(name)) {
  7050. options.firstRestricted = param;
  7051. options.message = Messages.StrictReservedWord;
  7052. } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  7053. options.firstRestricted = param;
  7054. options.message = Messages.StrictParamDupe;
  7055. }
  7056. }
  7057. options.paramSet[key] = true;
  7058. }
  7059. function parseParam(options) {
  7060. var token, param, def;
  7061. token = lookahead;
  7062. if (token.value === '...') {
  7063. param = parseRestElement();
  7064. validateParam(options, param.argument, param.argument.name);
  7065. options.params.push(param);
  7066. options.defaults.push(null);
  7067. return false;
  7068. }
  7069. param = parseVariableIdentifier();
  7070. validateParam(options, token, token.value);
  7071. if (match('=')) {
  7072. lex();
  7073. def = parseAssignmentExpression();
  7074. ++options.defaultCount;
  7075. }
  7076. options.params.push(param);
  7077. options.defaults.push(def);
  7078. return !match(')');
  7079. }
  7080. function parseParams(firstRestricted) {
  7081. var options;
  7082. options = {
  7083. params: [],
  7084. defaultCount: 0,
  7085. defaults: [],
  7086. firstRestricted: firstRestricted
  7087. };
  7088. expect('(');
  7089. if (!match(')')) {
  7090. options.paramSet = {};
  7091. while (startIndex < length) {
  7092. if (!parseParam(options)) {
  7093. break;
  7094. }
  7095. expect(',');
  7096. }
  7097. }
  7098. expect(')');
  7099. if (options.defaultCount === 0) {
  7100. options.defaults = [];
  7101. }
  7102. return {
  7103. params: options.params,
  7104. defaults: options.defaults,
  7105. stricted: options.stricted,
  7106. firstRestricted: options.firstRestricted,
  7107. message: options.message
  7108. };
  7109. }
  7110. function parseFunctionDeclaration(node) {
  7111. var id, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict;
  7112. expectKeyword('function');
  7113. token = lookahead;
  7114. id = parseVariableIdentifier();
  7115. if (strict) {
  7116. if (isRestrictedWord(token.value)) {
  7117. tolerateUnexpectedToken(token, Messages.StrictFunctionName);
  7118. }
  7119. } else {
  7120. if (isRestrictedWord(token.value)) {
  7121. firstRestricted = token;
  7122. message = Messages.StrictFunctionName;
  7123. } else if (isStrictModeReservedWord(token.value)) {
  7124. firstRestricted = token;
  7125. message = Messages.StrictReservedWord;
  7126. }
  7127. }
  7128. tmp = parseParams(firstRestricted);
  7129. params = tmp.params;
  7130. defaults = tmp.defaults;
  7131. stricted = tmp.stricted;
  7132. firstRestricted = tmp.firstRestricted;
  7133. if (tmp.message) {
  7134. message = tmp.message;
  7135. }
  7136. previousStrict = strict;
  7137. body = parseFunctionSourceElements();
  7138. if (strict && firstRestricted) {
  7139. throwUnexpectedToken(firstRestricted, message);
  7140. }
  7141. if (strict && stricted) {
  7142. tolerateUnexpectedToken(stricted, message);
  7143. }
  7144. strict = previousStrict;
  7145. return node.finishFunctionDeclaration(id, params, defaults, body);
  7146. }
  7147. function parseFunctionExpression() {
  7148. var token, id = null, stricted, firstRestricted, message, tmp,
  7149. params = [], defaults = [], body, previousStrict, node = new Node();
  7150. expectKeyword('function');
  7151. if (!match('(')) {
  7152. token = lookahead;
  7153. id = parseVariableIdentifier();
  7154. if (strict) {
  7155. if (isRestrictedWord(token.value)) {
  7156. tolerateUnexpectedToken(token, Messages.StrictFunctionName);
  7157. }
  7158. } else {
  7159. if (isRestrictedWord(token.value)) {
  7160. firstRestricted = token;
  7161. message = Messages.StrictFunctionName;
  7162. } else if (isStrictModeReservedWord(token.value)) {
  7163. firstRestricted = token;
  7164. message = Messages.StrictReservedWord;
  7165. }
  7166. }
  7167. }
  7168. tmp = parseParams(firstRestricted);
  7169. params = tmp.params;
  7170. defaults = tmp.defaults;
  7171. stricted = tmp.stricted;
  7172. firstRestricted = tmp.firstRestricted;
  7173. if (tmp.message) {
  7174. message = tmp.message;
  7175. }
  7176. previousStrict = strict;
  7177. body = parseFunctionSourceElements();
  7178. if (strict && firstRestricted) {
  7179. throwUnexpectedToken(firstRestricted, message);
  7180. }
  7181. if (strict && stricted) {
  7182. tolerateUnexpectedToken(stricted, message);
  7183. }
  7184. strict = previousStrict;
  7185. return node.finishFunctionExpression(id, params, defaults, body);
  7186. }
  7187. function parseClassBody() {
  7188. var classBody, token, isStatic, hasConstructor = false, body, method, computed, key;
  7189. classBody = new Node();
  7190. expect('{');
  7191. body = [];
  7192. while (!match('}')) {
  7193. if (match(';')) {
  7194. lex();
  7195. } else {
  7196. method = new Node();
  7197. token = lookahead;
  7198. isStatic = false;
  7199. computed = match('[');
  7200. key = parseObjectPropertyKey();
  7201. if (key.name === 'static' && lookaheadPropertyName()) {
  7202. token = lookahead;
  7203. isStatic = true;
  7204. computed = match('[');
  7205. key = parseObjectPropertyKey();
  7206. }
  7207. method = tryParseMethodDefinition(token, key, computed, method);
  7208. if (method) {
  7209. method.static = isStatic;
  7210. if (method.kind === 'init') {
  7211. method.kind = 'method';
  7212. }
  7213. if (!isStatic) {
  7214. if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') {
  7215. if (method.kind !== 'method' || !method.method || method.value.generator) {
  7216. throwUnexpectedToken(token, Messages.ConstructorSpecialMethod);
  7217. }
  7218. if (hasConstructor) {
  7219. throwUnexpectedToken(token, Messages.DuplicateConstructor);
  7220. } else {
  7221. hasConstructor = true;
  7222. }
  7223. method.kind = 'constructor';
  7224. }
  7225. } else {
  7226. if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') {
  7227. throwUnexpectedToken(token, Messages.StaticPrototype);
  7228. }
  7229. }
  7230. method.type = Syntax.MethodDefinition;
  7231. delete method.method;
  7232. delete method.shorthand;
  7233. body.push(method);
  7234. } else {
  7235. throwUnexpectedToken(lookahead);
  7236. }
  7237. }
  7238. }
  7239. lex();
  7240. return classBody.finishClassBody(body);
  7241. }
  7242. function parseClassDeclaration() {
  7243. var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
  7244. strict = true;
  7245. expectKeyword('class');
  7246. id = parseVariableIdentifier();
  7247. if (matchKeyword('extends')) {
  7248. lex();
  7249. superClass = parseLeftHandSideExpressionAllowCall();
  7250. }
  7251. classBody = parseClassBody();
  7252. strict = previousStrict;
  7253. return classNode.finishClassDeclaration(id, superClass, classBody);
  7254. }
  7255. function parseClassExpression() {
  7256. var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
  7257. strict = true;
  7258. expectKeyword('class');
  7259. if (lookahead.type === Token.Identifier) {
  7260. id = parseVariableIdentifier();
  7261. }
  7262. if (matchKeyword('extends')) {
  7263. lex();
  7264. superClass = parseLeftHandSideExpressionAllowCall();
  7265. }
  7266. classBody = parseClassBody();
  7267. strict = previousStrict;
  7268. return classNode.finishClassExpression(id, superClass, classBody);
  7269. }
  7270. // 14 Program
  7271. function parseScriptBody() {
  7272. var statement, body = [], token, directive, firstRestricted;
  7273. while (startIndex < length) {
  7274. token = lookahead;
  7275. if (token.type !== Token.StringLiteral) {
  7276. break;
  7277. }
  7278. statement = parseStatementListItem();
  7279. body.push(statement);
  7280. if (statement.expression.type !== Syntax.Literal) {
  7281. // this is not directive
  7282. break;
  7283. }
  7284. directive = source.slice(token.start + 1, token.end - 1);
  7285. if (directive === 'use strict') {
  7286. strict = true;
  7287. if (firstRestricted) {
  7288. tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
  7289. }
  7290. } else {
  7291. if (!firstRestricted && token.octal) {
  7292. firstRestricted = token;
  7293. }
  7294. }
  7295. }
  7296. while (startIndex < length) {
  7297. statement = parseStatementListItem();
  7298. /* istanbul ignore if */
  7299. if (typeof statement === 'undefined') {
  7300. break;
  7301. }
  7302. body.push(statement);
  7303. }
  7304. return body;
  7305. }
  7306. function parseProgram() {
  7307. var body, node;
  7308. peek();
  7309. node = new Node();
  7310. strict = false;
  7311. body = parseScriptBody();
  7312. return node.finishProgram(body);
  7313. }
  7314. function filterTokenLocation() {
  7315. var i, entry, token, tokens = [];
  7316. for (i = 0; i < extra.tokens.length; ++i) {
  7317. entry = extra.tokens[i];
  7318. token = {
  7319. type: entry.type,
  7320. value: entry.value
  7321. };
  7322. if (entry.regex) {
  7323. token.regex = {
  7324. pattern: entry.regex.pattern,
  7325. flags: entry.regex.flags
  7326. };
  7327. }
  7328. if (extra.range) {
  7329. token.range = entry.range;
  7330. }
  7331. if (extra.loc) {
  7332. token.loc = entry.loc;
  7333. }
  7334. tokens.push(token);
  7335. }
  7336. extra.tokens = tokens;
  7337. }
  7338. function tokenize(code, options) {
  7339. var toString,
  7340. tokens;
  7341. toString = String;
  7342. if (typeof code !== 'string' && !(code instanceof String)) {
  7343. code = toString(code);
  7344. }
  7345. source = code;
  7346. index = 0;
  7347. lineNumber = (source.length > 0) ? 1 : 0;
  7348. lineStart = 0;
  7349. startIndex = index;
  7350. startLineNumber = lineNumber;
  7351. startLineStart = lineStart;
  7352. length = source.length;
  7353. lookahead = null;
  7354. state = {
  7355. allowIn: true,
  7356. labelSet: {},
  7357. inFunctionBody: false,
  7358. inIteration: false,
  7359. inSwitch: false,
  7360. lastCommentStart: -1
  7361. };
  7362. extra = {};
  7363. // Options matching.
  7364. options = options || {};
  7365. // Of course we collect tokens here.
  7366. options.tokens = true;
  7367. extra.tokens = [];
  7368. extra.tokenize = true;
  7369. // The following two fields are necessary to compute the Regex tokens.
  7370. extra.openParenToken = -1;
  7371. extra.openCurlyToken = -1;
  7372. extra.range = (typeof options.range === 'boolean') && options.range;
  7373. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  7374. if (typeof options.comment === 'boolean' && options.comment) {
  7375. extra.comments = [];
  7376. }
  7377. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  7378. extra.errors = [];
  7379. }
  7380. try {
  7381. peek();
  7382. if (lookahead.type === Token.EOF) {
  7383. return extra.tokens;
  7384. }
  7385. lex();
  7386. while (lookahead.type !== Token.EOF) {
  7387. try {
  7388. lex();
  7389. } catch (lexError) {
  7390. if (extra.errors) {
  7391. recordError(lexError);
  7392. // We have to break on the first error
  7393. // to avoid infinite loops.
  7394. break;
  7395. } else {
  7396. throw lexError;
  7397. }
  7398. }
  7399. }
  7400. filterTokenLocation();
  7401. tokens = extra.tokens;
  7402. if (typeof extra.comments !== 'undefined') {
  7403. tokens.comments = extra.comments;
  7404. }
  7405. if (typeof extra.errors !== 'undefined') {
  7406. tokens.errors = extra.errors;
  7407. }
  7408. } catch (e) {
  7409. throw e;
  7410. } finally {
  7411. extra = {};
  7412. }
  7413. return tokens;
  7414. }
  7415. function parse(code, options) {
  7416. var program, toString;
  7417. toString = String;
  7418. if (typeof code !== 'string' && !(code instanceof String)) {
  7419. code = toString(code);
  7420. }
  7421. source = code;
  7422. index = 0;
  7423. lineNumber = (source.length > 0) ? 1 : 0;
  7424. lineStart = 0;
  7425. startIndex = index;
  7426. startLineNumber = lineNumber;
  7427. startLineStart = lineStart;
  7428. length = source.length;
  7429. lookahead = null;
  7430. state = {
  7431. allowIn: true,
  7432. labelSet: {},
  7433. inFunctionBody: false,
  7434. inIteration: false,
  7435. inSwitch: false,
  7436. lastCommentStart: -1
  7437. };
  7438. extra = {};
  7439. if (typeof options !== 'undefined') {
  7440. extra.range = (typeof options.range === 'boolean') && options.range;
  7441. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  7442. extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
  7443. if (extra.loc && options.source !== null && options.source !== undefined) {
  7444. extra.source = toString(options.source);
  7445. }
  7446. if (typeof options.tokens === 'boolean' && options.tokens) {
  7447. extra.tokens = [];
  7448. }
  7449. if (typeof options.comment === 'boolean' && options.comment) {
  7450. extra.comments = [];
  7451. }
  7452. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  7453. extra.errors = [];
  7454. }
  7455. if (extra.attachComment) {
  7456. extra.range = true;
  7457. extra.comments = [];
  7458. extra.bottomRightStack = [];
  7459. extra.trailingComments = [];
  7460. extra.leadingComments = [];
  7461. }
  7462. }
  7463. try {
  7464. program = parseProgram();
  7465. if (typeof extra.comments !== 'undefined') {
  7466. program.comments = extra.comments;
  7467. }
  7468. if (typeof extra.tokens !== 'undefined') {
  7469. filterTokenLocation();
  7470. program.tokens = extra.tokens;
  7471. }
  7472. if (typeof extra.errors !== 'undefined') {
  7473. program.errors = extra.errors;
  7474. }
  7475. } catch (e) {
  7476. throw e;
  7477. } finally {
  7478. extra = {};
  7479. }
  7480. return program;
  7481. }
  7482. // Sync with *.json manifests.
  7483. exports.version = '2.1.0';
  7484. exports.tokenize = tokenize;
  7485. exports.parse = parse;
  7486. // Deep copy.
  7487. /* istanbul ignore next */
  7488. exports.Syntax = (function () {
  7489. var name, types = {};
  7490. if (typeof Object.create === 'function') {
  7491. types = Object.create(null);
  7492. }
  7493. for (name in Syntax) {
  7494. if (Syntax.hasOwnProperty(name)) {
  7495. types[name] = Syntax[name];
  7496. }
  7497. }
  7498. if (typeof Object.freeze === 'function') {
  7499. Object.freeze(types);
  7500. }
  7501. return types;
  7502. }());
  7503. }));
  7504. /* vim: set sw=4 ts=4 et tw=80 : */
  7505. /**
  7506. * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  7507. * Available via the MIT or new BSD license.
  7508. * see: http://github.com/jrburke/requirejs for details
  7509. */
  7510. /*global define, Reflect */
  7511. /*
  7512. * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac),
  7513. * and the recursive nature of esprima can cause it to overflow pretty
  7514. * quickly. So favor it built in Reflect parser:
  7515. * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  7516. */
  7517. define('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) {
  7518. if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') {
  7519. return Reflect;
  7520. } else {
  7521. return esprima;
  7522. }
  7523. });
  7524. define('uglifyjs/consolidator', ["require", "exports", "module", "./parse-js", "./process"], function(require, exports, module) {
  7525. /**
  7526. * @preserve Copyright 2012 Robert Gust-Bardon <http://robert.gust-bardon.org/>.
  7527. * All rights reserved.
  7528. *
  7529. * Redistribution and use in source and binary forms, with or without
  7530. * modification, are permitted provided that the following conditions
  7531. * are met:
  7532. *
  7533. * * Redistributions of source code must retain the above
  7534. * copyright notice, this list of conditions and the following
  7535. * disclaimer.
  7536. *
  7537. * * Redistributions in binary form must reproduce the above
  7538. * copyright notice, this list of conditions and the following
  7539. * disclaimer in the documentation and/or other materials
  7540. * provided with the distribution.
  7541. *
  7542. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
  7543. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  7544. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  7545. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  7546. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  7547. * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  7548. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  7549. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7550. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  7551. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  7552. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  7553. * SUCH DAMAGE.
  7554. */
  7555. /**
  7556. * @fileoverview Enhances <a href="https://github.com/mishoo/UglifyJS/"
  7557. * >UglifyJS</a> with consolidation of null, Boolean, and String values.
  7558. * <p>Also known as aliasing, this feature has been deprecated in <a href=
  7559. * "http://closure-compiler.googlecode.com/">the Closure Compiler</a> since its
  7560. * initial release, where it is unavailable from the <abbr title=
  7561. * "command line interface">CLI</a>. The Closure Compiler allows one to log and
  7562. * influence this process. In contrast, this implementation does not introduce
  7563. * any variable declarations in global code and derives String values from
  7564. * identifier names used as property accessors.</p>
  7565. * <p>Consolidating literals may worsen the data compression ratio when an <a
  7566. * href="http://tools.ietf.org/html/rfc2616#section-3.5">encoding
  7567. * transformation</a> is applied. For instance, <a href=
  7568. * "http://code.jquery.com/jquery-1.7.1.js">jQuery 1.7.1</a> takes 248235 bytes.
  7569. * Building it with <a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">
  7570. * UglifyJS v1.2.5</a> results in 93647 bytes (37.73% of the original) which are
  7571. * then compressed to 33154 bytes (13.36% of the original) using <a href=
  7572. * "http://linux.die.net/man/1/gzip">gzip(1)</a>. Building it with the same
  7573. * version of UglifyJS 1.2.5 patched with the implementation of consolidation
  7574. * results in 80784 bytes (a decrease of 12863 bytes, i.e. 13.74%, in comparison
  7575. * to the aforementioned 93647 bytes) which are then compressed to 34013 bytes
  7576. * (an increase of 859 bytes, i.e. 2.59%, in comparison to the aforementioned
  7577. * 33154 bytes).</p>
  7578. * <p>Written in <a href="http://es5.github.com/#x4.2.2">the strict variant</a>
  7579. * of <a href="http://es5.github.com/">ECMA-262 5.1 Edition</a>. Encoded in <a
  7580. * href="http://tools.ietf.org/html/rfc3629">UTF-8</a>. Follows <a href=
  7581. * "http://google-styleguide.googlecode.com/svn-history/r76/trunk/javascriptguide.xml"
  7582. * >Revision 2.28 of the Google JavaScript Style Guide</a> (except for the
  7583. * discouraged use of the {@code function} tag and the {@code namespace} tag).
  7584. * 100% typed for the <a href=
  7585. * "http://closure-compiler.googlecode.com/files/compiler-20120123.tar.gz"
  7586. * >Closure Compiler Version 1741</a>.</p>
  7587. * <p>Should you find this software useful, please consider <a href=
  7588. * "https://paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JZLW72X8FD4WG"
  7589. * >a donation</a>.</p>
  7590. * @author follow.me@RGustBardon (Robert Gust-Bardon)
  7591. * @supported Tested with:
  7592. * <ul>
  7593. * <li><a href="http://nodejs.org/dist/v0.6.10/">Node v0.6.10</a>,</li>
  7594. * <li><a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">UglifyJS
  7595. * v1.2.5</a>.</li>
  7596. * </ul>
  7597. */
  7598. /*global console:false, exports:true, module:false, require:false */
  7599. /*jshint sub:true */
  7600. /**
  7601. * Consolidates null, Boolean, and String values found inside an <abbr title=
  7602. * "abstract syntax tree">AST</abbr>.
  7603. * @param {!TSyntacticCodeUnit} oAbstractSyntaxTree An array-like object
  7604. * representing an <abbr title="abstract syntax tree">AST</abbr>.
  7605. * @return {!TSyntacticCodeUnit} An array-like object representing an <abbr
  7606. * title="abstract syntax tree">AST</abbr> with its null, Boolean, and
  7607. * String values consolidated.
  7608. */
  7609. // TODO(user) Consolidation of mathematical values found in numeric literals.
  7610. // TODO(user) Unconsolidation.
  7611. // TODO(user) Consolidation of ECMA-262 6th Edition programs.
  7612. // TODO(user) Rewrite in ECMA-262 6th Edition.
  7613. exports['ast_consolidate'] = function(oAbstractSyntaxTree) {
  7614. 'use strict';
  7615. /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,
  7616. latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,
  7617. onevar:true, plusplus:true, regexp:true, undef:true, strict:true,
  7618. sub:false, trailing:true */
  7619. var _,
  7620. /**
  7621. * A record consisting of data about one or more source elements.
  7622. * @constructor
  7623. * @nosideeffects
  7624. */
  7625. TSourceElementsData = function() {
  7626. /**
  7627. * The category of the elements.
  7628. * @type {number}
  7629. * @see ESourceElementCategories
  7630. */
  7631. this.nCategory = ESourceElementCategories.N_OTHER;
  7632. /**
  7633. * The number of occurrences (within the elements) of each primitive
  7634. * value that could be consolidated.
  7635. * @type {!Array.<!Object.<string, number>>}
  7636. */
  7637. this.aCount = [];
  7638. this.aCount[EPrimaryExpressionCategories.N_IDENTIFIER_NAMES] = {};
  7639. this.aCount[EPrimaryExpressionCategories.N_STRING_LITERALS] = {};
  7640. this.aCount[EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS] =
  7641. {};
  7642. /**
  7643. * Identifier names found within the elements.
  7644. * @type {!Array.<string>}
  7645. */
  7646. this.aIdentifiers = [];
  7647. /**
  7648. * Prefixed representation Strings of each primitive value that could be
  7649. * consolidated within the elements.
  7650. * @type {!Array.<string>}
  7651. */
  7652. this.aPrimitiveValues = [];
  7653. },
  7654. /**
  7655. * A record consisting of data about a primitive value that could be
  7656. * consolidated.
  7657. * @constructor
  7658. * @nosideeffects
  7659. */
  7660. TPrimitiveValue = function() {
  7661. /**
  7662. * The difference in the number of terminal symbols between the original
  7663. * source text and the one with the primitive value consolidated. If the
  7664. * difference is positive, the primitive value is considered worthwhile.
  7665. * @type {number}
  7666. */
  7667. this.nSaving = 0;
  7668. /**
  7669. * An identifier name of the variable that will be declared and assigned
  7670. * the primitive value if the primitive value is consolidated.
  7671. * @type {string}
  7672. */
  7673. this.sName = '';
  7674. },
  7675. /**
  7676. * A record consisting of data on what to consolidate within the range of
  7677. * source elements that is currently being considered.
  7678. * @constructor
  7679. * @nosideeffects
  7680. */
  7681. TSolution = function() {
  7682. /**
  7683. * An object whose keys are prefixed representation Strings of each
  7684. * primitive value that could be consolidated within the elements and
  7685. * whose values are corresponding data about those primitive values.
  7686. * @type {!Object.<string, {nSaving: number, sName: string}>}
  7687. * @see TPrimitiveValue
  7688. */
  7689. this.oPrimitiveValues = {};
  7690. /**
  7691. * The difference in the number of terminal symbols between the original
  7692. * source text and the one with all the worthwhile primitive values
  7693. * consolidated.
  7694. * @type {number}
  7695. * @see TPrimitiveValue#nSaving
  7696. */
  7697. this.nSavings = 0;
  7698. },
  7699. /**
  7700. * The processor of <abbr title="abstract syntax tree">AST</abbr>s found
  7701. * in UglifyJS.
  7702. * @namespace
  7703. * @type {!TProcessor}
  7704. */
  7705. oProcessor = (/** @type {!TProcessor} */ require('./process')),
  7706. /**
  7707. * A record consisting of a number of constants that represent the
  7708. * difference in the number of terminal symbols between a source text with
  7709. * a modified syntactic code unit and the original one.
  7710. * @namespace
  7711. * @type {!Object.<string, number>}
  7712. */
  7713. oWeights = {
  7714. /**
  7715. * The difference in the number of punctuators required by the bracket
  7716. * notation and the dot notation.
  7717. * <p><code>'[]'.length - '.'.length</code></p>
  7718. * @const
  7719. * @type {number}
  7720. */
  7721. N_PROPERTY_ACCESSOR: 1,
  7722. /**
  7723. * The number of punctuators required by a variable declaration with an
  7724. * initialiser.
  7725. * <p><code>':'.length + ';'.length</code></p>
  7726. * @const
  7727. * @type {number}
  7728. */
  7729. N_VARIABLE_DECLARATION: 2,
  7730. /**
  7731. * The number of terminal symbols required to introduce a variable
  7732. * statement (excluding its variable declaration list).
  7733. * <p><code>'var '.length</code></p>
  7734. * @const
  7735. * @type {number}
  7736. */
  7737. N_VARIABLE_STATEMENT_AFFIXATION: 4,
  7738. /**
  7739. * The number of terminal symbols needed to enclose source elements
  7740. * within a function call with no argument values to a function with an
  7741. * empty parameter list.
  7742. * <p><code>'(function(){}());'.length</code></p>
  7743. * @const
  7744. * @type {number}
  7745. */
  7746. N_CLOSURE: 17
  7747. },
  7748. /**
  7749. * Categories of primary expressions from which primitive values that
  7750. * could be consolidated are derivable.
  7751. * @namespace
  7752. * @enum {number}
  7753. */
  7754. EPrimaryExpressionCategories = {
  7755. /**
  7756. * Identifier names used as property accessors.
  7757. * @type {number}
  7758. */
  7759. N_IDENTIFIER_NAMES: 0,
  7760. /**
  7761. * String literals.
  7762. * @type {number}
  7763. */
  7764. N_STRING_LITERALS: 1,
  7765. /**
  7766. * Null and Boolean literals.
  7767. * @type {number}
  7768. */
  7769. N_NULL_AND_BOOLEAN_LITERALS: 2
  7770. },
  7771. /**
  7772. * Prefixes of primitive values that could be consolidated.
  7773. * The String values of the prefixes must have same number of characters.
  7774. * The prefixes must not be used in any properties defined in any version
  7775. * of <a href=
  7776. * "http://www.ecma-international.org/publications/standards/Ecma-262.htm"
  7777. * >ECMA-262</a>.
  7778. * @namespace
  7779. * @enum {string}
  7780. */
  7781. EValuePrefixes = {
  7782. /**
  7783. * Identifies String values.
  7784. * @type {string}
  7785. */
  7786. S_STRING: '#S',
  7787. /**
  7788. * Identifies null and Boolean values.
  7789. * @type {string}
  7790. */
  7791. S_SYMBOLIC: '#O'
  7792. },
  7793. /**
  7794. * Categories of source elements in terms of their appropriateness of
  7795. * having their primitive values consolidated.
  7796. * @namespace
  7797. * @enum {number}
  7798. */
  7799. ESourceElementCategories = {
  7800. /**
  7801. * Identifies a source element that includes the <a href=
  7802. * "http://es5.github.com/#x12.10">{@code with}</a> statement.
  7803. * @type {number}
  7804. */
  7805. N_WITH: 0,
  7806. /**
  7807. * Identifies a source element that includes the <a href=
  7808. * "http://es5.github.com/#x15.1.2.1">{@code eval}</a> identifier name.
  7809. * @type {number}
  7810. */
  7811. N_EVAL: 1,
  7812. /**
  7813. * Identifies a source element that must be excluded from the process
  7814. * unless its whole scope is examined.
  7815. * @type {number}
  7816. */
  7817. N_EXCLUDABLE: 2,
  7818. /**
  7819. * Identifies source elements not posing any problems.
  7820. * @type {number}
  7821. */
  7822. N_OTHER: 3
  7823. },
  7824. /**
  7825. * The list of literals (other than the String ones) whose primitive
  7826. * values can be consolidated.
  7827. * @const
  7828. * @type {!Array.<string>}
  7829. */
  7830. A_OTHER_SUBSTITUTABLE_LITERALS = [
  7831. 'null', // The null literal.
  7832. 'false', // The Boolean literal {@code false}.
  7833. 'true' // The Boolean literal {@code true}.
  7834. ];
  7835. (/**
  7836. * Consolidates all worthwhile primitive values in a syntactic code unit.
  7837. * @param {!TSyntacticCodeUnit} oSyntacticCodeUnit An array-like object
  7838. * representing the branch of the abstract syntax tree representing the
  7839. * syntactic code unit along with its scope.
  7840. * @see TPrimitiveValue#nSaving
  7841. */
  7842. function fExamineSyntacticCodeUnit(oSyntacticCodeUnit) {
  7843. var _,
  7844. /**
  7845. * Indicates whether the syntactic code unit represents global code.
  7846. * @type {boolean}
  7847. */
  7848. bIsGlobal = 'toplevel' === oSyntacticCodeUnit[0],
  7849. /**
  7850. * Indicates whether the whole scope is being examined.
  7851. * @type {boolean}
  7852. */
  7853. bIsWhollyExaminable = !bIsGlobal,
  7854. /**
  7855. * An array-like object representing source elements that constitute a
  7856. * syntactic code unit.
  7857. * @type {!TSyntacticCodeUnit}
  7858. */
  7859. oSourceElements,
  7860. /**
  7861. * A record consisting of data about the source element that is
  7862. * currently being examined.
  7863. * @type {!TSourceElementsData}
  7864. */
  7865. oSourceElementData,
  7866. /**
  7867. * The scope of the syntactic code unit.
  7868. * @type {!TScope}
  7869. */
  7870. oScope,
  7871. /**
  7872. * An instance of an object that allows the traversal of an <abbr
  7873. * title="abstract syntax tree">AST</abbr>.
  7874. * @type {!TWalker}
  7875. */
  7876. oWalker,
  7877. /**
  7878. * An object encompassing collections of functions used during the
  7879. * traversal of an <abbr title="abstract syntax tree">AST</abbr>.
  7880. * @namespace
  7881. * @type {!Object.<string, !Object.<string, function(...[*])>>}
  7882. */
  7883. oWalkers = {
  7884. /**
  7885. * A collection of functions used during the surveyance of source
  7886. * elements.
  7887. * @namespace
  7888. * @type {!Object.<string, function(...[*])>}
  7889. */
  7890. oSurveySourceElement: {
  7891. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  7892. /**
  7893. * Classifies the source element as excludable if it does not
  7894. * contain a {@code with} statement or the {@code eval} identifier
  7895. * name. Adds the identifier of the function and its formal
  7896. * parameters to the list of identifier names found.
  7897. * @param {string} sIdentifier The identifier of the function.
  7898. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  7899. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  7900. */
  7901. 'defun': function(
  7902. sIdentifier,
  7903. aFormalParameterList,
  7904. oFunctionBody) {
  7905. fClassifyAsExcludable();
  7906. fAddIdentifier(sIdentifier);
  7907. aFormalParameterList.forEach(fAddIdentifier);
  7908. },
  7909. /**
  7910. * Increments the count of the number of occurrences of the String
  7911. * value that is equivalent to the sequence of terminal symbols
  7912. * that constitute the encountered identifier name.
  7913. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  7914. * MemberExpression.
  7915. * @param {string} sIdentifierName The identifier name used as the
  7916. * property accessor.
  7917. * @return {!Array} The encountered branch of an <abbr title=
  7918. * "abstract syntax tree">AST</abbr> with its nonterminal
  7919. * MemberExpression traversed.
  7920. */
  7921. 'dot': function(oExpression, sIdentifierName) {
  7922. fCountPrimaryExpression(
  7923. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
  7924. EValuePrefixes.S_STRING + sIdentifierName);
  7925. return ['dot', oWalker.walk(oExpression), sIdentifierName];
  7926. },
  7927. /**
  7928. * Adds the optional identifier of the function and its formal
  7929. * parameters to the list of identifier names found.
  7930. * @param {?string} sIdentifier The optional identifier of the
  7931. * function.
  7932. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  7933. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  7934. */
  7935. 'function': function(
  7936. sIdentifier,
  7937. aFormalParameterList,
  7938. oFunctionBody) {
  7939. if ('string' === typeof sIdentifier) {
  7940. fAddIdentifier(sIdentifier);
  7941. }
  7942. aFormalParameterList.forEach(fAddIdentifier);
  7943. },
  7944. /**
  7945. * Either increments the count of the number of occurrences of the
  7946. * encountered null or Boolean value or classifies a source element
  7947. * as containing the {@code eval} identifier name.
  7948. * @param {string} sIdentifier The identifier encountered.
  7949. */
  7950. 'name': function(sIdentifier) {
  7951. if (-1 !== A_OTHER_SUBSTITUTABLE_LITERALS.indexOf(sIdentifier)) {
  7952. fCountPrimaryExpression(
  7953. EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS,
  7954. EValuePrefixes.S_SYMBOLIC + sIdentifier);
  7955. } else {
  7956. if ('eval' === sIdentifier) {
  7957. oSourceElementData.nCategory =
  7958. ESourceElementCategories.N_EVAL;
  7959. }
  7960. fAddIdentifier(sIdentifier);
  7961. }
  7962. },
  7963. /**
  7964. * Classifies the source element as excludable if it does not
  7965. * contain a {@code with} statement or the {@code eval} identifier
  7966. * name.
  7967. * @param {TSyntacticCodeUnit} oExpression The expression whose
  7968. * value is to be returned.
  7969. */
  7970. 'return': function(oExpression) {
  7971. fClassifyAsExcludable();
  7972. },
  7973. /**
  7974. * Increments the count of the number of occurrences of the
  7975. * encountered String value.
  7976. * @param {string} sStringValue The String value of the string
  7977. * literal encountered.
  7978. */
  7979. 'string': function(sStringValue) {
  7980. if (sStringValue.length > 0) {
  7981. fCountPrimaryExpression(
  7982. EPrimaryExpressionCategories.N_STRING_LITERALS,
  7983. EValuePrefixes.S_STRING + sStringValue);
  7984. }
  7985. },
  7986. /**
  7987. * Adds the identifier reserved for an exception to the list of
  7988. * identifier names found.
  7989. * @param {!TSyntacticCodeUnit} oTry A block of code in which an
  7990. * exception can occur.
  7991. * @param {Array} aCatch The identifier reserved for an exception
  7992. * and a block of code to handle the exception.
  7993. * @param {TSyntacticCodeUnit} oFinally An optional block of code
  7994. * to be evaluated regardless of whether an exception occurs.
  7995. */
  7996. 'try': function(oTry, aCatch, oFinally) {
  7997. if (Array.isArray(aCatch)) {
  7998. fAddIdentifier(aCatch[0]);
  7999. }
  8000. },
  8001. /**
  8002. * Classifies the source element as excludable if it does not
  8003. * contain a {@code with} statement or the {@code eval} identifier
  8004. * name. Adds the identifier of each declared variable to the list
  8005. * of identifier names found.
  8006. * @param {!Array.<!Array>} aVariableDeclarationList Variable
  8007. * declarations.
  8008. */
  8009. 'var': function(aVariableDeclarationList) {
  8010. fClassifyAsExcludable();
  8011. aVariableDeclarationList.forEach(fAddVariable);
  8012. },
  8013. /**
  8014. * Classifies a source element as containing the {@code with}
  8015. * statement.
  8016. * @param {!TSyntacticCodeUnit} oExpression An expression whose
  8017. * value is to be converted to a value of type Object and
  8018. * become the binding object of a new object environment
  8019. * record of a new lexical environment in which the statement
  8020. * is to be executed.
  8021. * @param {!TSyntacticCodeUnit} oStatement The statement to be
  8022. * executed in the augmented lexical environment.
  8023. * @return {!Array} An empty array to stop the traversal.
  8024. */
  8025. 'with': function(oExpression, oStatement) {
  8026. oSourceElementData.nCategory = ESourceElementCategories.N_WITH;
  8027. return [];
  8028. }
  8029. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  8030. },
  8031. /**
  8032. * A collection of functions used while looking for nested functions.
  8033. * @namespace
  8034. * @type {!Object.<string, function(...[*])>}
  8035. */
  8036. oExamineFunctions: {
  8037. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  8038. /**
  8039. * Orders an examination of a nested function declaration.
  8040. * @this {!TSyntacticCodeUnit} An array-like object representing
  8041. * the branch of an <abbr title="abstract syntax tree"
  8042. * >AST</abbr> representing the syntactic code unit along with
  8043. * its scope.
  8044. * @return {!Array} An empty array to stop the traversal.
  8045. */
  8046. 'defun': function() {
  8047. fExamineSyntacticCodeUnit(this);
  8048. return [];
  8049. },
  8050. /**
  8051. * Orders an examination of a nested function expression.
  8052. * @this {!TSyntacticCodeUnit} An array-like object representing
  8053. * the branch of an <abbr title="abstract syntax tree"
  8054. * >AST</abbr> representing the syntactic code unit along with
  8055. * its scope.
  8056. * @return {!Array} An empty array to stop the traversal.
  8057. */
  8058. 'function': function() {
  8059. fExamineSyntacticCodeUnit(this);
  8060. return [];
  8061. }
  8062. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  8063. }
  8064. },
  8065. /**
  8066. * Records containing data about source elements.
  8067. * @type {Array.<TSourceElementsData>}
  8068. */
  8069. aSourceElementsData = [],
  8070. /**
  8071. * The index (in the source text order) of the source element
  8072. * immediately following a <a href="http://es5.github.com/#x14.1"
  8073. * >Directive Prologue</a>.
  8074. * @type {number}
  8075. */
  8076. nAfterDirectivePrologue = 0,
  8077. /**
  8078. * The index (in the source text order) of the source element that is
  8079. * currently being considered.
  8080. * @type {number}
  8081. */
  8082. nPosition,
  8083. /**
  8084. * The index (in the source text order) of the source element that is
  8085. * the last element of the range of source elements that is currently
  8086. * being considered.
  8087. * @type {(undefined|number)}
  8088. */
  8089. nTo,
  8090. /**
  8091. * Initiates the traversal of a source element.
  8092. * @param {!TWalker} oWalker An instance of an object that allows the
  8093. * traversal of an abstract syntax tree.
  8094. * @param {!TSyntacticCodeUnit} oSourceElement A source element from
  8095. * which the traversal should commence.
  8096. * @return {function(): !TSyntacticCodeUnit} A function that is able to
  8097. * initiate the traversal from a given source element.
  8098. */
  8099. cContext = function(oWalker, oSourceElement) {
  8100. /**
  8101. * @return {!TSyntacticCodeUnit} A function that is able to
  8102. * initiate the traversal from a given source element.
  8103. */
  8104. var fLambda = function() {
  8105. return oWalker.walk(oSourceElement);
  8106. };
  8107. return fLambda;
  8108. },
  8109. /**
  8110. * Classifies the source element as excludable if it does not
  8111. * contain a {@code with} statement or the {@code eval} identifier
  8112. * name.
  8113. */
  8114. fClassifyAsExcludable = function() {
  8115. if (oSourceElementData.nCategory ===
  8116. ESourceElementCategories.N_OTHER) {
  8117. oSourceElementData.nCategory =
  8118. ESourceElementCategories.N_EXCLUDABLE;
  8119. }
  8120. },
  8121. /**
  8122. * Adds an identifier to the list of identifier names found.
  8123. * @param {string} sIdentifier The identifier to be added.
  8124. */
  8125. fAddIdentifier = function(sIdentifier) {
  8126. if (-1 === oSourceElementData.aIdentifiers.indexOf(sIdentifier)) {
  8127. oSourceElementData.aIdentifiers.push(sIdentifier);
  8128. }
  8129. },
  8130. /**
  8131. * Adds the identifier of a variable to the list of identifier names
  8132. * found.
  8133. * @param {!Array} aVariableDeclaration A variable declaration.
  8134. */
  8135. fAddVariable = function(aVariableDeclaration) {
  8136. fAddIdentifier(/** @type {string} */ aVariableDeclaration[0]);
  8137. },
  8138. /**
  8139. * Increments the count of the number of occurrences of the prefixed
  8140. * String representation attributed to the primary expression.
  8141. * @param {number} nCategory The category of the primary expression.
  8142. * @param {string} sName The prefixed String representation attributed
  8143. * to the primary expression.
  8144. */
  8145. fCountPrimaryExpression = function(nCategory, sName) {
  8146. if (!oSourceElementData.aCount[nCategory].hasOwnProperty(sName)) {
  8147. oSourceElementData.aCount[nCategory][sName] = 0;
  8148. if (-1 === oSourceElementData.aPrimitiveValues.indexOf(sName)) {
  8149. oSourceElementData.aPrimitiveValues.push(sName);
  8150. }
  8151. }
  8152. oSourceElementData.aCount[nCategory][sName] += 1;
  8153. },
  8154. /**
  8155. * Consolidates all worthwhile primitive values in a range of source
  8156. * elements.
  8157. * @param {number} nFrom The index (in the source text order) of the
  8158. * source element that is the first element of the range.
  8159. * @param {number} nTo The index (in the source text order) of the
  8160. * source element that is the last element of the range.
  8161. * @param {boolean} bEnclose Indicates whether the range should be
  8162. * enclosed within a function call with no argument values to a
  8163. * function with an empty parameter list if any primitive values
  8164. * are consolidated.
  8165. * @see TPrimitiveValue#nSaving
  8166. */
  8167. fExamineSourceElements = function(nFrom, nTo, bEnclose) {
  8168. var _,
  8169. /**
  8170. * The index of the last mangled name.
  8171. * @type {number}
  8172. */
  8173. nIndex = oScope.cname,
  8174. /**
  8175. * The index of the source element that is currently being
  8176. * considered.
  8177. * @type {number}
  8178. */
  8179. nPosition,
  8180. /**
  8181. * A collection of functions used during the consolidation of
  8182. * primitive values and identifier names used as property
  8183. * accessors.
  8184. * @namespace
  8185. * @type {!Object.<string, function(...[*])>}
  8186. */
  8187. oWalkersTransformers = {
  8188. /**
  8189. * If the String value that is equivalent to the sequence of
  8190. * terminal symbols that constitute the encountered identifier
  8191. * name is worthwhile, a syntactic conversion from the dot
  8192. * notation to the bracket notation ensues with that sequence
  8193. * being substituted by an identifier name to which the value
  8194. * is assigned.
  8195. * Applies to property accessors that use the dot notation.
  8196. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  8197. * MemberExpression.
  8198. * @param {string} sIdentifierName The identifier name used as
  8199. * the property accessor.
  8200. * @return {!Array} A syntactic code unit that is equivalent to
  8201. * the one encountered.
  8202. * @see TPrimitiveValue#nSaving
  8203. */
  8204. 'dot': function(oExpression, sIdentifierName) {
  8205. /**
  8206. * The prefixed String value that is equivalent to the
  8207. * sequence of terminal symbols that constitute the
  8208. * encountered identifier name.
  8209. * @type {string}
  8210. */
  8211. var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
  8212. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  8213. sPrefixed) &&
  8214. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  8215. ['sub',
  8216. oWalker.walk(oExpression),
  8217. ['name',
  8218. oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
  8219. ['dot', oWalker.walk(oExpression), sIdentifierName];
  8220. },
  8221. /**
  8222. * If the encountered identifier is a null or Boolean literal
  8223. * and its value is worthwhile, the identifier is substituted
  8224. * by an identifier name to which that value is assigned.
  8225. * Applies to identifier names.
  8226. * @param {string} sIdentifier The identifier encountered.
  8227. * @return {!Array} A syntactic code unit that is equivalent to
  8228. * the one encountered.
  8229. * @see TPrimitiveValue#nSaving
  8230. */
  8231. 'name': function(sIdentifier) {
  8232. /**
  8233. * The prefixed representation String of the identifier.
  8234. * @type {string}
  8235. */
  8236. var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
  8237. return [
  8238. 'name',
  8239. oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
  8240. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  8241. oSolutionBest.oPrimitiveValues[sPrefixed].sName :
  8242. sIdentifier
  8243. ];
  8244. },
  8245. /**
  8246. * If the encountered String value is worthwhile, it is
  8247. * substituted by an identifier name to which that value is
  8248. * assigned.
  8249. * Applies to String values.
  8250. * @param {string} sStringValue The String value of the string
  8251. * literal encountered.
  8252. * @return {!Array} A syntactic code unit that is equivalent to
  8253. * the one encountered.
  8254. * @see TPrimitiveValue#nSaving
  8255. */
  8256. 'string': function(sStringValue) {
  8257. /**
  8258. * The prefixed representation String of the primitive value
  8259. * of the literal.
  8260. * @type {string}
  8261. */
  8262. var sPrefixed =
  8263. EValuePrefixes.S_STRING + sStringValue;
  8264. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  8265. sPrefixed) &&
  8266. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  8267. ['name',
  8268. oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
  8269. ['string', sStringValue];
  8270. }
  8271. },
  8272. /**
  8273. * Such data on what to consolidate within the range of source
  8274. * elements that is currently being considered that lead to the
  8275. * greatest known reduction of the number of the terminal symbols
  8276. * in comparison to the original source text.
  8277. * @type {!TSolution}
  8278. */
  8279. oSolutionBest = new TSolution(),
  8280. /**
  8281. * Data representing an ongoing attempt to find a better
  8282. * reduction of the number of the terminal symbols in comparison
  8283. * to the original source text than the best one that is
  8284. * currently known.
  8285. * @type {!TSolution}
  8286. * @see oSolutionBest
  8287. */
  8288. oSolutionCandidate = new TSolution(),
  8289. /**
  8290. * A record consisting of data about the range of source elements
  8291. * that is currently being examined.
  8292. * @type {!TSourceElementsData}
  8293. */
  8294. oSourceElementsData = new TSourceElementsData(),
  8295. /**
  8296. * Variable declarations for each primitive value that is to be
  8297. * consolidated within the elements.
  8298. * @type {!Array.<!Array>}
  8299. */
  8300. aVariableDeclarations = [],
  8301. /**
  8302. * Augments a list with a prefixed representation String.
  8303. * @param {!Array.<string>} aList A list that is to be augmented.
  8304. * @return {function(string)} A function that augments a list
  8305. * with a prefixed representation String.
  8306. */
  8307. cAugmentList = function(aList) {
  8308. /**
  8309. * @param {string} sPrefixed Prefixed representation String of
  8310. * a primitive value that could be consolidated within the
  8311. * elements.
  8312. */
  8313. var fLambda = function(sPrefixed) {
  8314. if (-1 === aList.indexOf(sPrefixed)) {
  8315. aList.push(sPrefixed);
  8316. }
  8317. };
  8318. return fLambda;
  8319. },
  8320. /**
  8321. * Adds the number of occurrences of a primitive value of a given
  8322. * category that could be consolidated in the source element with
  8323. * a given index to the count of occurrences of that primitive
  8324. * value within the range of source elements that is currently
  8325. * being considered.
  8326. * @param {number} nPosition The index (in the source text order)
  8327. * of a source element.
  8328. * @param {number} nCategory The category of the primary
  8329. * expression from which the primitive value is derived.
  8330. * @return {function(string)} A function that performs the
  8331. * addition.
  8332. * @see cAddOccurrencesInCategory
  8333. */
  8334. cAddOccurrences = function(nPosition, nCategory) {
  8335. /**
  8336. * @param {string} sPrefixed The prefixed representation String
  8337. * of a primitive value.
  8338. */
  8339. var fLambda = function(sPrefixed) {
  8340. if (!oSourceElementsData.aCount[nCategory].hasOwnProperty(
  8341. sPrefixed)) {
  8342. oSourceElementsData.aCount[nCategory][sPrefixed] = 0;
  8343. }
  8344. oSourceElementsData.aCount[nCategory][sPrefixed] +=
  8345. aSourceElementsData[nPosition].aCount[nCategory][
  8346. sPrefixed];
  8347. };
  8348. return fLambda;
  8349. },
  8350. /**
  8351. * Adds the number of occurrences of each primitive value of a
  8352. * given category that could be consolidated in the source
  8353. * element with a given index to the count of occurrences of that
  8354. * primitive values within the range of source elements that is
  8355. * currently being considered.
  8356. * @param {number} nPosition The index (in the source text order)
  8357. * of a source element.
  8358. * @return {function(number)} A function that performs the
  8359. * addition.
  8360. * @see fAddOccurrences
  8361. */
  8362. cAddOccurrencesInCategory = function(nPosition) {
  8363. /**
  8364. * @param {number} nCategory The category of the primary
  8365. * expression from which the primitive value is derived.
  8366. */
  8367. var fLambda = function(nCategory) {
  8368. Object.keys(
  8369. aSourceElementsData[nPosition].aCount[nCategory]
  8370. ).forEach(cAddOccurrences(nPosition, nCategory));
  8371. };
  8372. return fLambda;
  8373. },
  8374. /**
  8375. * Adds the number of occurrences of each primitive value that
  8376. * could be consolidated in the source element with a given index
  8377. * to the count of occurrences of that primitive values within
  8378. * the range of source elements that is currently being
  8379. * considered.
  8380. * @param {number} nPosition The index (in the source text order)
  8381. * of a source element.
  8382. */
  8383. fAddOccurrences = function(nPosition) {
  8384. Object.keys(aSourceElementsData[nPosition].aCount).forEach(
  8385. cAddOccurrencesInCategory(nPosition));
  8386. },
  8387. /**
  8388. * Creates a variable declaration for a primitive value if that
  8389. * primitive value is to be consolidated within the elements.
  8390. * @param {string} sPrefixed Prefixed representation String of a
  8391. * primitive value that could be consolidated within the
  8392. * elements.
  8393. * @see aVariableDeclarations
  8394. */
  8395. cAugmentVariableDeclarations = function(sPrefixed) {
  8396. if (oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0) {
  8397. aVariableDeclarations.push([
  8398. oSolutionBest.oPrimitiveValues[sPrefixed].sName,
  8399. [0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC) ?
  8400. 'name' : 'string',
  8401. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length)]
  8402. ]);
  8403. }
  8404. },
  8405. /**
  8406. * Sorts primitive values with regard to the difference in the
  8407. * number of terminal symbols between the original source text
  8408. * and the one with those primitive values consolidated.
  8409. * @param {string} sPrefixed0 The prefixed representation String
  8410. * of the first of the two primitive values that are being
  8411. * compared.
  8412. * @param {string} sPrefixed1 The prefixed representation String
  8413. * of the second of the two primitive values that are being
  8414. * compared.
  8415. * @return {number}
  8416. * <dl>
  8417. * <dt>-1</dt>
  8418. * <dd>if the first primitive value must be placed before
  8419. * the other one,</dd>
  8420. * <dt>0</dt>
  8421. * <dd>if the first primitive value may be placed before
  8422. * the other one,</dd>
  8423. * <dt>1</dt>
  8424. * <dd>if the first primitive value must not be placed
  8425. * before the other one.</dd>
  8426. * </dl>
  8427. * @see TSolution.oPrimitiveValues
  8428. */
  8429. cSortPrimitiveValues = function(sPrefixed0, sPrefixed1) {
  8430. /**
  8431. * The difference between:
  8432. * <ol>
  8433. * <li>the difference in the number of terminal symbols
  8434. * between the original source text and the one with the
  8435. * first primitive value consolidated, and</li>
  8436. * <li>the difference in the number of terminal symbols
  8437. * between the original source text and the one with the
  8438. * second primitive value consolidated.</li>
  8439. * </ol>
  8440. * @type {number}
  8441. */
  8442. var nDifference =
  8443. oSolutionCandidate.oPrimitiveValues[sPrefixed0].nSaving -
  8444. oSolutionCandidate.oPrimitiveValues[sPrefixed1].nSaving;
  8445. return nDifference > 0 ? -1 : nDifference < 0 ? 1 : 0;
  8446. },
  8447. /**
  8448. * Assigns an identifier name to a primitive value and calculates
  8449. * whether instances of that primitive value are worth
  8450. * consolidating.
  8451. * @param {string} sPrefixed The prefixed representation String
  8452. * of a primitive value that is being evaluated.
  8453. */
  8454. fEvaluatePrimitiveValue = function(sPrefixed) {
  8455. var _,
  8456. /**
  8457. * The index of the last mangled name.
  8458. * @type {number}
  8459. */
  8460. nIndex,
  8461. /**
  8462. * The representation String of the primitive value that is
  8463. * being evaluated.
  8464. * @type {string}
  8465. */
  8466. sName =
  8467. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length),
  8468. /**
  8469. * The number of source characters taken up by the
  8470. * representation String of the primitive value that is
  8471. * being evaluated.
  8472. * @type {number}
  8473. */
  8474. nLengthOriginal = sName.length,
  8475. /**
  8476. * The number of source characters taken up by the
  8477. * identifier name that could substitute the primitive
  8478. * value that is being evaluated.
  8479. * substituted.
  8480. * @type {number}
  8481. */
  8482. nLengthSubstitution,
  8483. /**
  8484. * The number of source characters taken up by by the
  8485. * representation String of the primitive value that is
  8486. * being evaluated when it is represented by a string
  8487. * literal.
  8488. * @type {number}
  8489. */
  8490. nLengthString = oProcessor.make_string(sName).length;
  8491. oSolutionCandidate.oPrimitiveValues[sPrefixed] =
  8492. new TPrimitiveValue();
  8493. do { // Find an identifier unused in this or any nested scope.
  8494. nIndex = oScope.cname;
  8495. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName =
  8496. oScope.next_mangled();
  8497. } while (-1 !== oSourceElementsData.aIdentifiers.indexOf(
  8498. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName));
  8499. nLengthSubstitution = oSolutionCandidate.oPrimitiveValues[
  8500. sPrefixed].sName.length;
  8501. if (0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC)) {
  8502. // foo:null, or foo:null;
  8503. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  8504. nLengthSubstitution + nLengthOriginal +
  8505. oWeights.N_VARIABLE_DECLARATION;
  8506. // null vs foo
  8507. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  8508. oSourceElementsData.aCount[
  8509. EPrimaryExpressionCategories.
  8510. N_NULL_AND_BOOLEAN_LITERALS][sPrefixed] *
  8511. (nLengthOriginal - nLengthSubstitution);
  8512. } else {
  8513. // foo:'fromCharCode';
  8514. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  8515. nLengthSubstitution + nLengthString +
  8516. oWeights.N_VARIABLE_DECLARATION;
  8517. // .fromCharCode vs [foo]
  8518. if (oSourceElementsData.aCount[
  8519. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  8520. ].hasOwnProperty(sPrefixed)) {
  8521. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  8522. oSourceElementsData.aCount[
  8523. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  8524. ][sPrefixed] *
  8525. (nLengthOriginal - nLengthSubstitution -
  8526. oWeights.N_PROPERTY_ACCESSOR);
  8527. }
  8528. // 'fromCharCode' vs foo
  8529. if (oSourceElementsData.aCount[
  8530. EPrimaryExpressionCategories.N_STRING_LITERALS
  8531. ].hasOwnProperty(sPrefixed)) {
  8532. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  8533. oSourceElementsData.aCount[
  8534. EPrimaryExpressionCategories.N_STRING_LITERALS
  8535. ][sPrefixed] *
  8536. (nLengthString - nLengthSubstitution);
  8537. }
  8538. }
  8539. if (oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving >
  8540. 0) {
  8541. oSolutionCandidate.nSavings +=
  8542. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving;
  8543. } else {
  8544. oScope.cname = nIndex; // Free the identifier name.
  8545. }
  8546. },
  8547. /**
  8548. * Adds a variable declaration to an existing variable statement.
  8549. * @param {!Array} aVariableDeclaration A variable declaration
  8550. * with an initialiser.
  8551. */
  8552. cAddVariableDeclaration = function(aVariableDeclaration) {
  8553. (/** @type {!Array} */ oSourceElements[nFrom][1]).unshift(
  8554. aVariableDeclaration);
  8555. };
  8556. if (nFrom > nTo) {
  8557. return;
  8558. }
  8559. // If the range is a closure, reuse the closure.
  8560. if (nFrom === nTo &&
  8561. 'stat' === oSourceElements[nFrom][0] &&
  8562. 'call' === oSourceElements[nFrom][1][0] &&
  8563. 'function' === oSourceElements[nFrom][1][1][0]) {
  8564. fExamineSyntacticCodeUnit(oSourceElements[nFrom][1][1]);
  8565. return;
  8566. }
  8567. // Create a list of all derived primitive values within the range.
  8568. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  8569. aSourceElementsData[nPosition].aPrimitiveValues.forEach(
  8570. cAugmentList(oSourceElementsData.aPrimitiveValues));
  8571. }
  8572. if (0 === oSourceElementsData.aPrimitiveValues.length) {
  8573. return;
  8574. }
  8575. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  8576. // Add the number of occurrences to the total count.
  8577. fAddOccurrences(nPosition);
  8578. // Add identifiers of this or any nested scope to the list.
  8579. aSourceElementsData[nPosition].aIdentifiers.forEach(
  8580. cAugmentList(oSourceElementsData.aIdentifiers));
  8581. }
  8582. // Distribute identifier names among derived primitive values.
  8583. do { // If there was any progress, find a better distribution.
  8584. oSolutionBest = oSolutionCandidate;
  8585. if (Object.keys(oSolutionCandidate.oPrimitiveValues).length > 0) {
  8586. // Sort primitive values descending by their worthwhileness.
  8587. oSourceElementsData.aPrimitiveValues.sort(cSortPrimitiveValues);
  8588. }
  8589. oSolutionCandidate = new TSolution();
  8590. oSourceElementsData.aPrimitiveValues.forEach(
  8591. fEvaluatePrimitiveValue);
  8592. oScope.cname = nIndex;
  8593. } while (oSolutionCandidate.nSavings > oSolutionBest.nSavings);
  8594. // Take the necessity of adding a variable statement into account.
  8595. if ('var' !== oSourceElements[nFrom][0]) {
  8596. oSolutionBest.nSavings -= oWeights.N_VARIABLE_STATEMENT_AFFIXATION;
  8597. }
  8598. if (bEnclose) {
  8599. // Take the necessity of forming a closure into account.
  8600. oSolutionBest.nSavings -= oWeights.N_CLOSURE;
  8601. }
  8602. if (oSolutionBest.nSavings > 0) {
  8603. // Create variable declarations suitable for UglifyJS.
  8604. Object.keys(oSolutionBest.oPrimitiveValues).forEach(
  8605. cAugmentVariableDeclarations);
  8606. // Rewrite expressions that contain worthwhile primitive values.
  8607. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  8608. oWalker = oProcessor.ast_walker();
  8609. oSourceElements[nPosition] =
  8610. oWalker.with_walkers(
  8611. oWalkersTransformers,
  8612. cContext(oWalker, oSourceElements[nPosition]));
  8613. }
  8614. if ('var' === oSourceElements[nFrom][0]) { // Reuse the statement.
  8615. (/** @type {!Array.<!Array>} */ aVariableDeclarations.reverse(
  8616. )).forEach(cAddVariableDeclaration);
  8617. } else { // Add a variable statement.
  8618. Array.prototype.splice.call(
  8619. oSourceElements,
  8620. nFrom,
  8621. 0,
  8622. ['var', aVariableDeclarations]);
  8623. nTo += 1;
  8624. }
  8625. if (bEnclose) {
  8626. // Add a closure.
  8627. Array.prototype.splice.call(
  8628. oSourceElements,
  8629. nFrom,
  8630. 0,
  8631. ['stat', ['call', ['function', null, [], []], []]]);
  8632. // Copy source elements into the closure.
  8633. for (nPosition = nTo + 1; nPosition > nFrom; nPosition -= 1) {
  8634. Array.prototype.unshift.call(
  8635. oSourceElements[nFrom][1][1][3],
  8636. oSourceElements[nPosition]);
  8637. }
  8638. // Remove source elements outside the closure.
  8639. Array.prototype.splice.call(
  8640. oSourceElements,
  8641. nFrom + 1,
  8642. nTo - nFrom + 1);
  8643. }
  8644. }
  8645. if (bEnclose) {
  8646. // Restore the availability of identifier names.
  8647. oScope.cname = nIndex;
  8648. }
  8649. };
  8650. oSourceElements = (/** @type {!TSyntacticCodeUnit} */
  8651. oSyntacticCodeUnit[bIsGlobal ? 1 : 3]);
  8652. if (0 === oSourceElements.length) {
  8653. return;
  8654. }
  8655. oScope = bIsGlobal ? oSyntacticCodeUnit.scope : oSourceElements.scope;
  8656. // Skip a Directive Prologue.
  8657. while (nAfterDirectivePrologue < oSourceElements.length &&
  8658. 'directive' === oSourceElements[nAfterDirectivePrologue][0]) {
  8659. nAfterDirectivePrologue += 1;
  8660. aSourceElementsData.push(null);
  8661. }
  8662. if (oSourceElements.length === nAfterDirectivePrologue) {
  8663. return;
  8664. }
  8665. for (nPosition = nAfterDirectivePrologue;
  8666. nPosition < oSourceElements.length;
  8667. nPosition += 1) {
  8668. oSourceElementData = new TSourceElementsData();
  8669. oWalker = oProcessor.ast_walker();
  8670. // Classify a source element.
  8671. // Find its derived primitive values and count their occurrences.
  8672. // Find all identifiers used (including nested scopes).
  8673. oWalker.with_walkers(
  8674. oWalkers.oSurveySourceElement,
  8675. cContext(oWalker, oSourceElements[nPosition]));
  8676. // Establish whether the scope is still wholly examinable.
  8677. bIsWhollyExaminable = bIsWhollyExaminable &&
  8678. ESourceElementCategories.N_WITH !== oSourceElementData.nCategory &&
  8679. ESourceElementCategories.N_EVAL !== oSourceElementData.nCategory;
  8680. aSourceElementsData.push(oSourceElementData);
  8681. }
  8682. if (bIsWhollyExaminable) { // Examine the whole scope.
  8683. fExamineSourceElements(
  8684. nAfterDirectivePrologue,
  8685. oSourceElements.length - 1,
  8686. false);
  8687. } else { // Examine unexcluded ranges of source elements.
  8688. for (nPosition = oSourceElements.length - 1;
  8689. nPosition >= nAfterDirectivePrologue;
  8690. nPosition -= 1) {
  8691. oSourceElementData = (/** @type {!TSourceElementsData} */
  8692. aSourceElementsData[nPosition]);
  8693. if (ESourceElementCategories.N_OTHER ===
  8694. oSourceElementData.nCategory) {
  8695. if ('undefined' === typeof nTo) {
  8696. nTo = nPosition; // Indicate the end of a range.
  8697. }
  8698. // Examine the range if it immediately follows a Directive Prologue.
  8699. if (nPosition === nAfterDirectivePrologue) {
  8700. fExamineSourceElements(nPosition, nTo, true);
  8701. }
  8702. } else {
  8703. if ('undefined' !== typeof nTo) {
  8704. // Examine the range that immediately follows this source element.
  8705. fExamineSourceElements(nPosition + 1, nTo, true);
  8706. nTo = void 0; // Obliterate the range.
  8707. }
  8708. // Examine nested functions.
  8709. oWalker = oProcessor.ast_walker();
  8710. oWalker.with_walkers(
  8711. oWalkers.oExamineFunctions,
  8712. cContext(oWalker, oSourceElements[nPosition]));
  8713. }
  8714. }
  8715. }
  8716. }(oAbstractSyntaxTree = oProcessor.ast_add_scope(oAbstractSyntaxTree)));
  8717. return oAbstractSyntaxTree;
  8718. };
  8719. /*jshint sub:false */
  8720. /* Local Variables: */
  8721. /* mode: js */
  8722. /* coding: utf-8 */
  8723. /* indent-tabs-mode: nil */
  8724. /* tab-width: 2 */
  8725. /* End: */
  8726. /* vim: set ft=javascript fenc=utf-8 et ts=2 sts=2 sw=2: */
  8727. /* :mode=javascript:noTabs=true:tabSize=2:indentSize=2:deepIndent=true: */
  8728. });
  8729. define('uglifyjs/parse-js', ["exports"], function(exports) {
  8730. /***********************************************************************
  8731. A JavaScript tokenizer / parser / beautifier / compressor.
  8732. This version is suitable for Node.js. With minimal changes (the
  8733. exports stuff) it should work on any JS platform.
  8734. This file contains the tokenizer/parser. It is a port to JavaScript
  8735. of parse-js [1], a JavaScript parser library written in Common Lisp
  8736. by Marijn Haverbeke. Thank you Marijn!
  8737. [1] http://marijn.haverbeke.nl/parse-js/
  8738. Exported functions:
  8739. - tokenizer(code) -- returns a function. Call the returned
  8740. function to fetch the next token.
  8741. - parse(code) -- returns an AST of the given JavaScript code.
  8742. -------------------------------- (C) ---------------------------------
  8743. Author: Mihai Bazon
  8744. <mihai.bazon@gmail.com>
  8745. http://mihai.bazon.net/blog
  8746. Distributed under the BSD license:
  8747. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  8748. Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  8749. Redistribution and use in source and binary forms, with or without
  8750. modification, are permitted provided that the following conditions
  8751. are met:
  8752. * Redistributions of source code must retain the above
  8753. copyright notice, this list of conditions and the following
  8754. disclaimer.
  8755. * Redistributions in binary form must reproduce the above
  8756. copyright notice, this list of conditions and the following
  8757. disclaimer in the documentation and/or other materials
  8758. provided with the distribution.
  8759. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  8760. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  8761. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  8762. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  8763. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  8764. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  8765. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  8766. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8767. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  8768. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  8769. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  8770. SUCH DAMAGE.
  8771. ***********************************************************************/
  8772. /* -----[ Tokenizer (constants) ]----- */
  8773. var KEYWORDS = array_to_hash([
  8774. "break",
  8775. "case",
  8776. "catch",
  8777. "const",
  8778. "continue",
  8779. "debugger",
  8780. "default",
  8781. "delete",
  8782. "do",
  8783. "else",
  8784. "finally",
  8785. "for",
  8786. "function",
  8787. "if",
  8788. "in",
  8789. "instanceof",
  8790. "new",
  8791. "return",
  8792. "switch",
  8793. "throw",
  8794. "try",
  8795. "typeof",
  8796. "var",
  8797. "void",
  8798. "while",
  8799. "with"
  8800. ]);
  8801. var RESERVED_WORDS = array_to_hash([
  8802. "abstract",
  8803. "boolean",
  8804. "byte",
  8805. "char",
  8806. "class",
  8807. "double",
  8808. "enum",
  8809. "export",
  8810. "extends",
  8811. "final",
  8812. "float",
  8813. "goto",
  8814. "implements",
  8815. "import",
  8816. "int",
  8817. "interface",
  8818. "long",
  8819. "native",
  8820. "package",
  8821. "private",
  8822. "protected",
  8823. "public",
  8824. "short",
  8825. "static",
  8826. "super",
  8827. "synchronized",
  8828. "throws",
  8829. "transient",
  8830. "volatile"
  8831. ]);
  8832. var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
  8833. "return",
  8834. "new",
  8835. "delete",
  8836. "throw",
  8837. "else",
  8838. "case"
  8839. ]);
  8840. var KEYWORDS_ATOM = array_to_hash([
  8841. "false",
  8842. "null",
  8843. "true",
  8844. "undefined"
  8845. ]);
  8846. var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
  8847. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  8848. var RE_OCT_NUMBER = /^0[0-7]+$/;
  8849. var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
  8850. var OPERATORS = array_to_hash([
  8851. "in",
  8852. "instanceof",
  8853. "typeof",
  8854. "new",
  8855. "void",
  8856. "delete",
  8857. "++",
  8858. "--",
  8859. "+",
  8860. "-",
  8861. "!",
  8862. "~",
  8863. "&",
  8864. "|",
  8865. "^",
  8866. "*",
  8867. "/",
  8868. "%",
  8869. ">>",
  8870. "<<",
  8871. ">>>",
  8872. "<",
  8873. ">",
  8874. "<=",
  8875. ">=",
  8876. "==",
  8877. "===",
  8878. "!=",
  8879. "!==",
  8880. "?",
  8881. "=",
  8882. "+=",
  8883. "-=",
  8884. "/=",
  8885. "*=",
  8886. "%=",
  8887. ">>=",
  8888. "<<=",
  8889. ">>>=",
  8890. "|=",
  8891. "^=",
  8892. "&=",
  8893. "&&",
  8894. "||"
  8895. ]);
  8896. var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\uFEFF"));
  8897. var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:"));
  8898. var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
  8899. var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
  8900. /* -----[ Tokenizer ]----- */
  8901. var UNICODE = { // Unicode 6.1
  8902. letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\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]"),
  8903. combining_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08E4-\\u08FE\\u0900-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C01-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C82\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D02\\u0D03\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1DC0-\\u1DE6\\u1DFC-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA674-\\uA67D\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
  8904. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"),
  8905. digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]")
  8906. };
  8907. function is_letter(ch) {
  8908. return UNICODE.letter.test(ch);
  8909. };
  8910. function is_digit(ch) {
  8911. ch = ch.charCodeAt(0);
  8912. return ch >= 48 && ch <= 57;
  8913. };
  8914. function is_unicode_digit(ch) {
  8915. return UNICODE.digit.test(ch);
  8916. }
  8917. function is_alphanumeric_char(ch) {
  8918. return is_digit(ch) || is_letter(ch);
  8919. };
  8920. function is_unicode_combining_mark(ch) {
  8921. return UNICODE.combining_mark.test(ch);
  8922. };
  8923. function is_unicode_connector_punctuation(ch) {
  8924. return UNICODE.connector_punctuation.test(ch);
  8925. };
  8926. function is_identifier_start(ch) {
  8927. return ch == "$" || ch == "_" || is_letter(ch);
  8928. };
  8929. function is_identifier_char(ch) {
  8930. return is_identifier_start(ch)
  8931. || is_unicode_combining_mark(ch)
  8932. || is_unicode_digit(ch)
  8933. || is_unicode_connector_punctuation(ch)
  8934. || ch == "\u200c" // zero-width non-joiner <ZWNJ>
  8935. || ch == "\u200d" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  8936. ;
  8937. };
  8938. function parse_js_number(num) {
  8939. if (RE_HEX_NUMBER.test(num)) {
  8940. return parseInt(num.substr(2), 16);
  8941. } else if (RE_OCT_NUMBER.test(num)) {
  8942. return parseInt(num.substr(1), 8);
  8943. } else if (RE_DEC_NUMBER.test(num)) {
  8944. return parseFloat(num);
  8945. }
  8946. };
  8947. function JS_Parse_Error(message, line, col, pos) {
  8948. this.message = message;
  8949. this.line = line + 1;
  8950. this.col = col + 1;
  8951. this.pos = pos + 1;
  8952. this.stack = new Error().stack;
  8953. };
  8954. JS_Parse_Error.prototype.toString = function() {
  8955. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  8956. };
  8957. function js_error(message, line, col, pos) {
  8958. throw new JS_Parse_Error(message, line, col, pos);
  8959. };
  8960. function is_token(token, type, val) {
  8961. return token.type == type && (val == null || token.value == val);
  8962. };
  8963. var EX_EOF = {};
  8964. function tokenizer($TEXT) {
  8965. var S = {
  8966. text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
  8967. pos : 0,
  8968. tokpos : 0,
  8969. line : 0,
  8970. tokline : 0,
  8971. col : 0,
  8972. tokcol : 0,
  8973. newline_before : false,
  8974. regex_allowed : false,
  8975. comments_before : []
  8976. };
  8977. function peek() { return S.text.charAt(S.pos); };
  8978. function next(signal_eof, in_string) {
  8979. var ch = S.text.charAt(S.pos++);
  8980. if (signal_eof && !ch)
  8981. throw EX_EOF;
  8982. if (ch == "\n") {
  8983. S.newline_before = S.newline_before || !in_string;
  8984. ++S.line;
  8985. S.col = 0;
  8986. } else {
  8987. ++S.col;
  8988. }
  8989. return ch;
  8990. };
  8991. function eof() {
  8992. return !S.peek();
  8993. };
  8994. function find(what, signal_eof) {
  8995. var pos = S.text.indexOf(what, S.pos);
  8996. if (signal_eof && pos == -1) throw EX_EOF;
  8997. return pos;
  8998. };
  8999. function start_token() {
  9000. S.tokline = S.line;
  9001. S.tokcol = S.col;
  9002. S.tokpos = S.pos;
  9003. };
  9004. function token(type, value, is_comment) {
  9005. S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
  9006. (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
  9007. (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
  9008. var ret = {
  9009. type : type,
  9010. value : value,
  9011. line : S.tokline,
  9012. col : S.tokcol,
  9013. pos : S.tokpos,
  9014. endpos : S.pos,
  9015. nlb : S.newline_before
  9016. };
  9017. if (!is_comment) {
  9018. ret.comments_before = S.comments_before;
  9019. S.comments_before = [];
  9020. // make note of any newlines in the comments that came before
  9021. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  9022. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  9023. }
  9024. }
  9025. S.newline_before = false;
  9026. return ret;
  9027. };
  9028. function skip_whitespace() {
  9029. while (HOP(WHITESPACE_CHARS, peek()))
  9030. next();
  9031. };
  9032. function read_while(pred) {
  9033. var ret = "", ch = peek(), i = 0;
  9034. while (ch && pred(ch, i++)) {
  9035. ret += next();
  9036. ch = peek();
  9037. }
  9038. return ret;
  9039. };
  9040. function parse_error(err) {
  9041. js_error(err, S.tokline, S.tokcol, S.tokpos);
  9042. };
  9043. function read_num(prefix) {
  9044. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  9045. var num = read_while(function(ch, i){
  9046. if (ch == "x" || ch == "X") {
  9047. if (has_x) return false;
  9048. return has_x = true;
  9049. }
  9050. if (!has_x && (ch == "E" || ch == "e")) {
  9051. if (has_e) return false;
  9052. return has_e = after_e = true;
  9053. }
  9054. if (ch == "-") {
  9055. if (after_e || (i == 0 && !prefix)) return true;
  9056. return false;
  9057. }
  9058. if (ch == "+") return after_e;
  9059. after_e = false;
  9060. if (ch == ".") {
  9061. if (!has_dot && !has_x && !has_e)
  9062. return has_dot = true;
  9063. return false;
  9064. }
  9065. return is_alphanumeric_char(ch);
  9066. });
  9067. if (prefix)
  9068. num = prefix + num;
  9069. var valid = parse_js_number(num);
  9070. if (!isNaN(valid)) {
  9071. return token("num", valid);
  9072. } else {
  9073. parse_error("Invalid syntax: " + num);
  9074. }
  9075. };
  9076. function read_escaped_char(in_string) {
  9077. var ch = next(true, in_string);
  9078. switch (ch) {
  9079. case "n" : return "\n";
  9080. case "r" : return "\r";
  9081. case "t" : return "\t";
  9082. case "b" : return "\b";
  9083. case "v" : return "\u000b";
  9084. case "f" : return "\f";
  9085. case "0" : return "\0";
  9086. case "x" : return String.fromCharCode(hex_bytes(2));
  9087. case "u" : return String.fromCharCode(hex_bytes(4));
  9088. case "\n": return "";
  9089. default : return ch;
  9090. }
  9091. };
  9092. function hex_bytes(n) {
  9093. var num = 0;
  9094. for (; n > 0; --n) {
  9095. var digit = parseInt(next(true), 16);
  9096. if (isNaN(digit))
  9097. parse_error("Invalid hex-character pattern in string");
  9098. num = (num << 4) | digit;
  9099. }
  9100. return num;
  9101. };
  9102. function read_string() {
  9103. return with_eof_error("Unterminated string constant", function(){
  9104. var quote = next(), ret = "";
  9105. for (;;) {
  9106. var ch = next(true);
  9107. if (ch == "\\") {
  9108. // read OctalEscapeSequence (XXX: deprecated if "strict mode")
  9109. // https://github.com/mishoo/UglifyJS/issues/178
  9110. var octal_len = 0, first = null;
  9111. ch = read_while(function(ch){
  9112. if (ch >= "0" && ch <= "7") {
  9113. if (!first) {
  9114. first = ch;
  9115. return ++octal_len;
  9116. }
  9117. else if (first <= "3" && octal_len <= 2) return ++octal_len;
  9118. else if (first >= "4" && octal_len <= 1) return ++octal_len;
  9119. }
  9120. return false;
  9121. });
  9122. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
  9123. else ch = read_escaped_char(true);
  9124. }
  9125. else if (ch == quote) break;
  9126. else if (ch == "\n") throw EX_EOF;
  9127. ret += ch;
  9128. }
  9129. return token("string", ret);
  9130. });
  9131. };
  9132. function read_line_comment() {
  9133. next();
  9134. var i = find("\n"), ret;
  9135. if (i == -1) {
  9136. ret = S.text.substr(S.pos);
  9137. S.pos = S.text.length;
  9138. } else {
  9139. ret = S.text.substring(S.pos, i);
  9140. S.pos = i;
  9141. }
  9142. return token("comment1", ret, true);
  9143. };
  9144. function read_multiline_comment() {
  9145. next();
  9146. return with_eof_error("Unterminated multiline comment", function(){
  9147. var i = find("*/", true),
  9148. text = S.text.substring(S.pos, i);
  9149. S.pos = i + 2;
  9150. S.line += text.split("\n").length - 1;
  9151. S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  9152. // https://github.com/mishoo/UglifyJS/issues/#issue/100
  9153. if (/^@cc_on/i.test(text)) {
  9154. warn("WARNING: at line " + S.line);
  9155. warn("*** Found \"conditional comment\": " + text);
  9156. warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
  9157. }
  9158. return token("comment2", text, true);
  9159. });
  9160. };
  9161. function read_name() {
  9162. var backslash = false, name = "", ch, escaped = false, hex;
  9163. while ((ch = peek()) != null) {
  9164. if (!backslash) {
  9165. if (ch == "\\") escaped = backslash = true, next();
  9166. else if (is_identifier_char(ch)) name += next();
  9167. else break;
  9168. }
  9169. else {
  9170. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  9171. ch = read_escaped_char();
  9172. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  9173. name += ch;
  9174. backslash = false;
  9175. }
  9176. }
  9177. if (HOP(KEYWORDS, name) && escaped) {
  9178. hex = name.charCodeAt(0).toString(16).toUpperCase();
  9179. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  9180. }
  9181. return name;
  9182. };
  9183. function read_regexp(regexp) {
  9184. return with_eof_error("Unterminated regular expression", function(){
  9185. var prev_backslash = false, ch, in_class = false;
  9186. while ((ch = next(true))) if (prev_backslash) {
  9187. regexp += "\\" + ch;
  9188. prev_backslash = false;
  9189. } else if (ch == "[") {
  9190. in_class = true;
  9191. regexp += ch;
  9192. } else if (ch == "]" && in_class) {
  9193. in_class = false;
  9194. regexp += ch;
  9195. } else if (ch == "/" && !in_class) {
  9196. break;
  9197. } else if (ch == "\\") {
  9198. prev_backslash = true;
  9199. } else {
  9200. regexp += ch;
  9201. }
  9202. var mods = read_name();
  9203. return token("regexp", [ regexp, mods ]);
  9204. });
  9205. };
  9206. function read_operator(prefix) {
  9207. function grow(op) {
  9208. if (!peek()) return op;
  9209. var bigger = op + peek();
  9210. if (HOP(OPERATORS, bigger)) {
  9211. next();
  9212. return grow(bigger);
  9213. } else {
  9214. return op;
  9215. }
  9216. };
  9217. return token("operator", grow(prefix || next()));
  9218. };
  9219. function handle_slash() {
  9220. next();
  9221. var regex_allowed = S.regex_allowed;
  9222. switch (peek()) {
  9223. case "/":
  9224. S.comments_before.push(read_line_comment());
  9225. S.regex_allowed = regex_allowed;
  9226. return next_token();
  9227. case "*":
  9228. S.comments_before.push(read_multiline_comment());
  9229. S.regex_allowed = regex_allowed;
  9230. return next_token();
  9231. }
  9232. return S.regex_allowed ? read_regexp("") : read_operator("/");
  9233. };
  9234. function handle_dot() {
  9235. next();
  9236. return is_digit(peek())
  9237. ? read_num(".")
  9238. : token("punc", ".");
  9239. };
  9240. function read_word() {
  9241. var word = read_name();
  9242. return !HOP(KEYWORDS, word)
  9243. ? token("name", word)
  9244. : HOP(OPERATORS, word)
  9245. ? token("operator", word)
  9246. : HOP(KEYWORDS_ATOM, word)
  9247. ? token("atom", word)
  9248. : token("keyword", word);
  9249. };
  9250. function with_eof_error(eof_error, cont) {
  9251. try {
  9252. return cont();
  9253. } catch(ex) {
  9254. if (ex === EX_EOF) parse_error(eof_error);
  9255. else throw ex;
  9256. }
  9257. };
  9258. function next_token(force_regexp) {
  9259. if (force_regexp != null)
  9260. return read_regexp(force_regexp);
  9261. skip_whitespace();
  9262. start_token();
  9263. var ch = peek();
  9264. if (!ch) return token("eof");
  9265. if (is_digit(ch)) return read_num();
  9266. if (ch == '"' || ch == "'") return read_string();
  9267. if (HOP(PUNC_CHARS, ch)) return token("punc", next());
  9268. if (ch == ".") return handle_dot();
  9269. if (ch == "/") return handle_slash();
  9270. if (HOP(OPERATOR_CHARS, ch)) return read_operator();
  9271. if (ch == "\\" || is_identifier_start(ch)) return read_word();
  9272. parse_error("Unexpected character '" + ch + "'");
  9273. };
  9274. next_token.context = function(nc) {
  9275. if (nc) S = nc;
  9276. return S;
  9277. };
  9278. return next_token;
  9279. };
  9280. /* -----[ Parser (constants) ]----- */
  9281. var UNARY_PREFIX = array_to_hash([
  9282. "typeof",
  9283. "void",
  9284. "delete",
  9285. "--",
  9286. "++",
  9287. "!",
  9288. "~",
  9289. "-",
  9290. "+"
  9291. ]);
  9292. var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
  9293. var ASSIGNMENT = (function(a, ret, i){
  9294. while (i < a.length) {
  9295. ret[a[i]] = a[i].substr(0, a[i].length - 1);
  9296. i++;
  9297. }
  9298. return ret;
  9299. })(
  9300. ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
  9301. { "=": true },
  9302. 0
  9303. );
  9304. var PRECEDENCE = (function(a, ret){
  9305. for (var i = 0, n = 1; i < a.length; ++i, ++n) {
  9306. var b = a[i];
  9307. for (var j = 0; j < b.length; ++j) {
  9308. ret[b[j]] = n;
  9309. }
  9310. }
  9311. return ret;
  9312. })(
  9313. [
  9314. ["||"],
  9315. ["&&"],
  9316. ["|"],
  9317. ["^"],
  9318. ["&"],
  9319. ["==", "===", "!=", "!=="],
  9320. ["<", ">", "<=", ">=", "in", "instanceof"],
  9321. [">>", "<<", ">>>"],
  9322. ["+", "-"],
  9323. ["*", "/", "%"]
  9324. ],
  9325. {}
  9326. );
  9327. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  9328. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  9329. /* -----[ Parser ]----- */
  9330. function NodeWithToken(str, start, end) {
  9331. this.name = str;
  9332. this.start = start;
  9333. this.end = end;
  9334. };
  9335. NodeWithToken.prototype.toString = function() { return this.name; };
  9336. function parse($TEXT, exigent_mode, embed_tokens) {
  9337. var S = {
  9338. input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT,
  9339. token : null,
  9340. prev : null,
  9341. peeked : null,
  9342. in_function : 0,
  9343. in_directives : true,
  9344. in_loop : 0,
  9345. labels : []
  9346. };
  9347. S.token = next();
  9348. function is(type, value) {
  9349. return is_token(S.token, type, value);
  9350. };
  9351. function peek() { return S.peeked || (S.peeked = S.input()); };
  9352. function next() {
  9353. S.prev = S.token;
  9354. if (S.peeked) {
  9355. S.token = S.peeked;
  9356. S.peeked = null;
  9357. } else {
  9358. S.token = S.input();
  9359. }
  9360. S.in_directives = S.in_directives && (
  9361. S.token.type == "string" || is("punc", ";")
  9362. );
  9363. return S.token;
  9364. };
  9365. function prev() {
  9366. return S.prev;
  9367. };
  9368. function croak(msg, line, col, pos) {
  9369. var ctx = S.input.context();
  9370. js_error(msg,
  9371. line != null ? line : ctx.tokline,
  9372. col != null ? col : ctx.tokcol,
  9373. pos != null ? pos : ctx.tokpos);
  9374. };
  9375. function token_error(token, msg) {
  9376. croak(msg, token.line, token.col);
  9377. };
  9378. function unexpected(token) {
  9379. if (token == null)
  9380. token = S.token;
  9381. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  9382. };
  9383. function expect_token(type, val) {
  9384. if (is(type, val)) {
  9385. return next();
  9386. }
  9387. token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type);
  9388. };
  9389. function expect(punc) { return expect_token("punc", punc); };
  9390. function can_insert_semicolon() {
  9391. return !exigent_mode && (
  9392. S.token.nlb || is("eof") || is("punc", "}")
  9393. );
  9394. };
  9395. function semicolon() {
  9396. if (is("punc", ";")) next();
  9397. else if (!can_insert_semicolon()) unexpected();
  9398. };
  9399. function as() {
  9400. return slice(arguments);
  9401. };
  9402. function parenthesised() {
  9403. expect("(");
  9404. var ex = expression();
  9405. expect(")");
  9406. return ex;
  9407. };
  9408. function add_tokens(str, start, end) {
  9409. return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
  9410. };
  9411. function maybe_embed_tokens(parser) {
  9412. if (embed_tokens) return function() {
  9413. var start = S.token;
  9414. var ast = parser.apply(this, arguments);
  9415. ast[0] = add_tokens(ast[0], start, prev());
  9416. return ast;
  9417. };
  9418. else return parser;
  9419. };
  9420. var statement = maybe_embed_tokens(function() {
  9421. if (is("operator", "/") || is("operator", "/=")) {
  9422. S.peeked = null;
  9423. S.token = S.input(S.token.value.substr(1)); // force regexp
  9424. }
  9425. switch (S.token.type) {
  9426. case "string":
  9427. var dir = S.in_directives, stat = simple_statement();
  9428. if (dir && stat[1][0] == "string" && !is("punc", ","))
  9429. return as("directive", stat[1][1]);
  9430. return stat;
  9431. case "num":
  9432. case "regexp":
  9433. case "operator":
  9434. case "atom":
  9435. return simple_statement();
  9436. case "name":
  9437. return is_token(peek(), "punc", ":")
  9438. ? labeled_statement(prog1(S.token.value, next, next))
  9439. : simple_statement();
  9440. case "punc":
  9441. switch (S.token.value) {
  9442. case "{":
  9443. return as("block", block_());
  9444. case "[":
  9445. case "(":
  9446. return simple_statement();
  9447. case ";":
  9448. next();
  9449. return as("block");
  9450. default:
  9451. unexpected();
  9452. }
  9453. case "keyword":
  9454. switch (prog1(S.token.value, next)) {
  9455. case "break":
  9456. return break_cont("break");
  9457. case "continue":
  9458. return break_cont("continue");
  9459. case "debugger":
  9460. semicolon();
  9461. return as("debugger");
  9462. case "do":
  9463. return (function(body){
  9464. expect_token("keyword", "while");
  9465. return as("do", prog1(parenthesised, semicolon), body);
  9466. })(in_loop(statement));
  9467. case "for":
  9468. return for_();
  9469. case "function":
  9470. return function_(true);
  9471. case "if":
  9472. return if_();
  9473. case "return":
  9474. if (S.in_function == 0)
  9475. croak("'return' outside of function");
  9476. return as("return",
  9477. is("punc", ";")
  9478. ? (next(), null)
  9479. : can_insert_semicolon()
  9480. ? null
  9481. : prog1(expression, semicolon));
  9482. case "switch":
  9483. return as("switch", parenthesised(), switch_block_());
  9484. case "throw":
  9485. if (S.token.nlb)
  9486. croak("Illegal newline after 'throw'");
  9487. return as("throw", prog1(expression, semicolon));
  9488. case "try":
  9489. return try_();
  9490. case "var":
  9491. return prog1(var_, semicolon);
  9492. case "const":
  9493. return prog1(const_, semicolon);
  9494. case "while":
  9495. return as("while", parenthesised(), in_loop(statement));
  9496. case "with":
  9497. return as("with", parenthesised(), statement());
  9498. default:
  9499. unexpected();
  9500. }
  9501. }
  9502. });
  9503. function labeled_statement(label) {
  9504. S.labels.push(label);
  9505. var start = S.token, stat = statement();
  9506. if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
  9507. unexpected(start);
  9508. S.labels.pop();
  9509. return as("label", label, stat);
  9510. };
  9511. function simple_statement() {
  9512. return as("stat", prog1(expression, semicolon));
  9513. };
  9514. function break_cont(type) {
  9515. var name;
  9516. if (!can_insert_semicolon()) {
  9517. name = is("name") ? S.token.value : null;
  9518. }
  9519. if (name != null) {
  9520. next();
  9521. if (!member(name, S.labels))
  9522. croak("Label " + name + " without matching loop or statement");
  9523. }
  9524. else if (S.in_loop == 0)
  9525. croak(type + " not inside a loop or switch");
  9526. semicolon();
  9527. return as(type, name);
  9528. };
  9529. function for_() {
  9530. expect("(");
  9531. var init = null;
  9532. if (!is("punc", ";")) {
  9533. init = is("keyword", "var")
  9534. ? (next(), var_(true))
  9535. : expression(true, true);
  9536. if (is("operator", "in")) {
  9537. if (init[0] == "var" && init[1].length > 1)
  9538. croak("Only one variable declaration allowed in for..in loop");
  9539. return for_in(init);
  9540. }
  9541. }
  9542. return regular_for(init);
  9543. };
  9544. function regular_for(init) {
  9545. expect(";");
  9546. var test = is("punc", ";") ? null : expression();
  9547. expect(";");
  9548. var step = is("punc", ")") ? null : expression();
  9549. expect(")");
  9550. return as("for", init, test, step, in_loop(statement));
  9551. };
  9552. function for_in(init) {
  9553. var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
  9554. next();
  9555. var obj = expression();
  9556. expect(")");
  9557. return as("for-in", init, lhs, obj, in_loop(statement));
  9558. };
  9559. var function_ = function(in_statement) {
  9560. var name = is("name") ? prog1(S.token.value, next) : null;
  9561. if (in_statement && !name)
  9562. unexpected();
  9563. expect("(");
  9564. return as(in_statement ? "defun" : "function",
  9565. name,
  9566. // arguments
  9567. (function(first, a){
  9568. while (!is("punc", ")")) {
  9569. if (first) first = false; else expect(",");
  9570. if (!is("name")) unexpected();
  9571. a.push(S.token.value);
  9572. next();
  9573. }
  9574. next();
  9575. return a;
  9576. })(true, []),
  9577. // body
  9578. (function(){
  9579. ++S.in_function;
  9580. var loop = S.in_loop;
  9581. S.in_directives = true;
  9582. S.in_loop = 0;
  9583. var a = block_();
  9584. --S.in_function;
  9585. S.in_loop = loop;
  9586. return a;
  9587. })());
  9588. };
  9589. function if_() {
  9590. var cond = parenthesised(), body = statement(), belse;
  9591. if (is("keyword", "else")) {
  9592. next();
  9593. belse = statement();
  9594. }
  9595. return as("if", cond, body, belse);
  9596. };
  9597. function block_() {
  9598. expect("{");
  9599. var a = [];
  9600. while (!is("punc", "}")) {
  9601. if (is("eof")) unexpected();
  9602. a.push(statement());
  9603. }
  9604. next();
  9605. return a;
  9606. };
  9607. var switch_block_ = curry(in_loop, function(){
  9608. expect("{");
  9609. var a = [], cur = null;
  9610. while (!is("punc", "}")) {
  9611. if (is("eof")) unexpected();
  9612. if (is("keyword", "case")) {
  9613. next();
  9614. cur = [];
  9615. a.push([ expression(), cur ]);
  9616. expect(":");
  9617. }
  9618. else if (is("keyword", "default")) {
  9619. next();
  9620. expect(":");
  9621. cur = [];
  9622. a.push([ null, cur ]);
  9623. }
  9624. else {
  9625. if (!cur) unexpected();
  9626. cur.push(statement());
  9627. }
  9628. }
  9629. next();
  9630. return a;
  9631. });
  9632. function try_() {
  9633. var body = block_(), bcatch, bfinally;
  9634. if (is("keyword", "catch")) {
  9635. next();
  9636. expect("(");
  9637. if (!is("name"))
  9638. croak("Name expected");
  9639. var name = S.token.value;
  9640. next();
  9641. expect(")");
  9642. bcatch = [ name, block_() ];
  9643. }
  9644. if (is("keyword", "finally")) {
  9645. next();
  9646. bfinally = block_();
  9647. }
  9648. if (!bcatch && !bfinally)
  9649. croak("Missing catch/finally blocks");
  9650. return as("try", body, bcatch, bfinally);
  9651. };
  9652. function vardefs(no_in) {
  9653. var a = [];
  9654. for (;;) {
  9655. if (!is("name"))
  9656. unexpected();
  9657. var name = S.token.value;
  9658. next();
  9659. if (is("operator", "=")) {
  9660. next();
  9661. a.push([ name, expression(false, no_in) ]);
  9662. } else {
  9663. a.push([ name ]);
  9664. }
  9665. if (!is("punc", ","))
  9666. break;
  9667. next();
  9668. }
  9669. return a;
  9670. };
  9671. function var_(no_in) {
  9672. return as("var", vardefs(no_in));
  9673. };
  9674. function const_() {
  9675. return as("const", vardefs());
  9676. };
  9677. function new_() {
  9678. var newexp = expr_atom(false), args;
  9679. if (is("punc", "(")) {
  9680. next();
  9681. args = expr_list(")");
  9682. } else {
  9683. args = [];
  9684. }
  9685. return subscripts(as("new", newexp, args), true);
  9686. };
  9687. var expr_atom = maybe_embed_tokens(function(allow_calls) {
  9688. if (is("operator", "new")) {
  9689. next();
  9690. return new_();
  9691. }
  9692. if (is("punc")) {
  9693. switch (S.token.value) {
  9694. case "(":
  9695. next();
  9696. return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
  9697. case "[":
  9698. next();
  9699. return subscripts(array_(), allow_calls);
  9700. case "{":
  9701. next();
  9702. return subscripts(object_(), allow_calls);
  9703. }
  9704. unexpected();
  9705. }
  9706. if (is("keyword", "function")) {
  9707. next();
  9708. return subscripts(function_(false), allow_calls);
  9709. }
  9710. if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
  9711. var atom = S.token.type == "regexp"
  9712. ? as("regexp", S.token.value[0], S.token.value[1])
  9713. : as(S.token.type, S.token.value);
  9714. return subscripts(prog1(atom, next), allow_calls);
  9715. }
  9716. unexpected();
  9717. });
  9718. function expr_list(closing, allow_trailing_comma, allow_empty) {
  9719. var first = true, a = [];
  9720. while (!is("punc", closing)) {
  9721. if (first) first = false; else expect(",");
  9722. if (allow_trailing_comma && is("punc", closing)) break;
  9723. if (is("punc", ",") && allow_empty) {
  9724. a.push([ "atom", "undefined" ]);
  9725. } else {
  9726. a.push(expression(false));
  9727. }
  9728. }
  9729. next();
  9730. return a;
  9731. };
  9732. function array_() {
  9733. return as("array", expr_list("]", !exigent_mode, true));
  9734. };
  9735. function object_() {
  9736. var first = true, a = [];
  9737. while (!is("punc", "}")) {
  9738. if (first) first = false; else expect(",");
  9739. if (!exigent_mode && is("punc", "}"))
  9740. // allow trailing comma
  9741. break;
  9742. var type = S.token.type;
  9743. var name = as_property_name();
  9744. if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
  9745. a.push([ as_name(), function_(false), name ]);
  9746. } else {
  9747. expect(":");
  9748. a.push([ name, expression(false) ]);
  9749. }
  9750. }
  9751. next();
  9752. return as("object", a);
  9753. };
  9754. function as_property_name() {
  9755. switch (S.token.type) {
  9756. case "num":
  9757. case "string":
  9758. return prog1(S.token.value, next);
  9759. }
  9760. return as_name();
  9761. };
  9762. function as_name() {
  9763. switch (S.token.type) {
  9764. case "name":
  9765. case "operator":
  9766. case "keyword":
  9767. case "atom":
  9768. return prog1(S.token.value, next);
  9769. default:
  9770. unexpected();
  9771. }
  9772. };
  9773. function subscripts(expr, allow_calls) {
  9774. if (is("punc", ".")) {
  9775. next();
  9776. return subscripts(as("dot", expr, as_name()), allow_calls);
  9777. }
  9778. if (is("punc", "[")) {
  9779. next();
  9780. return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
  9781. }
  9782. if (allow_calls && is("punc", "(")) {
  9783. next();
  9784. return subscripts(as("call", expr, expr_list(")")), true);
  9785. }
  9786. return expr;
  9787. };
  9788. function maybe_unary(allow_calls) {
  9789. if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
  9790. return make_unary("unary-prefix",
  9791. prog1(S.token.value, next),
  9792. maybe_unary(allow_calls));
  9793. }
  9794. var val = expr_atom(allow_calls);
  9795. while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
  9796. val = make_unary("unary-postfix", S.token.value, val);
  9797. next();
  9798. }
  9799. return val;
  9800. };
  9801. function make_unary(tag, op, expr) {
  9802. if ((op == "++" || op == "--") && !is_assignable(expr))
  9803. croak("Invalid use of " + op + " operator");
  9804. return as(tag, op, expr);
  9805. };
  9806. function expr_op(left, min_prec, no_in) {
  9807. var op = is("operator") ? S.token.value : null;
  9808. if (op && op == "in" && no_in) op = null;
  9809. var prec = op != null ? PRECEDENCE[op] : null;
  9810. if (prec != null && prec > min_prec) {
  9811. next();
  9812. var right = expr_op(maybe_unary(true), prec, no_in);
  9813. return expr_op(as("binary", op, left, right), min_prec, no_in);
  9814. }
  9815. return left;
  9816. };
  9817. function expr_ops(no_in) {
  9818. return expr_op(maybe_unary(true), 0, no_in);
  9819. };
  9820. function maybe_conditional(no_in) {
  9821. var expr = expr_ops(no_in);
  9822. if (is("operator", "?")) {
  9823. next();
  9824. var yes = expression(false);
  9825. expect(":");
  9826. return as("conditional", expr, yes, expression(false, no_in));
  9827. }
  9828. return expr;
  9829. };
  9830. function is_assignable(expr) {
  9831. if (!exigent_mode) return true;
  9832. switch (expr[0]+"") {
  9833. case "dot":
  9834. case "sub":
  9835. case "new":
  9836. case "call":
  9837. return true;
  9838. case "name":
  9839. return expr[1] != "this";
  9840. }
  9841. };
  9842. function maybe_assign(no_in) {
  9843. var left = maybe_conditional(no_in), val = S.token.value;
  9844. if (is("operator") && HOP(ASSIGNMENT, val)) {
  9845. if (is_assignable(left)) {
  9846. next();
  9847. return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
  9848. }
  9849. croak("Invalid assignment");
  9850. }
  9851. return left;
  9852. };
  9853. var expression = maybe_embed_tokens(function(commas, no_in) {
  9854. if (arguments.length == 0)
  9855. commas = true;
  9856. var expr = maybe_assign(no_in);
  9857. if (commas && is("punc", ",")) {
  9858. next();
  9859. return as("seq", expr, expression(true, no_in));
  9860. }
  9861. return expr;
  9862. });
  9863. function in_loop(cont) {
  9864. try {
  9865. ++S.in_loop;
  9866. return cont();
  9867. } finally {
  9868. --S.in_loop;
  9869. }
  9870. };
  9871. return as("toplevel", (function(a){
  9872. while (!is("eof"))
  9873. a.push(statement());
  9874. return a;
  9875. })([]));
  9876. };
  9877. /* -----[ Utilities ]----- */
  9878. function curry(f) {
  9879. var args = slice(arguments, 1);
  9880. return function() { return f.apply(this, args.concat(slice(arguments))); };
  9881. };
  9882. function prog1(ret) {
  9883. if (ret instanceof Function)
  9884. ret = ret();
  9885. for (var i = 1, n = arguments.length; --n > 0; ++i)
  9886. arguments[i]();
  9887. return ret;
  9888. };
  9889. function array_to_hash(a) {
  9890. var ret = {};
  9891. for (var i = 0; i < a.length; ++i)
  9892. ret[a[i]] = true;
  9893. return ret;
  9894. };
  9895. function slice(a, start) {
  9896. return Array.prototype.slice.call(a, start || 0);
  9897. };
  9898. function characters(str) {
  9899. return str.split("");
  9900. };
  9901. function member(name, array) {
  9902. for (var i = array.length; --i >= 0;)
  9903. if (array[i] == name)
  9904. return true;
  9905. return false;
  9906. };
  9907. function HOP(obj, prop) {
  9908. return Object.prototype.hasOwnProperty.call(obj, prop);
  9909. };
  9910. var warn = function() {};
  9911. /* -----[ Exports ]----- */
  9912. exports.tokenizer = tokenizer;
  9913. exports.parse = parse;
  9914. exports.slice = slice;
  9915. exports.curry = curry;
  9916. exports.member = member;
  9917. exports.array_to_hash = array_to_hash;
  9918. exports.PRECEDENCE = PRECEDENCE;
  9919. exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
  9920. exports.RESERVED_WORDS = RESERVED_WORDS;
  9921. exports.KEYWORDS = KEYWORDS;
  9922. exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
  9923. exports.OPERATORS = OPERATORS;
  9924. exports.is_alphanumeric_char = is_alphanumeric_char;
  9925. exports.is_identifier_start = is_identifier_start;
  9926. exports.is_identifier_char = is_identifier_char;
  9927. exports.set_logger = function(logger) {
  9928. warn = logger;
  9929. };
  9930. // Local variables:
  9931. // js-indent-level: 4
  9932. // End:
  9933. });define('uglifyjs/squeeze-more', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
  9934. var jsp = require("./parse-js"),
  9935. pro = require("./process"),
  9936. slice = jsp.slice,
  9937. member = jsp.member,
  9938. curry = jsp.curry,
  9939. MAP = pro.MAP,
  9940. PRECEDENCE = jsp.PRECEDENCE,
  9941. OPERATORS = jsp.OPERATORS;
  9942. function ast_squeeze_more(ast) {
  9943. var w = pro.ast_walker(), walk = w.walk, scope;
  9944. function with_scope(s, cont) {
  9945. var save = scope, ret;
  9946. scope = s;
  9947. ret = cont();
  9948. scope = save;
  9949. return ret;
  9950. };
  9951. function _lambda(name, args, body) {
  9952. return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  9953. };
  9954. return w.with_walkers({
  9955. "toplevel": function(body) {
  9956. return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
  9957. },
  9958. "function": _lambda,
  9959. "defun": _lambda,
  9960. "new": function(ctor, args) {
  9961. if (ctor[0] == "name") {
  9962. if (ctor[1] == "Array" && !scope.has("Array")) {
  9963. if (args.length != 1) {
  9964. return [ "array", args ];
  9965. } else {
  9966. return walk([ "call", [ "name", "Array" ], args ]);
  9967. }
  9968. } else if (ctor[1] == "Object" && !scope.has("Object")) {
  9969. if (!args.length) {
  9970. return [ "object", [] ];
  9971. } else {
  9972. return walk([ "call", [ "name", "Object" ], args ]);
  9973. }
  9974. } else if ((ctor[1] == "RegExp" || ctor[1] == "Function" || ctor[1] == "Error") && !scope.has(ctor[1])) {
  9975. return walk([ "call", [ "name", ctor[1] ], args]);
  9976. }
  9977. }
  9978. },
  9979. "call": function(expr, args) {
  9980. if (expr[0] == "dot" && expr[1][0] == "string" && args.length == 1
  9981. && (args[0][1] > 0 && expr[2] == "substring" || expr[2] == "substr")) {
  9982. return [ "call", [ "dot", expr[1], "slice"], args];
  9983. }
  9984. if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) {
  9985. // foo.toString() ==> foo+""
  9986. if (expr[1][0] == "string") return expr[1];
  9987. return [ "binary", "+", expr[1], [ "string", "" ]];
  9988. }
  9989. if (expr[0] == "name") {
  9990. if (expr[1] == "Array" && args.length != 1 && !scope.has("Array")) {
  9991. return [ "array", args ];
  9992. }
  9993. if (expr[1] == "Object" && !args.length && !scope.has("Object")) {
  9994. return [ "object", [] ];
  9995. }
  9996. if (expr[1] == "String" && !scope.has("String")) {
  9997. return [ "binary", "+", args[0], [ "string", "" ]];
  9998. }
  9999. }
  10000. }
  10001. }, function() {
  10002. return walk(pro.ast_add_scope(ast));
  10003. });
  10004. };
  10005. exports.ast_squeeze_more = ast_squeeze_more;
  10006. // Local variables:
  10007. // js-indent-level: 4
  10008. // End:
  10009. });
  10010. define('uglifyjs/process', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
  10011. /***********************************************************************
  10012. A JavaScript tokenizer / parser / beautifier / compressor.
  10013. This version is suitable for Node.js. With minimal changes (the
  10014. exports stuff) it should work on any JS platform.
  10015. This file implements some AST processors. They work on data built
  10016. by parse-js.
  10017. Exported functions:
  10018. - ast_mangle(ast, options) -- mangles the variable/function names
  10019. in the AST. Returns an AST.
  10020. - ast_squeeze(ast) -- employs various optimizations to make the
  10021. final generated code even smaller. Returns an AST.
  10022. - gen_code(ast, options) -- generates JS code from the AST. Pass
  10023. true (or an object, see the code for some options) as second
  10024. argument to get "pretty" (indented) code.
  10025. -------------------------------- (C) ---------------------------------
  10026. Author: Mihai Bazon
  10027. <mihai.bazon@gmail.com>
  10028. http://mihai.bazon.net/blog
  10029. Distributed under the BSD license:
  10030. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10031. Redistribution and use in source and binary forms, with or without
  10032. modification, are permitted provided that the following conditions
  10033. are met:
  10034. * Redistributions of source code must retain the above
  10035. copyright notice, this list of conditions and the following
  10036. disclaimer.
  10037. * Redistributions in binary form must reproduce the above
  10038. copyright notice, this list of conditions and the following
  10039. disclaimer in the documentation and/or other materials
  10040. provided with the distribution.
  10041. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  10042. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  10043. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  10044. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  10045. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  10046. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  10047. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  10048. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10049. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  10050. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  10051. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  10052. SUCH DAMAGE.
  10053. ***********************************************************************/
  10054. var jsp = require("./parse-js"),
  10055. curry = jsp.curry,
  10056. slice = jsp.slice,
  10057. member = jsp.member,
  10058. is_identifier_char = jsp.is_identifier_char,
  10059. PRECEDENCE = jsp.PRECEDENCE,
  10060. OPERATORS = jsp.OPERATORS;
  10061. /* -----[ helper for AST traversal ]----- */
  10062. function ast_walker() {
  10063. function _vardefs(defs) {
  10064. return [ this[0], MAP(defs, function(def){
  10065. var a = [ def[0] ];
  10066. if (def.length > 1)
  10067. a[1] = walk(def[1]);
  10068. return a;
  10069. }) ];
  10070. };
  10071. function _block(statements) {
  10072. var out = [ this[0] ];
  10073. if (statements != null)
  10074. out.push(MAP(statements, walk));
  10075. return out;
  10076. };
  10077. var walkers = {
  10078. "string": function(str) {
  10079. return [ this[0], str ];
  10080. },
  10081. "num": function(num) {
  10082. return [ this[0], num ];
  10083. },
  10084. "name": function(name) {
  10085. return [ this[0], name ];
  10086. },
  10087. "toplevel": function(statements) {
  10088. return [ this[0], MAP(statements, walk) ];
  10089. },
  10090. "block": _block,
  10091. "splice": _block,
  10092. "var": _vardefs,
  10093. "const": _vardefs,
  10094. "try": function(t, c, f) {
  10095. return [
  10096. this[0],
  10097. MAP(t, walk),
  10098. c != null ? [ c[0], MAP(c[1], walk) ] : null,
  10099. f != null ? MAP(f, walk) : null
  10100. ];
  10101. },
  10102. "throw": function(expr) {
  10103. return [ this[0], walk(expr) ];
  10104. },
  10105. "new": function(ctor, args) {
  10106. return [ this[0], walk(ctor), MAP(args, walk) ];
  10107. },
  10108. "switch": function(expr, body) {
  10109. return [ this[0], walk(expr), MAP(body, function(branch){
  10110. return [ branch[0] ? walk(branch[0]) : null,
  10111. MAP(branch[1], walk) ];
  10112. }) ];
  10113. },
  10114. "break": function(label) {
  10115. return [ this[0], label ];
  10116. },
  10117. "continue": function(label) {
  10118. return [ this[0], label ];
  10119. },
  10120. "conditional": function(cond, t, e) {
  10121. return [ this[0], walk(cond), walk(t), walk(e) ];
  10122. },
  10123. "assign": function(op, lvalue, rvalue) {
  10124. return [ this[0], op, walk(lvalue), walk(rvalue) ];
  10125. },
  10126. "dot": function(expr) {
  10127. return [ this[0], walk(expr) ].concat(slice(arguments, 1));
  10128. },
  10129. "call": function(expr, args) {
  10130. return [ this[0], walk(expr), MAP(args, walk) ];
  10131. },
  10132. "function": function(name, args, body) {
  10133. return [ this[0], name, args.slice(), MAP(body, walk) ];
  10134. },
  10135. "debugger": function() {
  10136. return [ this[0] ];
  10137. },
  10138. "defun": function(name, args, body) {
  10139. return [ this[0], name, args.slice(), MAP(body, walk) ];
  10140. },
  10141. "if": function(conditional, t, e) {
  10142. return [ this[0], walk(conditional), walk(t), walk(e) ];
  10143. },
  10144. "for": function(init, cond, step, block) {
  10145. return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
  10146. },
  10147. "for-in": function(vvar, key, hash, block) {
  10148. return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
  10149. },
  10150. "while": function(cond, block) {
  10151. return [ this[0], walk(cond), walk(block) ];
  10152. },
  10153. "do": function(cond, block) {
  10154. return [ this[0], walk(cond), walk(block) ];
  10155. },
  10156. "return": function(expr) {
  10157. return [ this[0], walk(expr) ];
  10158. },
  10159. "binary": function(op, left, right) {
  10160. return [ this[0], op, walk(left), walk(right) ];
  10161. },
  10162. "unary-prefix": function(op, expr) {
  10163. return [ this[0], op, walk(expr) ];
  10164. },
  10165. "unary-postfix": function(op, expr) {
  10166. return [ this[0], op, walk(expr) ];
  10167. },
  10168. "sub": function(expr, subscript) {
  10169. return [ this[0], walk(expr), walk(subscript) ];
  10170. },
  10171. "object": function(props) {
  10172. return [ this[0], MAP(props, function(p){
  10173. return p.length == 2
  10174. ? [ p[0], walk(p[1]) ]
  10175. : [ p[0], walk(p[1]), p[2] ]; // get/set-ter
  10176. }) ];
  10177. },
  10178. "regexp": function(rx, mods) {
  10179. return [ this[0], rx, mods ];
  10180. },
  10181. "array": function(elements) {
  10182. return [ this[0], MAP(elements, walk) ];
  10183. },
  10184. "stat": function(stat) {
  10185. return [ this[0], walk(stat) ];
  10186. },
  10187. "seq": function() {
  10188. return [ this[0] ].concat(MAP(slice(arguments), walk));
  10189. },
  10190. "label": function(name, block) {
  10191. return [ this[0], name, walk(block) ];
  10192. },
  10193. "with": function(expr, block) {
  10194. return [ this[0], walk(expr), walk(block) ];
  10195. },
  10196. "atom": function(name) {
  10197. return [ this[0], name ];
  10198. },
  10199. "directive": function(dir) {
  10200. return [ this[0], dir ];
  10201. }
  10202. };
  10203. var user = {};
  10204. var stack = [];
  10205. function walk(ast) {
  10206. if (ast == null)
  10207. return null;
  10208. try {
  10209. stack.push(ast);
  10210. var type = ast[0];
  10211. var gen = user[type];
  10212. if (gen) {
  10213. var ret = gen.apply(ast, ast.slice(1));
  10214. if (ret != null)
  10215. return ret;
  10216. }
  10217. gen = walkers[type];
  10218. return gen.apply(ast, ast.slice(1));
  10219. } finally {
  10220. stack.pop();
  10221. }
  10222. };
  10223. function dive(ast) {
  10224. if (ast == null)
  10225. return null;
  10226. try {
  10227. stack.push(ast);
  10228. return walkers[ast[0]].apply(ast, ast.slice(1));
  10229. } finally {
  10230. stack.pop();
  10231. }
  10232. };
  10233. function with_walkers(walkers, cont){
  10234. var save = {}, i;
  10235. for (i in walkers) if (HOP(walkers, i)) {
  10236. save[i] = user[i];
  10237. user[i] = walkers[i];
  10238. }
  10239. var ret = cont();
  10240. for (i in save) if (HOP(save, i)) {
  10241. if (!save[i]) delete user[i];
  10242. else user[i] = save[i];
  10243. }
  10244. return ret;
  10245. };
  10246. return {
  10247. walk: walk,
  10248. dive: dive,
  10249. with_walkers: with_walkers,
  10250. parent: function() {
  10251. return stack[stack.length - 2]; // last one is current node
  10252. },
  10253. stack: function() {
  10254. return stack;
  10255. }
  10256. };
  10257. };
  10258. /* -----[ Scope and mangling ]----- */
  10259. function Scope(parent) {
  10260. this.names = {}; // names defined in this scope
  10261. this.mangled = {}; // mangled names (orig.name => mangled)
  10262. this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
  10263. this.cname = -1; // current mangled name
  10264. this.refs = {}; // names referenced from this scope
  10265. this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
  10266. this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
  10267. this.directives = []; // directives activated from this scope
  10268. this.parent = parent; // parent scope
  10269. this.children = []; // sub-scopes
  10270. if (parent) {
  10271. this.level = parent.level + 1;
  10272. parent.children.push(this);
  10273. } else {
  10274. this.level = 0;
  10275. }
  10276. };
  10277. function base54_digits() {
  10278. if (typeof DIGITS_OVERRIDE_FOR_TESTING != "undefined")
  10279. return DIGITS_OVERRIDE_FOR_TESTING;
  10280. else
  10281. return "etnrisouaflchpdvmgybwESxTNCkLAOM_DPHBjFIqRUzWXV$JKQGYZ0516372984";
  10282. }
  10283. var base54 = (function(){
  10284. var DIGITS = base54_digits();
  10285. return function(num) {
  10286. var ret = "", base = 54;
  10287. do {
  10288. ret += DIGITS.charAt(num % base);
  10289. num = Math.floor(num / base);
  10290. base = 64;
  10291. } while (num > 0);
  10292. return ret;
  10293. };
  10294. })();
  10295. Scope.prototype = {
  10296. has: function(name) {
  10297. for (var s = this; s; s = s.parent)
  10298. if (HOP(s.names, name))
  10299. return s;
  10300. },
  10301. has_mangled: function(mname) {
  10302. for (var s = this; s; s = s.parent)
  10303. if (HOP(s.rev_mangled, mname))
  10304. return s;
  10305. },
  10306. toJSON: function() {
  10307. return {
  10308. names: this.names,
  10309. uses_eval: this.uses_eval,
  10310. uses_with: this.uses_with
  10311. };
  10312. },
  10313. next_mangled: function() {
  10314. // we must be careful that the new mangled name:
  10315. //
  10316. // 1. doesn't shadow a mangled name from a parent
  10317. // scope, unless we don't reference the original
  10318. // name from this scope OR from any sub-scopes!
  10319. // This will get slow.
  10320. //
  10321. // 2. doesn't shadow an original name from a parent
  10322. // scope, in the event that the name is not mangled
  10323. // in the parent scope and we reference that name
  10324. // here OR IN ANY SUBSCOPES!
  10325. //
  10326. // 3. doesn't shadow a name that is referenced but not
  10327. // defined (possibly global defined elsewhere).
  10328. for (;;) {
  10329. var m = base54(++this.cname), prior;
  10330. // case 1.
  10331. prior = this.has_mangled(m);
  10332. if (prior && this.refs[prior.rev_mangled[m]] === prior)
  10333. continue;
  10334. // case 2.
  10335. prior = this.has(m);
  10336. if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
  10337. continue;
  10338. // case 3.
  10339. if (HOP(this.refs, m) && this.refs[m] == null)
  10340. continue;
  10341. // I got "do" once. :-/
  10342. if (!is_identifier(m))
  10343. continue;
  10344. return m;
  10345. }
  10346. },
  10347. set_mangle: function(name, m) {
  10348. this.rev_mangled[m] = name;
  10349. return this.mangled[name] = m;
  10350. },
  10351. get_mangled: function(name, newMangle) {
  10352. if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
  10353. var s = this.has(name);
  10354. if (!s) return name; // not in visible scope, no mangle
  10355. if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
  10356. if (!newMangle) return name; // not found and no mangling requested
  10357. return s.set_mangle(name, s.next_mangled());
  10358. },
  10359. references: function(name) {
  10360. return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];
  10361. },
  10362. define: function(name, type) {
  10363. if (name != null) {
  10364. if (type == "var" || !HOP(this.names, name))
  10365. this.names[name] = type || "var";
  10366. return name;
  10367. }
  10368. },
  10369. active_directive: function(dir) {
  10370. return member(dir, this.directives) || this.parent && this.parent.active_directive(dir);
  10371. }
  10372. };
  10373. function ast_add_scope(ast) {
  10374. var current_scope = null;
  10375. var w = ast_walker(), walk = w.walk;
  10376. var having_eval = [];
  10377. function with_new_scope(cont) {
  10378. current_scope = new Scope(current_scope);
  10379. current_scope.labels = new Scope();
  10380. var ret = current_scope.body = cont();
  10381. ret.scope = current_scope;
  10382. current_scope = current_scope.parent;
  10383. return ret;
  10384. };
  10385. function define(name, type) {
  10386. return current_scope.define(name, type);
  10387. };
  10388. function reference(name) {
  10389. current_scope.refs[name] = true;
  10390. };
  10391. function _lambda(name, args, body) {
  10392. var is_defun = this[0] == "defun";
  10393. return [ this[0], is_defun ? define(name, "defun") : name, args, with_new_scope(function(){
  10394. if (!is_defun) define(name, "lambda");
  10395. MAP(args, function(name){ define(name, "arg") });
  10396. return MAP(body, walk);
  10397. })];
  10398. };
  10399. function _vardefs(type) {
  10400. return function(defs) {
  10401. MAP(defs, function(d){
  10402. define(d[0], type);
  10403. if (d[1]) reference(d[0]);
  10404. });
  10405. };
  10406. };
  10407. function _breacont(label) {
  10408. if (label)
  10409. current_scope.labels.refs[label] = true;
  10410. };
  10411. return with_new_scope(function(){
  10412. // process AST
  10413. var ret = w.with_walkers({
  10414. "function": _lambda,
  10415. "defun": _lambda,
  10416. "label": function(name, stat) { current_scope.labels.define(name) },
  10417. "break": _breacont,
  10418. "continue": _breacont,
  10419. "with": function(expr, block) {
  10420. for (var s = current_scope; s; s = s.parent)
  10421. s.uses_with = true;
  10422. },
  10423. "var": _vardefs("var"),
  10424. "const": _vardefs("const"),
  10425. "try": function(t, c, f) {
  10426. if (c != null) return [
  10427. this[0],
  10428. MAP(t, walk),
  10429. [ define(c[0], "catch"), MAP(c[1], walk) ],
  10430. f != null ? MAP(f, walk) : null
  10431. ];
  10432. },
  10433. "name": function(name) {
  10434. if (name == "eval")
  10435. having_eval.push(current_scope);
  10436. reference(name);
  10437. }
  10438. }, function(){
  10439. return walk(ast);
  10440. });
  10441. // the reason why we need an additional pass here is
  10442. // that names can be used prior to their definition.
  10443. // scopes where eval was detected and their parents
  10444. // are marked with uses_eval, unless they define the
  10445. // "eval" name.
  10446. MAP(having_eval, function(scope){
  10447. if (!scope.has("eval")) while (scope) {
  10448. scope.uses_eval = true;
  10449. scope = scope.parent;
  10450. }
  10451. });
  10452. // for referenced names it might be useful to know
  10453. // their origin scope. current_scope here is the
  10454. // toplevel one.
  10455. function fixrefs(scope, i) {
  10456. // do children first; order shouldn't matter
  10457. for (i = scope.children.length; --i >= 0;)
  10458. fixrefs(scope.children[i]);
  10459. for (i in scope.refs) if (HOP(scope.refs, i)) {
  10460. // find origin scope and propagate the reference to origin
  10461. for (var origin = scope.has(i), s = scope; s; s = s.parent) {
  10462. s.refs[i] = origin;
  10463. if (s === origin) break;
  10464. }
  10465. }
  10466. };
  10467. fixrefs(current_scope);
  10468. return ret;
  10469. });
  10470. };
  10471. /* -----[ mangle names ]----- */
  10472. function ast_mangle(ast, options) {
  10473. var w = ast_walker(), walk = w.walk, scope;
  10474. options = defaults(options, {
  10475. mangle : true,
  10476. toplevel : false,
  10477. defines : null,
  10478. except : null,
  10479. no_functions : false
  10480. });
  10481. function get_mangled(name, newMangle) {
  10482. if (!options.mangle) return name;
  10483. if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
  10484. if (options.except && member(name, options.except))
  10485. return name;
  10486. if (options.no_functions && HOP(scope.names, name) &&
  10487. (scope.names[name] == 'defun' || scope.names[name] == 'lambda'))
  10488. return name;
  10489. return scope.get_mangled(name, newMangle);
  10490. };
  10491. function get_define(name) {
  10492. if (options.defines) {
  10493. // we always lookup a defined symbol for the current scope FIRST, so declared
  10494. // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value
  10495. if (!scope.has(name)) {
  10496. if (HOP(options.defines, name)) {
  10497. return options.defines[name];
  10498. }
  10499. }
  10500. return null;
  10501. }
  10502. };
  10503. function _lambda(name, args, body) {
  10504. if (!options.no_functions && options.mangle) {
  10505. var is_defun = this[0] == "defun", extra;
  10506. if (name) {
  10507. if (is_defun) name = get_mangled(name);
  10508. else if (body.scope.references(name)) {
  10509. extra = {};
  10510. if (!(scope.uses_eval || scope.uses_with))
  10511. name = extra[name] = scope.next_mangled();
  10512. else
  10513. extra[name] = name;
  10514. }
  10515. else name = null;
  10516. }
  10517. }
  10518. body = with_scope(body.scope, function(){
  10519. args = MAP(args, function(name){ return get_mangled(name) });
  10520. return MAP(body, walk);
  10521. }, extra);
  10522. return [ this[0], name, args, body ];
  10523. };
  10524. function with_scope(s, cont, extra) {
  10525. var _scope = scope;
  10526. scope = s;
  10527. if (extra) for (var i in extra) if (HOP(extra, i)) {
  10528. s.set_mangle(i, extra[i]);
  10529. }
  10530. for (var i in s.names) if (HOP(s.names, i)) {
  10531. get_mangled(i, true);
  10532. }
  10533. var ret = cont();
  10534. ret.scope = s;
  10535. scope = _scope;
  10536. return ret;
  10537. };
  10538. function _vardefs(defs) {
  10539. return [ this[0], MAP(defs, function(d){
  10540. return [ get_mangled(d[0]), walk(d[1]) ];
  10541. }) ];
  10542. };
  10543. function _breacont(label) {
  10544. if (label) return [ this[0], scope.labels.get_mangled(label) ];
  10545. };
  10546. return w.with_walkers({
  10547. "function": _lambda,
  10548. "defun": function() {
  10549. // move function declarations to the top when
  10550. // they are not in some block.
  10551. var ast = _lambda.apply(this, arguments);
  10552. switch (w.parent()[0]) {
  10553. case "toplevel":
  10554. case "function":
  10555. case "defun":
  10556. return MAP.at_top(ast);
  10557. }
  10558. return ast;
  10559. },
  10560. "label": function(label, stat) {
  10561. if (scope.labels.refs[label]) return [
  10562. this[0],
  10563. scope.labels.get_mangled(label, true),
  10564. walk(stat)
  10565. ];
  10566. return walk(stat);
  10567. },
  10568. "break": _breacont,
  10569. "continue": _breacont,
  10570. "var": _vardefs,
  10571. "const": _vardefs,
  10572. "name": function(name) {
  10573. return get_define(name) || [ this[0], get_mangled(name) ];
  10574. },
  10575. "try": function(t, c, f) {
  10576. return [ this[0],
  10577. MAP(t, walk),
  10578. c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,
  10579. f != null ? MAP(f, walk) : null ];
  10580. },
  10581. "toplevel": function(body) {
  10582. var self = this;
  10583. return with_scope(self.scope, function(){
  10584. return [ self[0], MAP(body, walk) ];
  10585. });
  10586. },
  10587. "directive": function() {
  10588. return MAP.at_top(this);
  10589. }
  10590. }, function() {
  10591. return walk(ast_add_scope(ast));
  10592. });
  10593. };
  10594. /* -----[
  10595. - compress foo["bar"] into foo.bar,
  10596. - remove block brackets {} where possible
  10597. - join consecutive var declarations
  10598. - various optimizations for IFs:
  10599. - if (cond) foo(); else bar(); ==> cond?foo():bar();
  10600. - if (cond) foo(); ==> cond&&foo();
  10601. - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
  10602. - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
  10603. ]----- */
  10604. var warn = function(){};
  10605. function best_of(ast1, ast2) {
  10606. return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
  10607. };
  10608. function last_stat(b) {
  10609. if (b[0] == "block" && b[1] && b[1].length > 0)
  10610. return b[1][b[1].length - 1];
  10611. return b;
  10612. }
  10613. function aborts(t) {
  10614. if (t) switch (last_stat(t)[0]) {
  10615. case "return":
  10616. case "break":
  10617. case "continue":
  10618. case "throw":
  10619. return true;
  10620. }
  10621. };
  10622. function boolean_expr(expr) {
  10623. return ( (expr[0] == "unary-prefix"
  10624. && member(expr[1], [ "!", "delete" ])) ||
  10625. (expr[0] == "binary"
  10626. && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) ||
  10627. (expr[0] == "binary"
  10628. && member(expr[1], [ "&&", "||" ])
  10629. && boolean_expr(expr[2])
  10630. && boolean_expr(expr[3])) ||
  10631. (expr[0] == "conditional"
  10632. && boolean_expr(expr[2])
  10633. && boolean_expr(expr[3])) ||
  10634. (expr[0] == "assign"
  10635. && expr[1] === true
  10636. && boolean_expr(expr[3])) ||
  10637. (expr[0] == "seq"
  10638. && boolean_expr(expr[expr.length - 1]))
  10639. );
  10640. };
  10641. function empty(b) {
  10642. return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
  10643. };
  10644. function is_string(node) {
  10645. return (node[0] == "string" ||
  10646. node[0] == "unary-prefix" && node[1] == "typeof" ||
  10647. node[0] == "binary" && node[1] == "+" &&
  10648. (is_string(node[2]) || is_string(node[3])));
  10649. };
  10650. var when_constant = (function(){
  10651. var $NOT_CONSTANT = {};
  10652. // this can only evaluate constant expressions. If it finds anything
  10653. // not constant, it throws $NOT_CONSTANT.
  10654. function evaluate(expr) {
  10655. switch (expr[0]) {
  10656. case "string":
  10657. case "num":
  10658. return expr[1];
  10659. case "name":
  10660. case "atom":
  10661. switch (expr[1]) {
  10662. case "true": return true;
  10663. case "false": return false;
  10664. case "null": return null;
  10665. }
  10666. break;
  10667. case "unary-prefix":
  10668. switch (expr[1]) {
  10669. case "!": return !evaluate(expr[2]);
  10670. case "typeof": return typeof evaluate(expr[2]);
  10671. case "~": return ~evaluate(expr[2]);
  10672. case "-": return -evaluate(expr[2]);
  10673. case "+": return +evaluate(expr[2]);
  10674. }
  10675. break;
  10676. case "binary":
  10677. var left = expr[2], right = expr[3];
  10678. switch (expr[1]) {
  10679. case "&&" : return evaluate(left) && evaluate(right);
  10680. case "||" : return evaluate(left) || evaluate(right);
  10681. case "|" : return evaluate(left) | evaluate(right);
  10682. case "&" : return evaluate(left) & evaluate(right);
  10683. case "^" : return evaluate(left) ^ evaluate(right);
  10684. case "+" : return evaluate(left) + evaluate(right);
  10685. case "*" : return evaluate(left) * evaluate(right);
  10686. case "/" : return evaluate(left) / evaluate(right);
  10687. case "%" : return evaluate(left) % evaluate(right);
  10688. case "-" : return evaluate(left) - evaluate(right);
  10689. case "<<" : return evaluate(left) << evaluate(right);
  10690. case ">>" : return evaluate(left) >> evaluate(right);
  10691. case ">>>" : return evaluate(left) >>> evaluate(right);
  10692. case "==" : return evaluate(left) == evaluate(right);
  10693. case "===" : return evaluate(left) === evaluate(right);
  10694. case "!=" : return evaluate(left) != evaluate(right);
  10695. case "!==" : return evaluate(left) !== evaluate(right);
  10696. case "<" : return evaluate(left) < evaluate(right);
  10697. case "<=" : return evaluate(left) <= evaluate(right);
  10698. case ">" : return evaluate(left) > evaluate(right);
  10699. case ">=" : return evaluate(left) >= evaluate(right);
  10700. case "in" : return evaluate(left) in evaluate(right);
  10701. case "instanceof" : return evaluate(left) instanceof evaluate(right);
  10702. }
  10703. }
  10704. throw $NOT_CONSTANT;
  10705. };
  10706. return function(expr, yes, no) {
  10707. try {
  10708. var val = evaluate(expr), ast;
  10709. switch (typeof val) {
  10710. case "string": ast = [ "string", val ]; break;
  10711. case "number": ast = [ "num", val ]; break;
  10712. case "boolean": ast = [ "name", String(val) ]; break;
  10713. default:
  10714. if (val === null) { ast = [ "atom", "null" ]; break; }
  10715. throw new Error("Can't handle constant of type: " + (typeof val));
  10716. }
  10717. return yes.call(expr, ast, val);
  10718. } catch(ex) {
  10719. if (ex === $NOT_CONSTANT) {
  10720. if (expr[0] == "binary"
  10721. && (expr[1] == "===" || expr[1] == "!==")
  10722. && ((is_string(expr[2]) && is_string(expr[3]))
  10723. || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {
  10724. expr[1] = expr[1].substr(0, 2);
  10725. }
  10726. else if (no && expr[0] == "binary"
  10727. && (expr[1] == "||" || expr[1] == "&&")) {
  10728. // the whole expression is not constant but the lval may be...
  10729. try {
  10730. var lval = evaluate(expr[2]);
  10731. expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) ||
  10732. (expr[1] == "||" && (lval ? lval : expr[3])) ||
  10733. expr);
  10734. } catch(ex2) {
  10735. // IGNORE... lval is not constant
  10736. }
  10737. }
  10738. return no ? no.call(expr, expr) : null;
  10739. }
  10740. else throw ex;
  10741. }
  10742. };
  10743. })();
  10744. function warn_unreachable(ast) {
  10745. if (!empty(ast))
  10746. warn("Dropping unreachable code: " + gen_code(ast, true));
  10747. };
  10748. function prepare_ifs(ast) {
  10749. var w = ast_walker(), walk = w.walk;
  10750. // In this first pass, we rewrite ifs which abort with no else with an
  10751. // if-else. For example:
  10752. //
  10753. // if (x) {
  10754. // blah();
  10755. // return y;
  10756. // }
  10757. // foobar();
  10758. //
  10759. // is rewritten into:
  10760. //
  10761. // if (x) {
  10762. // blah();
  10763. // return y;
  10764. // } else {
  10765. // foobar();
  10766. // }
  10767. function redo_if(statements) {
  10768. statements = MAP(statements, walk);
  10769. for (var i = 0; i < statements.length; ++i) {
  10770. var fi = statements[i];
  10771. if (fi[0] != "if") continue;
  10772. if (fi[3]) continue;
  10773. var t = fi[2];
  10774. if (!aborts(t)) continue;
  10775. var conditional = walk(fi[1]);
  10776. var e_body = redo_if(statements.slice(i + 1));
  10777. var e = e_body.length == 1 ? e_body[0] : [ "block", e_body ];
  10778. return statements.slice(0, i).concat([ [
  10779. fi[0], // "if"
  10780. conditional, // conditional
  10781. t, // then
  10782. e // else
  10783. ] ]);
  10784. }
  10785. return statements;
  10786. };
  10787. function redo_if_lambda(name, args, body) {
  10788. body = redo_if(body);
  10789. return [ this[0], name, args, body ];
  10790. };
  10791. function redo_if_block(statements) {
  10792. return [ this[0], statements != null ? redo_if(statements) : null ];
  10793. };
  10794. return w.with_walkers({
  10795. "defun": redo_if_lambda,
  10796. "function": redo_if_lambda,
  10797. "block": redo_if_block,
  10798. "splice": redo_if_block,
  10799. "toplevel": function(statements) {
  10800. return [ this[0], redo_if(statements) ];
  10801. },
  10802. "try": function(t, c, f) {
  10803. return [
  10804. this[0],
  10805. redo_if(t),
  10806. c != null ? [ c[0], redo_if(c[1]) ] : null,
  10807. f != null ? redo_if(f) : null
  10808. ];
  10809. }
  10810. }, function() {
  10811. return walk(ast);
  10812. });
  10813. };
  10814. function for_side_effects(ast, handler) {
  10815. var w = ast_walker(), walk = w.walk;
  10816. var $stop = {}, $restart = {};
  10817. function stop() { throw $stop };
  10818. function restart() { throw $restart };
  10819. function found(){ return handler.call(this, this, w, stop, restart) };
  10820. function unary(op) {
  10821. if (op == "++" || op == "--")
  10822. return found.apply(this, arguments);
  10823. };
  10824. function binary(op) {
  10825. if (op == "&&" || op == "||")
  10826. return found.apply(this, arguments);
  10827. };
  10828. return w.with_walkers({
  10829. "try": found,
  10830. "throw": found,
  10831. "return": found,
  10832. "new": found,
  10833. "switch": found,
  10834. "break": found,
  10835. "continue": found,
  10836. "assign": found,
  10837. "call": found,
  10838. "if": found,
  10839. "for": found,
  10840. "for-in": found,
  10841. "while": found,
  10842. "do": found,
  10843. "return": found,
  10844. "unary-prefix": unary,
  10845. "unary-postfix": unary,
  10846. "conditional": found,
  10847. "binary": binary,
  10848. "defun": found
  10849. }, function(){
  10850. while (true) try {
  10851. walk(ast);
  10852. break;
  10853. } catch(ex) {
  10854. if (ex === $stop) break;
  10855. if (ex === $restart) continue;
  10856. throw ex;
  10857. }
  10858. });
  10859. };
  10860. function ast_lift_variables(ast) {
  10861. var w = ast_walker(), walk = w.walk, scope;
  10862. function do_body(body, env) {
  10863. var _scope = scope;
  10864. scope = env;
  10865. body = MAP(body, walk);
  10866. var hash = {}, names = MAP(env.names, function(type, name){
  10867. if (type != "var") return MAP.skip;
  10868. if (!env.references(name)) return MAP.skip;
  10869. hash[name] = true;
  10870. return [ name ];
  10871. });
  10872. if (names.length > 0) {
  10873. // looking for assignments to any of these variables.
  10874. // we can save considerable space by moving the definitions
  10875. // in the var declaration.
  10876. for_side_effects([ "block", body ], function(ast, walker, stop, restart) {
  10877. if (ast[0] == "assign"
  10878. && ast[1] === true
  10879. && ast[2][0] == "name"
  10880. && HOP(hash, ast[2][1])) {
  10881. // insert the definition into the var declaration
  10882. for (var i = names.length; --i >= 0;) {
  10883. if (names[i][0] == ast[2][1]) {
  10884. if (names[i][1]) // this name already defined, we must stop
  10885. stop();
  10886. names[i][1] = ast[3]; // definition
  10887. names.push(names.splice(i, 1)[0]);
  10888. break;
  10889. }
  10890. }
  10891. // remove this assignment from the AST.
  10892. var p = walker.parent();
  10893. if (p[0] == "seq") {
  10894. var a = p[2];
  10895. a.unshift(0, p.length);
  10896. p.splice.apply(p, a);
  10897. }
  10898. else if (p[0] == "stat") {
  10899. p.splice(0, p.length, "block"); // empty statement
  10900. }
  10901. else {
  10902. stop();
  10903. }
  10904. restart();
  10905. }
  10906. stop();
  10907. });
  10908. body.unshift([ "var", names ]);
  10909. }
  10910. scope = _scope;
  10911. return body;
  10912. };
  10913. function _vardefs(defs) {
  10914. var ret = null;
  10915. for (var i = defs.length; --i >= 0;) {
  10916. var d = defs[i];
  10917. if (!d[1]) continue;
  10918. d = [ "assign", true, [ "name", d[0] ], d[1] ];
  10919. if (ret == null) ret = d;
  10920. else ret = [ "seq", d, ret ];
  10921. }
  10922. if (ret == null && w.parent()[0] != "for") {
  10923. if (w.parent()[0] == "for-in")
  10924. return [ "name", defs[0][0] ];
  10925. return MAP.skip;
  10926. }
  10927. return [ "stat", ret ];
  10928. };
  10929. function _toplevel(body) {
  10930. return [ this[0], do_body(body, this.scope) ];
  10931. };
  10932. return w.with_walkers({
  10933. "function": function(name, args, body){
  10934. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  10935. args.pop();
  10936. if (!body.scope.references(name)) name = null;
  10937. return [ this[0], name, args, do_body(body, body.scope) ];
  10938. },
  10939. "defun": function(name, args, body){
  10940. if (!scope.references(name)) return MAP.skip;
  10941. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  10942. args.pop();
  10943. return [ this[0], name, args, do_body(body, body.scope) ];
  10944. },
  10945. "var": _vardefs,
  10946. "toplevel": _toplevel
  10947. }, function(){
  10948. return walk(ast_add_scope(ast));
  10949. });
  10950. };
  10951. function ast_squeeze(ast, options) {
  10952. ast = squeeze_1(ast, options);
  10953. ast = squeeze_2(ast, options);
  10954. return ast;
  10955. };
  10956. function squeeze_1(ast, options) {
  10957. options = defaults(options, {
  10958. make_seqs : true,
  10959. dead_code : true,
  10960. no_warnings : false,
  10961. keep_comps : true,
  10962. unsafe : false
  10963. });
  10964. var w = ast_walker(), walk = w.walk, scope;
  10965. function negate(c) {
  10966. var not_c = [ "unary-prefix", "!", c ];
  10967. switch (c[0]) {
  10968. case "unary-prefix":
  10969. return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c;
  10970. case "seq":
  10971. c = slice(c);
  10972. c[c.length - 1] = negate(c[c.length - 1]);
  10973. return c;
  10974. case "conditional":
  10975. return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]);
  10976. case "binary":
  10977. var op = c[1], left = c[2], right = c[3];
  10978. if (!options.keep_comps) switch (op) {
  10979. case "<=" : return [ "binary", ">", left, right ];
  10980. case "<" : return [ "binary", ">=", left, right ];
  10981. case ">=" : return [ "binary", "<", left, right ];
  10982. case ">" : return [ "binary", "<=", left, right ];
  10983. }
  10984. switch (op) {
  10985. case "==" : return [ "binary", "!=", left, right ];
  10986. case "!=" : return [ "binary", "==", left, right ];
  10987. case "===" : return [ "binary", "!==", left, right ];
  10988. case "!==" : return [ "binary", "===", left, right ];
  10989. case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]);
  10990. case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]);
  10991. }
  10992. break;
  10993. }
  10994. return not_c;
  10995. };
  10996. function make_conditional(c, t, e) {
  10997. var make_real_conditional = function() {
  10998. if (c[0] == "unary-prefix" && c[1] == "!") {
  10999. return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
  11000. } else {
  11001. return e ? best_of(
  11002. [ "conditional", c, t, e ],
  11003. [ "conditional", negate(c), e, t ]
  11004. ) : [ "binary", "&&", c, t ];
  11005. }
  11006. };
  11007. // shortcut the conditional if the expression has a constant value
  11008. return when_constant(c, function(ast, val){
  11009. warn_unreachable(val ? e : t);
  11010. return (val ? t : e);
  11011. }, make_real_conditional);
  11012. };
  11013. function rmblock(block) {
  11014. if (block != null && block[0] == "block" && block[1]) {
  11015. if (block[1].length == 1)
  11016. block = block[1][0];
  11017. else if (block[1].length == 0)
  11018. block = [ "block" ];
  11019. }
  11020. return block;
  11021. };
  11022. function _lambda(name, args, body) {
  11023. return [ this[0], name, args, tighten(body, "lambda") ];
  11024. };
  11025. // this function does a few things:
  11026. // 1. discard useless blocks
  11027. // 2. join consecutive var declarations
  11028. // 3. remove obviously dead code
  11029. // 4. transform consecutive statements using the comma operator
  11030. // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }
  11031. function tighten(statements, block_type) {
  11032. statements = MAP(statements, walk);
  11033. statements = statements.reduce(function(a, stat){
  11034. if (stat[0] == "block") {
  11035. if (stat[1]) {
  11036. a.push.apply(a, stat[1]);
  11037. }
  11038. } else {
  11039. a.push(stat);
  11040. }
  11041. return a;
  11042. }, []);
  11043. statements = (function(a, prev){
  11044. statements.forEach(function(cur){
  11045. if (prev && ((cur[0] == "var" && prev[0] == "var") ||
  11046. (cur[0] == "const" && prev[0] == "const"))) {
  11047. prev[1] = prev[1].concat(cur[1]);
  11048. } else {
  11049. a.push(cur);
  11050. prev = cur;
  11051. }
  11052. });
  11053. return a;
  11054. })([]);
  11055. if (options.dead_code) statements = (function(a, has_quit){
  11056. statements.forEach(function(st){
  11057. if (has_quit) {
  11058. if (st[0] == "function" || st[0] == "defun") {
  11059. a.push(st);
  11060. }
  11061. else if (st[0] == "var" || st[0] == "const") {
  11062. if (!options.no_warnings)
  11063. warn("Variables declared in unreachable code");
  11064. st[1] = MAP(st[1], function(def){
  11065. if (def[1] && !options.no_warnings)
  11066. warn_unreachable([ "assign", true, [ "name", def[0] ], def[1] ]);
  11067. return [ def[0] ];
  11068. });
  11069. a.push(st);
  11070. }
  11071. else if (!options.no_warnings)
  11072. warn_unreachable(st);
  11073. }
  11074. else {
  11075. a.push(st);
  11076. if (member(st[0], [ "return", "throw", "break", "continue" ]))
  11077. has_quit = true;
  11078. }
  11079. });
  11080. return a;
  11081. })([]);
  11082. if (options.make_seqs) statements = (function(a, prev) {
  11083. statements.forEach(function(cur){
  11084. if (prev && prev[0] == "stat" && cur[0] == "stat") {
  11085. prev[1] = [ "seq", prev[1], cur[1] ];
  11086. } else {
  11087. a.push(cur);
  11088. prev = cur;
  11089. }
  11090. });
  11091. if (a.length >= 2
  11092. && a[a.length-2][0] == "stat"
  11093. && (a[a.length-1][0] == "return" || a[a.length-1][0] == "throw")
  11094. && a[a.length-1][1])
  11095. {
  11096. a.splice(a.length - 2, 2,
  11097. [ a[a.length-1][0],
  11098. [ "seq", a[a.length-2][1], a[a.length-1][1] ]]);
  11099. }
  11100. return a;
  11101. })([]);
  11102. // this increases jQuery by 1K. Probably not such a good idea after all..
  11103. // part of this is done in prepare_ifs anyway.
  11104. // if (block_type == "lambda") statements = (function(i, a, stat){
  11105. // while (i < statements.length) {
  11106. // stat = statements[i++];
  11107. // if (stat[0] == "if" && !stat[3]) {
  11108. // if (stat[2][0] == "return" && stat[2][1] == null) {
  11109. // a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
  11110. // break;
  11111. // }
  11112. // var last = last_stat(stat[2]);
  11113. // if (last[0] == "return" && last[1] == null) {
  11114. // a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ]));
  11115. // break;
  11116. // }
  11117. // }
  11118. // a.push(stat);
  11119. // }
  11120. // return a;
  11121. // })(0, []);
  11122. return statements;
  11123. };
  11124. function make_if(c, t, e) {
  11125. return when_constant(c, function(ast, val){
  11126. if (val) {
  11127. t = walk(t);
  11128. warn_unreachable(e);
  11129. return t || [ "block" ];
  11130. } else {
  11131. e = walk(e);
  11132. warn_unreachable(t);
  11133. return e || [ "block" ];
  11134. }
  11135. }, function() {
  11136. return make_real_if(c, t, e);
  11137. });
  11138. };
  11139. function abort_else(c, t, e) {
  11140. var ret = [ [ "if", negate(c), e ] ];
  11141. if (t[0] == "block") {
  11142. if (t[1]) ret = ret.concat(t[1]);
  11143. } else {
  11144. ret.push(t);
  11145. }
  11146. return walk([ "block", ret ]);
  11147. };
  11148. function make_real_if(c, t, e) {
  11149. c = walk(c);
  11150. t = walk(t);
  11151. e = walk(e);
  11152. if (empty(e) && empty(t))
  11153. return [ "stat", c ];
  11154. if (empty(t)) {
  11155. c = negate(c);
  11156. t = e;
  11157. e = null;
  11158. } else if (empty(e)) {
  11159. e = null;
  11160. } else {
  11161. // if we have both else and then, maybe it makes sense to switch them?
  11162. (function(){
  11163. var a = gen_code(c);
  11164. var n = negate(c);
  11165. var b = gen_code(n);
  11166. if (b.length < a.length) {
  11167. var tmp = t;
  11168. t = e;
  11169. e = tmp;
  11170. c = n;
  11171. }
  11172. })();
  11173. }
  11174. var ret = [ "if", c, t, e ];
  11175. if (t[0] == "if" && empty(t[3]) && empty(e)) {
  11176. ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ]));
  11177. }
  11178. else if (t[0] == "stat") {
  11179. if (e) {
  11180. if (e[0] == "stat")
  11181. ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
  11182. else if (aborts(e))
  11183. ret = abort_else(c, t, e);
  11184. }
  11185. else {
  11186. ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
  11187. }
  11188. }
  11189. else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) {
  11190. ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
  11191. }
  11192. else if (e && aborts(t)) {
  11193. ret = [ [ "if", c, t ] ];
  11194. if (e[0] == "block") {
  11195. if (e[1]) ret = ret.concat(e[1]);
  11196. }
  11197. else {
  11198. ret.push(e);
  11199. }
  11200. ret = walk([ "block", ret ]);
  11201. }
  11202. else if (t && aborts(e)) {
  11203. ret = abort_else(c, t, e);
  11204. }
  11205. return ret;
  11206. };
  11207. function _do_while(cond, body) {
  11208. return when_constant(cond, function(cond, val){
  11209. if (!val) {
  11210. warn_unreachable(body);
  11211. return [ "block" ];
  11212. } else {
  11213. return [ "for", null, null, null, walk(body) ];
  11214. }
  11215. });
  11216. };
  11217. return w.with_walkers({
  11218. "sub": function(expr, subscript) {
  11219. if (subscript[0] == "string") {
  11220. var name = subscript[1];
  11221. if (is_identifier(name))
  11222. return [ "dot", walk(expr), name ];
  11223. else if (/^[1-9][0-9]*$/.test(name) || name === "0")
  11224. return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ];
  11225. }
  11226. },
  11227. "if": make_if,
  11228. "toplevel": function(body) {
  11229. return [ "toplevel", tighten(body) ];
  11230. },
  11231. "switch": function(expr, body) {
  11232. var last = body.length - 1;
  11233. return [ "switch", walk(expr), MAP(body, function(branch, i){
  11234. var block = tighten(branch[1]);
  11235. if (i == last && block.length > 0) {
  11236. var node = block[block.length - 1];
  11237. if (node[0] == "break" && !node[1])
  11238. block.pop();
  11239. }
  11240. return [ branch[0] ? walk(branch[0]) : null, block ];
  11241. }) ];
  11242. },
  11243. "function": _lambda,
  11244. "defun": _lambda,
  11245. "block": function(body) {
  11246. if (body) return rmblock([ "block", tighten(body) ]);
  11247. },
  11248. "binary": function(op, left, right) {
  11249. return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){
  11250. return best_of(walk(c), this);
  11251. }, function no() {
  11252. return function(){
  11253. if(op != "==" && op != "!=") return;
  11254. var l = walk(left), r = walk(right);
  11255. if(l && l[0] == "unary-prefix" && l[1] == "!" && l[2][0] == "num")
  11256. left = ['num', +!l[2][1]];
  11257. else if (r && r[0] == "unary-prefix" && r[1] == "!" && r[2][0] == "num")
  11258. right = ['num', +!r[2][1]];
  11259. return ["binary", op, left, right];
  11260. }() || this;
  11261. });
  11262. },
  11263. "conditional": function(c, t, e) {
  11264. return make_conditional(walk(c), walk(t), walk(e));
  11265. },
  11266. "try": function(t, c, f) {
  11267. return [
  11268. "try",
  11269. tighten(t),
  11270. c != null ? [ c[0], tighten(c[1]) ] : null,
  11271. f != null ? tighten(f) : null
  11272. ];
  11273. },
  11274. "unary-prefix": function(op, expr) {
  11275. expr = walk(expr);
  11276. var ret = [ "unary-prefix", op, expr ];
  11277. if (op == "!")
  11278. ret = best_of(ret, negate(expr));
  11279. return when_constant(ret, function(ast, val){
  11280. return walk(ast); // it's either true or false, so minifies to !0 or !1
  11281. }, function() { return ret });
  11282. },
  11283. "name": function(name) {
  11284. switch (name) {
  11285. case "true": return [ "unary-prefix", "!", [ "num", 0 ]];
  11286. case "false": return [ "unary-prefix", "!", [ "num", 1 ]];
  11287. }
  11288. },
  11289. "while": _do_while,
  11290. "assign": function(op, lvalue, rvalue) {
  11291. lvalue = walk(lvalue);
  11292. rvalue = walk(rvalue);
  11293. var okOps = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  11294. if (op === true && lvalue[0] === "name" && rvalue[0] === "binary" &&
  11295. ~okOps.indexOf(rvalue[1]) && rvalue[2][0] === "name" &&
  11296. rvalue[2][1] === lvalue[1]) {
  11297. return [ this[0], rvalue[1], lvalue, rvalue[3] ]
  11298. }
  11299. return [ this[0], op, lvalue, rvalue ];
  11300. },
  11301. "call": function(expr, args) {
  11302. expr = walk(expr);
  11303. if (options.unsafe && expr[0] == "dot" && expr[1][0] == "string" && expr[2] == "toString") {
  11304. return expr[1];
  11305. }
  11306. return [ this[0], expr, MAP(args, walk) ];
  11307. },
  11308. "num": function (num) {
  11309. if (!isFinite(num))
  11310. return [ "binary", "/", num === 1 / 0
  11311. ? [ "num", 1 ] : num === -1 / 0
  11312. ? [ "unary-prefix", "-", [ "num", 1 ] ]
  11313. : [ "num", 0 ], [ "num", 0 ] ];
  11314. return [ this[0], num ];
  11315. }
  11316. }, function() {
  11317. return walk(prepare_ifs(walk(prepare_ifs(ast))));
  11318. });
  11319. };
  11320. function squeeze_2(ast, options) {
  11321. var w = ast_walker(), walk = w.walk, scope;
  11322. function with_scope(s, cont) {
  11323. var save = scope, ret;
  11324. scope = s;
  11325. ret = cont();
  11326. scope = save;
  11327. return ret;
  11328. };
  11329. function lambda(name, args, body) {
  11330. return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  11331. };
  11332. return w.with_walkers({
  11333. "directive": function(dir) {
  11334. if (scope.active_directive(dir))
  11335. return [ "block" ];
  11336. scope.directives.push(dir);
  11337. },
  11338. "toplevel": function(body) {
  11339. return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
  11340. },
  11341. "function": lambda,
  11342. "defun": lambda
  11343. }, function(){
  11344. return walk(ast_add_scope(ast));
  11345. });
  11346. };
  11347. /* -----[ re-generate code from the AST ]----- */
  11348. var DOT_CALL_NO_PARENS = jsp.array_to_hash([
  11349. "name",
  11350. "array",
  11351. "object",
  11352. "string",
  11353. "dot",
  11354. "sub",
  11355. "call",
  11356. "regexp",
  11357. "defun"
  11358. ]);
  11359. function make_string(str, ascii_only) {
  11360. var dq = 0, sq = 0;
  11361. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
  11362. switch (s) {
  11363. case "\\": return "\\\\";
  11364. case "\b": return "\\b";
  11365. case "\f": return "\\f";
  11366. case "\n": return "\\n";
  11367. case "\r": return "\\r";
  11368. case "\u2028": return "\\u2028";
  11369. case "\u2029": return "\\u2029";
  11370. case '"': ++dq; return '"';
  11371. case "'": ++sq; return "'";
  11372. case "\0": return "\\0";
  11373. }
  11374. return s;
  11375. });
  11376. if (ascii_only) str = to_ascii(str);
  11377. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
  11378. else return '"' + str.replace(/\x22/g, '\\"') + '"';
  11379. };
  11380. function to_ascii(str) {
  11381. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  11382. var code = ch.charCodeAt(0).toString(16);
  11383. while (code.length < 4) code = "0" + code;
  11384. return "\\u" + code;
  11385. });
  11386. };
  11387. var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]);
  11388. function gen_code(ast, options) {
  11389. options = defaults(options, {
  11390. indent_start : 0,
  11391. indent_level : 4,
  11392. quote_keys : false,
  11393. space_colon : false,
  11394. beautify : false,
  11395. ascii_only : false,
  11396. inline_script: false
  11397. });
  11398. var beautify = !!options.beautify;
  11399. var indentation = 0,
  11400. newline = beautify ? "\n" : "",
  11401. space = beautify ? " " : "";
  11402. function encode_string(str) {
  11403. var ret = make_string(str, options.ascii_only);
  11404. if (options.inline_script)
  11405. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  11406. return ret;
  11407. };
  11408. function make_name(name) {
  11409. name = name.toString();
  11410. if (options.ascii_only)
  11411. name = to_ascii(name);
  11412. return name;
  11413. };
  11414. function indent(line) {
  11415. if (line == null)
  11416. line = "";
  11417. if (beautify)
  11418. line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line;
  11419. return line;
  11420. };
  11421. function with_indent(cont, incr) {
  11422. if (incr == null) incr = 1;
  11423. indentation += incr;
  11424. try { return cont.apply(null, slice(arguments, 1)); }
  11425. finally { indentation -= incr; }
  11426. };
  11427. function last_char(str) {
  11428. str = str.toString();
  11429. return str.charAt(str.length - 1);
  11430. };
  11431. function first_char(str) {
  11432. return str.toString().charAt(0);
  11433. };
  11434. function add_spaces(a) {
  11435. if (beautify)
  11436. return a.join(" ");
  11437. var b = [];
  11438. for (var i = 0; i < a.length; ++i) {
  11439. var next = a[i + 1];
  11440. b.push(a[i]);
  11441. if (next &&
  11442. ((is_identifier_char(last_char(a[i])) && (is_identifier_char(first_char(next))
  11443. || first_char(next) == "\\")) ||
  11444. (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString()) ||
  11445. last_char(a[i]) == "/" && first_char(next) == "/"))) {
  11446. b.push(" ");
  11447. }
  11448. }
  11449. return b.join("");
  11450. };
  11451. function add_commas(a) {
  11452. return a.join("," + space);
  11453. };
  11454. function parenthesize(expr) {
  11455. var gen = make(expr);
  11456. for (var i = 1; i < arguments.length; ++i) {
  11457. var el = arguments[i];
  11458. if ((el instanceof Function && el(expr)) || expr[0] == el)
  11459. return "(" + gen + ")";
  11460. }
  11461. return gen;
  11462. };
  11463. function best_of(a) {
  11464. if (a.length == 1) {
  11465. return a[0];
  11466. }
  11467. if (a.length == 2) {
  11468. var b = a[1];
  11469. a = a[0];
  11470. return a.length <= b.length ? a : b;
  11471. }
  11472. return best_of([ a[0], best_of(a.slice(1)) ]);
  11473. };
  11474. function needs_parens(expr) {
  11475. if (expr[0] == "function" || expr[0] == "object") {
  11476. // dot/call on a literal function requires the
  11477. // function literal itself to be parenthesized
  11478. // only if it's the first "thing" in a
  11479. // statement. This means that the parent is
  11480. // "stat", but it could also be a "seq" and
  11481. // we're the first in this "seq" and the
  11482. // parent is "stat", and so on. Messy stuff,
  11483. // but it worths the trouble.
  11484. var a = slice(w.stack()), self = a.pop(), p = a.pop();
  11485. while (p) {
  11486. if (p[0] == "stat") return true;
  11487. if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) ||
  11488. ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) {
  11489. self = p;
  11490. p = a.pop();
  11491. } else {
  11492. return false;
  11493. }
  11494. }
  11495. }
  11496. return !HOP(DOT_CALL_NO_PARENS, expr[0]);
  11497. };
  11498. function make_num(num) {
  11499. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  11500. if (Math.floor(num) === num) {
  11501. if (num >= 0) {
  11502. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  11503. "0" + num.toString(8)); // same.
  11504. } else {
  11505. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  11506. "-0" + (-num).toString(8)); // same.
  11507. }
  11508. if ((m = /^(.*?)(0+)$/.exec(num))) {
  11509. a.push(m[1] + "e" + m[2].length);
  11510. }
  11511. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  11512. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  11513. str.substr(str.indexOf(".")));
  11514. }
  11515. return best_of(a);
  11516. };
  11517. var w = ast_walker();
  11518. var make = w.walk;
  11519. return w.with_walkers({
  11520. "string": encode_string,
  11521. "num": make_num,
  11522. "name": make_name,
  11523. "debugger": function(){ return "debugger;" },
  11524. "toplevel": function(statements) {
  11525. return make_block_statements(statements)
  11526. .join(newline + newline);
  11527. },
  11528. "splice": function(statements) {
  11529. var parent = w.parent();
  11530. if (HOP(SPLICE_NEEDS_BRACKETS, parent)) {
  11531. // we need block brackets in this case
  11532. return make_block.apply(this, arguments);
  11533. } else {
  11534. return MAP(make_block_statements(statements, true),
  11535. function(line, i) {
  11536. // the first line is already indented
  11537. return i > 0 ? indent(line) : line;
  11538. }).join(newline);
  11539. }
  11540. },
  11541. "block": make_block,
  11542. "var": function(defs) {
  11543. return "var " + add_commas(MAP(defs, make_1vardef)) + ";";
  11544. },
  11545. "const": function(defs) {
  11546. return "const " + add_commas(MAP(defs, make_1vardef)) + ";";
  11547. },
  11548. "try": function(tr, ca, fi) {
  11549. var out = [ "try", make_block(tr) ];
  11550. if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
  11551. if (fi) out.push("finally", make_block(fi));
  11552. return add_spaces(out);
  11553. },
  11554. "throw": function(expr) {
  11555. return add_spaces([ "throw", make(expr) ]) + ";";
  11556. },
  11557. "new": function(ctor, args) {
  11558. args = args.length > 0 ? "(" + add_commas(MAP(args, function(expr){
  11559. return parenthesize(expr, "seq");
  11560. })) + ")" : "";
  11561. return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
  11562. var w = ast_walker(), has_call = {};
  11563. try {
  11564. w.with_walkers({
  11565. "call": function() { throw has_call },
  11566. "function": function() { return this }
  11567. }, function(){
  11568. w.walk(expr);
  11569. });
  11570. } catch(ex) {
  11571. if (ex === has_call)
  11572. return true;
  11573. throw ex;
  11574. }
  11575. }) + args ]);
  11576. },
  11577. "switch": function(expr, body) {
  11578. return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
  11579. },
  11580. "break": function(label) {
  11581. var out = "break";
  11582. if (label != null)
  11583. out += " " + make_name(label);
  11584. return out + ";";
  11585. },
  11586. "continue": function(label) {
  11587. var out = "continue";
  11588. if (label != null)
  11589. out += " " + make_name(label);
  11590. return out + ";";
  11591. },
  11592. "conditional": function(co, th, el) {
  11593. return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
  11594. parenthesize(th, "seq"), ":",
  11595. parenthesize(el, "seq") ]);
  11596. },
  11597. "assign": function(op, lvalue, rvalue) {
  11598. if (op && op !== true) op += "=";
  11599. else op = "=";
  11600. return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]);
  11601. },
  11602. "dot": function(expr) {
  11603. var out = make(expr), i = 1;
  11604. if (expr[0] == "num") {
  11605. if (!/[a-f.]/i.test(out))
  11606. out += ".";
  11607. } else if (expr[0] != "function" && needs_parens(expr))
  11608. out = "(" + out + ")";
  11609. while (i < arguments.length)
  11610. out += "." + make_name(arguments[i++]);
  11611. return out;
  11612. },
  11613. "call": function(func, args) {
  11614. var f = make(func);
  11615. if (f.charAt(0) != "(" && needs_parens(func))
  11616. f = "(" + f + ")";
  11617. return f + "(" + add_commas(MAP(args, function(expr){
  11618. return parenthesize(expr, "seq");
  11619. })) + ")";
  11620. },
  11621. "function": make_function,
  11622. "defun": make_function,
  11623. "if": function(co, th, el) {
  11624. var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
  11625. if (el) {
  11626. out.push("else", make(el));
  11627. }
  11628. return add_spaces(out);
  11629. },
  11630. "for": function(init, cond, step, block) {
  11631. var out = [ "for" ];
  11632. init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
  11633. cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
  11634. step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
  11635. var args = init + cond + step;
  11636. if (args == "; ; ") args = ";;";
  11637. out.push("(" + args + ")", make(block));
  11638. return add_spaces(out);
  11639. },
  11640. "for-in": function(vvar, key, hash, block) {
  11641. return add_spaces([ "for", "(" +
  11642. (vvar ? make(vvar).replace(/;+$/, "") : make(key)),
  11643. "in",
  11644. make(hash) + ")", make(block) ]);
  11645. },
  11646. "while": function(condition, block) {
  11647. return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
  11648. },
  11649. "do": function(condition, block) {
  11650. return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
  11651. },
  11652. "return": function(expr) {
  11653. var out = [ "return" ];
  11654. if (expr != null) out.push(make(expr));
  11655. return add_spaces(out) + ";";
  11656. },
  11657. "binary": function(operator, lvalue, rvalue) {
  11658. var left = make(lvalue), right = make(rvalue);
  11659. // XXX: I'm pretty sure other cases will bite here.
  11660. // we need to be smarter.
  11661. // adding parens all the time is the safest bet.
  11662. if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
  11663. lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]] ||
  11664. lvalue[0] == "function" && needs_parens(this)) {
  11665. left = "(" + left + ")";
  11666. }
  11667. if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
  11668. rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&
  11669. !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) {
  11670. right = "(" + right + ")";
  11671. }
  11672. else if (!beautify && options.inline_script && (operator == "<" || operator == "<<")
  11673. && rvalue[0] == "regexp" && /^script/i.test(rvalue[1])) {
  11674. right = " " + right;
  11675. }
  11676. return add_spaces([ left, operator, right ]);
  11677. },
  11678. "unary-prefix": function(operator, expr) {
  11679. var val = make(expr);
  11680. if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  11681. val = "(" + val + ")";
  11682. return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
  11683. },
  11684. "unary-postfix": function(operator, expr) {
  11685. var val = make(expr);
  11686. if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  11687. val = "(" + val + ")";
  11688. return val + operator;
  11689. },
  11690. "sub": function(expr, subscript) {
  11691. var hash = make(expr);
  11692. if (needs_parens(expr))
  11693. hash = "(" + hash + ")";
  11694. return hash + "[" + make(subscript) + "]";
  11695. },
  11696. "object": function(props) {
  11697. var obj_needs_parens = needs_parens(this);
  11698. if (props.length == 0)
  11699. return obj_needs_parens ? "({})" : "{}";
  11700. var out = "{" + newline + with_indent(function(){
  11701. return MAP(props, function(p){
  11702. if (p.length == 3) {
  11703. // getter/setter. The name is in p[0], the arg.list in p[1][2], the
  11704. // body in p[1][3] and type ("get" / "set") in p[2].
  11705. return indent(make_function(p[0], p[1][2], p[1][3], p[2], true));
  11706. }
  11707. var key = p[0], val = parenthesize(p[1], "seq");
  11708. if (options.quote_keys) {
  11709. key = encode_string(key);
  11710. } else if ((typeof key == "number" || !beautify && +key + "" == key)
  11711. && parseFloat(key) >= 0) {
  11712. key = make_num(+key);
  11713. } else if (!is_identifier(key)) {
  11714. key = encode_string(key);
  11715. }
  11716. return indent(add_spaces(beautify && options.space_colon
  11717. ? [ key, ":", val ]
  11718. : [ key + ":", val ]));
  11719. }).join("," + newline);
  11720. }) + newline + indent("}");
  11721. return obj_needs_parens ? "(" + out + ")" : out;
  11722. },
  11723. "regexp": function(rx, mods) {
  11724. if (options.ascii_only) rx = to_ascii(rx);
  11725. return "/" + rx + "/" + mods;
  11726. },
  11727. "array": function(elements) {
  11728. if (elements.length == 0) return "[]";
  11729. return add_spaces([ "[", add_commas(MAP(elements, function(el, i){
  11730. if (!beautify && el[0] == "atom" && el[1] == "undefined") return i === elements.length - 1 ? "," : "";
  11731. return parenthesize(el, "seq");
  11732. })), "]" ]);
  11733. },
  11734. "stat": function(stmt) {
  11735. return stmt != null
  11736. ? make(stmt).replace(/;*\s*$/, ";")
  11737. : ";";
  11738. },
  11739. "seq": function() {
  11740. return add_commas(MAP(slice(arguments), make));
  11741. },
  11742. "label": function(name, block) {
  11743. return add_spaces([ make_name(name), ":", make(block) ]);
  11744. },
  11745. "with": function(expr, block) {
  11746. return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
  11747. },
  11748. "atom": function(name) {
  11749. return make_name(name);
  11750. },
  11751. "directive": function(dir) {
  11752. return make_string(dir) + ";";
  11753. }
  11754. }, function(){ return make(ast) });
  11755. // The squeezer replaces "block"-s that contain only a single
  11756. // statement with the statement itself; technically, the AST
  11757. // is correct, but this can create problems when we output an
  11758. // IF having an ELSE clause where the THEN clause ends in an
  11759. // IF *without* an ELSE block (then the outer ELSE would refer
  11760. // to the inner IF). This function checks for this case and
  11761. // adds the block brackets if needed.
  11762. function make_then(th) {
  11763. if (th == null) return ";";
  11764. if (th[0] == "do") {
  11765. // https://github.com/mishoo/UglifyJS/issues/#issue/57
  11766. // IE croaks with "syntax error" on code like this:
  11767. // if (foo) do ... while(cond); else ...
  11768. // we need block brackets around do/while
  11769. return make_block([ th ]);
  11770. }
  11771. var b = th;
  11772. while (true) {
  11773. var type = b[0];
  11774. if (type == "if") {
  11775. if (!b[3])
  11776. // no else, we must add the block
  11777. return make([ "block", [ th ]]);
  11778. b = b[3];
  11779. }
  11780. else if (type == "while" || type == "do") b = b[2];
  11781. else if (type == "for" || type == "for-in") b = b[4];
  11782. else break;
  11783. }
  11784. return make(th);
  11785. };
  11786. function make_function(name, args, body, keyword, no_parens) {
  11787. var out = keyword || "function";
  11788. if (name) {
  11789. out += " " + make_name(name);
  11790. }
  11791. out += "(" + add_commas(MAP(args, make_name)) + ")";
  11792. out = add_spaces([ out, make_block(body) ]);
  11793. return (!no_parens && needs_parens(this)) ? "(" + out + ")" : out;
  11794. };
  11795. function must_has_semicolon(node) {
  11796. switch (node[0]) {
  11797. case "with":
  11798. case "while":
  11799. return empty(node[2]) || must_has_semicolon(node[2]);
  11800. case "for":
  11801. case "for-in":
  11802. return empty(node[4]) || must_has_semicolon(node[4]);
  11803. case "if":
  11804. if (empty(node[2]) && !node[3]) return true; // `if' with empty `then' and no `else'
  11805. if (node[3]) {
  11806. if (empty(node[3])) return true; // `else' present but empty
  11807. return must_has_semicolon(node[3]); // dive into the `else' branch
  11808. }
  11809. return must_has_semicolon(node[2]); // dive into the `then' branch
  11810. case "directive":
  11811. return true;
  11812. }
  11813. };
  11814. function make_block_statements(statements, noindent) {
  11815. for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
  11816. var stat = statements[i];
  11817. var code = make(stat);
  11818. if (code != ";") {
  11819. if (!beautify && i == last && !must_has_semicolon(stat)) {
  11820. code = code.replace(/;+\s*$/, "");
  11821. }
  11822. a.push(code);
  11823. }
  11824. }
  11825. return noindent ? a : MAP(a, indent);
  11826. };
  11827. function make_switch_block(body) {
  11828. var n = body.length;
  11829. if (n == 0) return "{}";
  11830. return "{" + newline + MAP(body, function(branch, i){
  11831. var has_body = branch[1].length > 0, code = with_indent(function(){
  11832. return indent(branch[0]
  11833. ? add_spaces([ "case", make(branch[0]) + ":" ])
  11834. : "default:");
  11835. }, 0.5) + (has_body ? newline + with_indent(function(){
  11836. return make_block_statements(branch[1]).join(newline);
  11837. }) : "");
  11838. if (!beautify && has_body && i < n - 1)
  11839. code += ";";
  11840. return code;
  11841. }).join(newline) + newline + indent("}");
  11842. };
  11843. function make_block(statements) {
  11844. if (!statements) return ";";
  11845. if (statements.length == 0) return "{}";
  11846. return "{" + newline + with_indent(function(){
  11847. return make_block_statements(statements).join(newline);
  11848. }) + newline + indent("}");
  11849. };
  11850. function make_1vardef(def) {
  11851. var name = def[0], val = def[1];
  11852. if (val != null)
  11853. name = add_spaces([ make_name(name), "=", parenthesize(val, "seq") ]);
  11854. return name;
  11855. };
  11856. };
  11857. function split_lines(code, max_line_length) {
  11858. var splits = [ 0 ];
  11859. jsp.parse(function(){
  11860. var next_token = jsp.tokenizer(code);
  11861. var last_split = 0;
  11862. var prev_token;
  11863. function current_length(tok) {
  11864. return tok.pos - last_split;
  11865. };
  11866. function split_here(tok) {
  11867. last_split = tok.pos;
  11868. splits.push(last_split);
  11869. };
  11870. function custom(){
  11871. var tok = next_token.apply(this, arguments);
  11872. out: {
  11873. if (prev_token) {
  11874. if (prev_token.type == "keyword") break out;
  11875. }
  11876. if (current_length(tok) > max_line_length) {
  11877. switch (tok.type) {
  11878. case "keyword":
  11879. case "atom":
  11880. case "name":
  11881. case "punc":
  11882. split_here(tok);
  11883. break out;
  11884. }
  11885. }
  11886. }
  11887. prev_token = tok;
  11888. return tok;
  11889. };
  11890. custom.context = function() {
  11891. return next_token.context.apply(this, arguments);
  11892. };
  11893. return custom;
  11894. }());
  11895. return splits.map(function(pos, i){
  11896. return code.substring(pos, splits[i + 1] || code.length);
  11897. }).join("\n");
  11898. };
  11899. /* -----[ Utilities ]----- */
  11900. function repeat_string(str, i) {
  11901. if (i <= 0) return "";
  11902. if (i == 1) return str;
  11903. var d = repeat_string(str, i >> 1);
  11904. d += d;
  11905. if (i & 1) d += str;
  11906. return d;
  11907. };
  11908. function defaults(args, defs) {
  11909. var ret = {};
  11910. if (args === true)
  11911. args = {};
  11912. for (var i in defs) if (HOP(defs, i)) {
  11913. ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
  11914. }
  11915. return ret;
  11916. };
  11917. function is_identifier(name) {
  11918. return /^[a-z_$][a-z0-9_$]*$/i.test(name)
  11919. && name != "this"
  11920. && !HOP(jsp.KEYWORDS_ATOM, name)
  11921. && !HOP(jsp.RESERVED_WORDS, name)
  11922. && !HOP(jsp.KEYWORDS, name);
  11923. };
  11924. function HOP(obj, prop) {
  11925. return Object.prototype.hasOwnProperty.call(obj, prop);
  11926. };
  11927. // some utilities
  11928. var MAP;
  11929. (function(){
  11930. MAP = function(a, f, o) {
  11931. var ret = [], top = [], i;
  11932. function doit() {
  11933. var val = f.call(o, a[i], i);
  11934. if (val instanceof AtTop) {
  11935. val = val.v;
  11936. if (val instanceof Splice) {
  11937. top.push.apply(top, val.v);
  11938. } else {
  11939. top.push(val);
  11940. }
  11941. }
  11942. else if (val != skip) {
  11943. if (val instanceof Splice) {
  11944. ret.push.apply(ret, val.v);
  11945. } else {
  11946. ret.push(val);
  11947. }
  11948. }
  11949. };
  11950. if (a instanceof Array) for (i = 0; i < a.length; ++i) doit();
  11951. else for (i in a) if (HOP(a, i)) doit();
  11952. return top.concat(ret);
  11953. };
  11954. MAP.at_top = function(val) { return new AtTop(val) };
  11955. MAP.splice = function(val) { return new Splice(val) };
  11956. var skip = MAP.skip = {};
  11957. function AtTop(val) { this.v = val };
  11958. function Splice(val) { this.v = val };
  11959. })();
  11960. /* -----[ Exports ]----- */
  11961. exports.ast_walker = ast_walker;
  11962. exports.ast_mangle = ast_mangle;
  11963. exports.ast_squeeze = ast_squeeze;
  11964. exports.ast_lift_variables = ast_lift_variables;
  11965. exports.gen_code = gen_code;
  11966. exports.ast_add_scope = ast_add_scope;
  11967. exports.set_logger = function(logger) { warn = logger };
  11968. exports.make_string = make_string;
  11969. exports.split_lines = split_lines;
  11970. exports.MAP = MAP;
  11971. // keep this last!
  11972. exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more;
  11973. // Local variables:
  11974. // js-indent-level: 4
  11975. // End:
  11976. });
  11977. define('uglifyjs/index', ["require", "exports", "module", "./parse-js", "./process", "./consolidator"], function(require, exports, module) {
  11978. //convienence function(src, [options]);
  11979. function uglify(orig_code, options){
  11980. options || (options = {});
  11981. var jsp = uglify.parser;
  11982. var pro = uglify.uglify;
  11983. var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST
  11984. ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names
  11985. ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations
  11986. var final_code = pro.gen_code(ast, options.gen_options); // compressed code here
  11987. return final_code;
  11988. };
  11989. uglify.parser = require("./parse-js");
  11990. uglify.uglify = require("./process");
  11991. uglify.consolidator = require("./consolidator");
  11992. module.exports = uglify
  11993. });/* -*- Mode: js; js-indent-level: 2; -*- */
  11994. /*
  11995. * Copyright 2011 Mozilla Foundation and contributors
  11996. * Licensed under the New BSD license. See LICENSE or:
  11997. * http://opensource.org/licenses/BSD-3-Clause
  11998. */
  11999. define('source-map/array-set', function (require, exports, module) {
  12000. var util = require('./util');
  12001. /**
  12002. * A data structure which is a combination of an array and a set. Adding a new
  12003. * member is O(1), testing for membership is O(1), and finding the index of an
  12004. * element is O(1). Removing elements from the set is not supported. Only
  12005. * strings are supported for membership.
  12006. */
  12007. function ArraySet() {
  12008. this._array = [];
  12009. this._set = {};
  12010. }
  12011. /**
  12012. * Static method for creating ArraySet instances from an existing array.
  12013. */
  12014. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  12015. var set = new ArraySet();
  12016. for (var i = 0, len = aArray.length; i < len; i++) {
  12017. set.add(aArray[i], aAllowDuplicates);
  12018. }
  12019. return set;
  12020. };
  12021. /**
  12022. * Add the given string to this set.
  12023. *
  12024. * @param String aStr
  12025. */
  12026. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  12027. var isDuplicate = this.has(aStr);
  12028. var idx = this._array.length;
  12029. if (!isDuplicate || aAllowDuplicates) {
  12030. this._array.push(aStr);
  12031. }
  12032. if (!isDuplicate) {
  12033. this._set[util.toSetString(aStr)] = idx;
  12034. }
  12035. };
  12036. /**
  12037. * Is the given string a member of this set?
  12038. *
  12039. * @param String aStr
  12040. */
  12041. ArraySet.prototype.has = function ArraySet_has(aStr) {
  12042. return Object.prototype.hasOwnProperty.call(this._set,
  12043. util.toSetString(aStr));
  12044. };
  12045. /**
  12046. * What is the index of the given string in the array?
  12047. *
  12048. * @param String aStr
  12049. */
  12050. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  12051. if (this.has(aStr)) {
  12052. return this._set[util.toSetString(aStr)];
  12053. }
  12054. throw new Error('"' + aStr + '" is not in the set.');
  12055. };
  12056. /**
  12057. * What is the element at the given index?
  12058. *
  12059. * @param Number aIdx
  12060. */
  12061. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  12062. if (aIdx >= 0 && aIdx < this._array.length) {
  12063. return this._array[aIdx];
  12064. }
  12065. throw new Error('No element indexed by ' + aIdx);
  12066. };
  12067. /**
  12068. * Returns the array representation of this set (which has the proper indices
  12069. * indicated by indexOf). Note that this is a copy of the internal array used
  12070. * for storing the members so that no one can mess with internal state.
  12071. */
  12072. ArraySet.prototype.toArray = function ArraySet_toArray() {
  12073. return this._array.slice();
  12074. };
  12075. exports.ArraySet = ArraySet;
  12076. });
  12077. /* -*- Mode: js; js-indent-level: 2; -*- */
  12078. /*
  12079. * Copyright 2011 Mozilla Foundation and contributors
  12080. * Licensed under the New BSD license. See LICENSE or:
  12081. * http://opensource.org/licenses/BSD-3-Clause
  12082. *
  12083. * Based on the Base 64 VLQ implementation in Closure Compiler:
  12084. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  12085. *
  12086. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  12087. * Redistribution and use in source and binary forms, with or without
  12088. * modification, are permitted provided that the following conditions are
  12089. * met:
  12090. *
  12091. * * Redistributions of source code must retain the above copyright
  12092. * notice, this list of conditions and the following disclaimer.
  12093. * * Redistributions in binary form must reproduce the above
  12094. * copyright notice, this list of conditions and the following
  12095. * disclaimer in the documentation and/or other materials provided
  12096. * with the distribution.
  12097. * * Neither the name of Google Inc. nor the names of its
  12098. * contributors may be used to endorse or promote products derived
  12099. * from this software without specific prior written permission.
  12100. *
  12101. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  12102. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  12103. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  12104. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  12105. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  12106. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  12107. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  12108. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  12109. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12110. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  12111. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  12112. */
  12113. define('source-map/base64-vlq', function (require, exports, module) {
  12114. var base64 = require('./base64');
  12115. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  12116. // length quantities we use in the source map spec, the first bit is the sign,
  12117. // the next four bits are the actual value, and the 6th bit is the
  12118. // continuation bit. The continuation bit tells us whether there are more
  12119. // digits in this value following this digit.
  12120. //
  12121. // Continuation
  12122. // | Sign
  12123. // | |
  12124. // V V
  12125. // 101011
  12126. var VLQ_BASE_SHIFT = 5;
  12127. // binary: 100000
  12128. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  12129. // binary: 011111
  12130. var VLQ_BASE_MASK = VLQ_BASE - 1;
  12131. // binary: 100000
  12132. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  12133. /**
  12134. * Converts from a two-complement value to a value where the sign bit is
  12135. * is placed in the least significant bit. For example, as decimals:
  12136. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  12137. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  12138. */
  12139. function toVLQSigned(aValue) {
  12140. return aValue < 0
  12141. ? ((-aValue) << 1) + 1
  12142. : (aValue << 1) + 0;
  12143. }
  12144. /**
  12145. * Converts to a two-complement value from a value where the sign bit is
  12146. * is placed in the least significant bit. For example, as decimals:
  12147. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  12148. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  12149. */
  12150. function fromVLQSigned(aValue) {
  12151. var isNegative = (aValue & 1) === 1;
  12152. var shifted = aValue >> 1;
  12153. return isNegative
  12154. ? -shifted
  12155. : shifted;
  12156. }
  12157. /**
  12158. * Returns the base 64 VLQ encoded value.
  12159. */
  12160. exports.encode = function base64VLQ_encode(aValue) {
  12161. var encoded = "";
  12162. var digit;
  12163. var vlq = toVLQSigned(aValue);
  12164. do {
  12165. digit = vlq & VLQ_BASE_MASK;
  12166. vlq >>>= VLQ_BASE_SHIFT;
  12167. if (vlq > 0) {
  12168. // There are still more digits in this value, so we must make sure the
  12169. // continuation bit is marked.
  12170. digit |= VLQ_CONTINUATION_BIT;
  12171. }
  12172. encoded += base64.encode(digit);
  12173. } while (vlq > 0);
  12174. return encoded;
  12175. };
  12176. /**
  12177. * Decodes the next base 64 VLQ value from the given string and returns the
  12178. * value and the rest of the string.
  12179. */
  12180. exports.decode = function base64VLQ_decode(aStr) {
  12181. var i = 0;
  12182. var strLen = aStr.length;
  12183. var result = 0;
  12184. var shift = 0;
  12185. var continuation, digit;
  12186. do {
  12187. if (i >= strLen) {
  12188. throw new Error("Expected more digits in base 64 VLQ value.");
  12189. }
  12190. digit = base64.decode(aStr.charAt(i++));
  12191. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  12192. digit &= VLQ_BASE_MASK;
  12193. result = result + (digit << shift);
  12194. shift += VLQ_BASE_SHIFT;
  12195. } while (continuation);
  12196. return {
  12197. value: fromVLQSigned(result),
  12198. rest: aStr.slice(i)
  12199. };
  12200. };
  12201. });
  12202. /* -*- Mode: js; js-indent-level: 2; -*- */
  12203. /*
  12204. * Copyright 2011 Mozilla Foundation and contributors
  12205. * Licensed under the New BSD license. See LICENSE or:
  12206. * http://opensource.org/licenses/BSD-3-Clause
  12207. */
  12208. define('source-map/base64', function (require, exports, module) {
  12209. var charToIntMap = {};
  12210. var intToCharMap = {};
  12211. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  12212. .split('')
  12213. .forEach(function (ch, index) {
  12214. charToIntMap[ch] = index;
  12215. intToCharMap[index] = ch;
  12216. });
  12217. /**
  12218. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  12219. */
  12220. exports.encode = function base64_encode(aNumber) {
  12221. if (aNumber in intToCharMap) {
  12222. return intToCharMap[aNumber];
  12223. }
  12224. throw new TypeError("Must be between 0 and 63: " + aNumber);
  12225. };
  12226. /**
  12227. * Decode a single base 64 digit to an integer.
  12228. */
  12229. exports.decode = function base64_decode(aChar) {
  12230. if (aChar in charToIntMap) {
  12231. return charToIntMap[aChar];
  12232. }
  12233. throw new TypeError("Not a valid base 64 digit: " + aChar);
  12234. };
  12235. });
  12236. /* -*- Mode: js; js-indent-level: 2; -*- */
  12237. /*
  12238. * Copyright 2011 Mozilla Foundation and contributors
  12239. * Licensed under the New BSD license. See LICENSE or:
  12240. * http://opensource.org/licenses/BSD-3-Clause
  12241. */
  12242. define('source-map/binary-search', function (require, exports, module) {
  12243. /**
  12244. * Recursive implementation of binary search.
  12245. *
  12246. * @param aLow Indices here and lower do not contain the needle.
  12247. * @param aHigh Indices here and higher do not contain the needle.
  12248. * @param aNeedle The element being searched for.
  12249. * @param aHaystack The non-empty array being searched.
  12250. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  12251. */
  12252. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
  12253. // This function terminates when one of the following is true:
  12254. //
  12255. // 1. We find the exact element we are looking for.
  12256. //
  12257. // 2. We did not find the exact element, but we can return the next
  12258. // closest element that is less than that element.
  12259. //
  12260. // 3. We did not find the exact element, and there is no next-closest
  12261. // element which is less than the one we are searching for, so we
  12262. // return null.
  12263. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  12264. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  12265. if (cmp === 0) {
  12266. // Found the element we are looking for.
  12267. return aHaystack[mid];
  12268. }
  12269. else if (cmp > 0) {
  12270. // aHaystack[mid] is greater than our needle.
  12271. if (aHigh - mid > 1) {
  12272. // The element is in the upper half.
  12273. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
  12274. }
  12275. // We did not find an exact match, return the next closest one
  12276. // (termination case 2).
  12277. return aHaystack[mid];
  12278. }
  12279. else {
  12280. // aHaystack[mid] is less than our needle.
  12281. if (mid - aLow > 1) {
  12282. // The element is in the lower half.
  12283. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
  12284. }
  12285. // The exact needle element was not found in this haystack. Determine if
  12286. // we are in termination case (2) or (3) and return the appropriate thing.
  12287. return aLow < 0
  12288. ? null
  12289. : aHaystack[aLow];
  12290. }
  12291. }
  12292. /**
  12293. * This is an implementation of binary search which will always try and return
  12294. * the next lowest value checked if there is no exact hit. This is because
  12295. * mappings between original and generated line/col pairs are single points,
  12296. * and there is an implicit region between each of them, so a miss just means
  12297. * that you aren't on the very start of a region.
  12298. *
  12299. * @param aNeedle The element you are looking for.
  12300. * @param aHaystack The array that is being searched.
  12301. * @param aCompare A function which takes the needle and an element in the
  12302. * array and returns -1, 0, or 1 depending on whether the needle is less
  12303. * than, equal to, or greater than the element, respectively.
  12304. */
  12305. exports.search = function search(aNeedle, aHaystack, aCompare) {
  12306. return aHaystack.length > 0
  12307. ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
  12308. : null;
  12309. };
  12310. });
  12311. /* -*- Mode: js; js-indent-level: 2; -*- */
  12312. /*
  12313. * Copyright 2011 Mozilla Foundation and contributors
  12314. * Licensed under the New BSD license. See LICENSE or:
  12315. * http://opensource.org/licenses/BSD-3-Clause
  12316. */
  12317. define('source-map/source-map-consumer', function (require, exports, module) {
  12318. var util = require('./util');
  12319. var binarySearch = require('./binary-search');
  12320. var ArraySet = require('./array-set').ArraySet;
  12321. var base64VLQ = require('./base64-vlq');
  12322. /**
  12323. * A SourceMapConsumer instance represents a parsed source map which we can
  12324. * query for information about the original file positions by giving it a file
  12325. * position in the generated source.
  12326. *
  12327. * The only parameter is the raw source map (either as a JSON string, or
  12328. * already parsed to an object). According to the spec, source maps have the
  12329. * following attributes:
  12330. *
  12331. * - version: Which version of the source map spec this map is following.
  12332. * - sources: An array of URLs to the original source files.
  12333. * - names: An array of identifiers which can be referrenced by individual mappings.
  12334. * - sourceRoot: Optional. The URL root from which all sources are relative.
  12335. * - sourcesContent: Optional. An array of contents of the original source files.
  12336. * - mappings: A string of base64 VLQs which contain the actual mappings.
  12337. * - file: Optional. The generated file this source map is associated with.
  12338. *
  12339. * Here is an example source map, taken from the source map spec[0]:
  12340. *
  12341. * {
  12342. * version : 3,
  12343. * file: "out.js",
  12344. * sourceRoot : "",
  12345. * sources: ["foo.js", "bar.js"],
  12346. * names: ["src", "maps", "are", "fun"],
  12347. * mappings: "AA,AB;;ABCDE;"
  12348. * }
  12349. *
  12350. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  12351. */
  12352. function SourceMapConsumer(aSourceMap) {
  12353. var sourceMap = aSourceMap;
  12354. if (typeof aSourceMap === 'string') {
  12355. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  12356. }
  12357. var version = util.getArg(sourceMap, 'version');
  12358. var sources = util.getArg(sourceMap, 'sources');
  12359. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  12360. // requires the array) to play nice here.
  12361. var names = util.getArg(sourceMap, 'names', []);
  12362. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  12363. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  12364. var mappings = util.getArg(sourceMap, 'mappings');
  12365. var file = util.getArg(sourceMap, 'file', null);
  12366. // Once again, Sass deviates from the spec and supplies the version as a
  12367. // string rather than a number, so we use loose equality checking here.
  12368. if (version != this._version) {
  12369. throw new Error('Unsupported version: ' + version);
  12370. }
  12371. // Pass `true` below to allow duplicate names and sources. While source maps
  12372. // are intended to be compressed and deduplicated, the TypeScript compiler
  12373. // sometimes generates source maps with duplicates in them. See Github issue
  12374. // #72 and bugzil.la/889492.
  12375. this._names = ArraySet.fromArray(names, true);
  12376. this._sources = ArraySet.fromArray(sources, true);
  12377. this.sourceRoot = sourceRoot;
  12378. this.sourcesContent = sourcesContent;
  12379. this._mappings = mappings;
  12380. this.file = file;
  12381. }
  12382. /**
  12383. * Create a SourceMapConsumer from a SourceMapGenerator.
  12384. *
  12385. * @param SourceMapGenerator aSourceMap
  12386. * The source map that will be consumed.
  12387. * @returns SourceMapConsumer
  12388. */
  12389. SourceMapConsumer.fromSourceMap =
  12390. function SourceMapConsumer_fromSourceMap(aSourceMap) {
  12391. var smc = Object.create(SourceMapConsumer.prototype);
  12392. smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  12393. smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  12394. smc.sourceRoot = aSourceMap._sourceRoot;
  12395. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  12396. smc.sourceRoot);
  12397. smc.file = aSourceMap._file;
  12398. smc.__generatedMappings = aSourceMap._mappings.slice()
  12399. .sort(util.compareByGeneratedPositions);
  12400. smc.__originalMappings = aSourceMap._mappings.slice()
  12401. .sort(util.compareByOriginalPositions);
  12402. return smc;
  12403. };
  12404. /**
  12405. * The version of the source mapping spec that we are consuming.
  12406. */
  12407. SourceMapConsumer.prototype._version = 3;
  12408. /**
  12409. * The list of original sources.
  12410. */
  12411. Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
  12412. get: function () {
  12413. return this._sources.toArray().map(function (s) {
  12414. return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
  12415. }, this);
  12416. }
  12417. });
  12418. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  12419. // parsed mapping coordinates from the source map's "mappings" attribute. They
  12420. // are lazily instantiated, accessed via the `_generatedMappings` and
  12421. // `_originalMappings` getters respectively, and we only parse the mappings
  12422. // and create these arrays once queried for a source location. We jump through
  12423. // these hoops because there can be many thousands of mappings, and parsing
  12424. // them is expensive, so we only want to do it if we must.
  12425. //
  12426. // Each object in the arrays is of the form:
  12427. //
  12428. // {
  12429. // generatedLine: The line number in the generated code,
  12430. // generatedColumn: The column number in the generated code,
  12431. // source: The path to the original source file that generated this
  12432. // chunk of code,
  12433. // originalLine: The line number in the original source that
  12434. // corresponds to this chunk of generated code,
  12435. // originalColumn: The column number in the original source that
  12436. // corresponds to this chunk of generated code,
  12437. // name: The name of the original symbol which generated this chunk of
  12438. // code.
  12439. // }
  12440. //
  12441. // All properties except for `generatedLine` and `generatedColumn` can be
  12442. // `null`.
  12443. //
  12444. // `_generatedMappings` is ordered by the generated positions.
  12445. //
  12446. // `_originalMappings` is ordered by the original positions.
  12447. SourceMapConsumer.prototype.__generatedMappings = null;
  12448. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  12449. get: function () {
  12450. if (!this.__generatedMappings) {
  12451. this.__generatedMappings = [];
  12452. this.__originalMappings = [];
  12453. this._parseMappings(this._mappings, this.sourceRoot);
  12454. }
  12455. return this.__generatedMappings;
  12456. }
  12457. });
  12458. SourceMapConsumer.prototype.__originalMappings = null;
  12459. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  12460. get: function () {
  12461. if (!this.__originalMappings) {
  12462. this.__generatedMappings = [];
  12463. this.__originalMappings = [];
  12464. this._parseMappings(this._mappings, this.sourceRoot);
  12465. }
  12466. return this.__originalMappings;
  12467. }
  12468. });
  12469. /**
  12470. * Parse the mappings in a string in to a data structure which we can easily
  12471. * query (the ordered arrays in the `this.__generatedMappings` and
  12472. * `this.__originalMappings` properties).
  12473. */
  12474. SourceMapConsumer.prototype._parseMappings =
  12475. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  12476. var generatedLine = 1;
  12477. var previousGeneratedColumn = 0;
  12478. var previousOriginalLine = 0;
  12479. var previousOriginalColumn = 0;
  12480. var previousSource = 0;
  12481. var previousName = 0;
  12482. var mappingSeparator = /^[,;]/;
  12483. var str = aStr;
  12484. var mapping;
  12485. var temp;
  12486. while (str.length > 0) {
  12487. if (str.charAt(0) === ';') {
  12488. generatedLine++;
  12489. str = str.slice(1);
  12490. previousGeneratedColumn = 0;
  12491. }
  12492. else if (str.charAt(0) === ',') {
  12493. str = str.slice(1);
  12494. }
  12495. else {
  12496. mapping = {};
  12497. mapping.generatedLine = generatedLine;
  12498. // Generated column.
  12499. temp = base64VLQ.decode(str);
  12500. mapping.generatedColumn = previousGeneratedColumn + temp.value;
  12501. previousGeneratedColumn = mapping.generatedColumn;
  12502. str = temp.rest;
  12503. if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
  12504. // Original source.
  12505. temp = base64VLQ.decode(str);
  12506. mapping.source = this._sources.at(previousSource + temp.value);
  12507. previousSource += temp.value;
  12508. str = temp.rest;
  12509. if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
  12510. throw new Error('Found a source, but no line and column');
  12511. }
  12512. // Original line.
  12513. temp = base64VLQ.decode(str);
  12514. mapping.originalLine = previousOriginalLine + temp.value;
  12515. previousOriginalLine = mapping.originalLine;
  12516. // Lines are stored 0-based
  12517. mapping.originalLine += 1;
  12518. str = temp.rest;
  12519. if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
  12520. throw new Error('Found a source and line, but no column');
  12521. }
  12522. // Original column.
  12523. temp = base64VLQ.decode(str);
  12524. mapping.originalColumn = previousOriginalColumn + temp.value;
  12525. previousOriginalColumn = mapping.originalColumn;
  12526. str = temp.rest;
  12527. if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
  12528. // Original name.
  12529. temp = base64VLQ.decode(str);
  12530. mapping.name = this._names.at(previousName + temp.value);
  12531. previousName += temp.value;
  12532. str = temp.rest;
  12533. }
  12534. }
  12535. this.__generatedMappings.push(mapping);
  12536. if (typeof mapping.originalLine === 'number') {
  12537. this.__originalMappings.push(mapping);
  12538. }
  12539. }
  12540. }
  12541. this.__generatedMappings.sort(util.compareByGeneratedPositions);
  12542. this.__originalMappings.sort(util.compareByOriginalPositions);
  12543. };
  12544. /**
  12545. * Find the mapping that best matches the hypothetical "needle" mapping that
  12546. * we are searching for in the given "haystack" of mappings.
  12547. */
  12548. SourceMapConsumer.prototype._findMapping =
  12549. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  12550. aColumnName, aComparator) {
  12551. // To return the position we are searching for, we must first find the
  12552. // mapping for the given position and then return the opposite position it
  12553. // points to. Because the mappings are sorted, we can use binary search to
  12554. // find the best mapping.
  12555. if (aNeedle[aLineName] <= 0) {
  12556. throw new TypeError('Line must be greater than or equal to 1, got '
  12557. + aNeedle[aLineName]);
  12558. }
  12559. if (aNeedle[aColumnName] < 0) {
  12560. throw new TypeError('Column must be greater than or equal to 0, got '
  12561. + aNeedle[aColumnName]);
  12562. }
  12563. return binarySearch.search(aNeedle, aMappings, aComparator);
  12564. };
  12565. /**
  12566. * Returns the original source, line, and column information for the generated
  12567. * source's line and column positions provided. The only argument is an object
  12568. * with the following properties:
  12569. *
  12570. * - line: The line number in the generated source.
  12571. * - column: The column number in the generated source.
  12572. *
  12573. * and an object is returned with the following properties:
  12574. *
  12575. * - source: The original source file, or null.
  12576. * - line: The line number in the original source, or null.
  12577. * - column: The column number in the original source, or null.
  12578. * - name: The original identifier, or null.
  12579. */
  12580. SourceMapConsumer.prototype.originalPositionFor =
  12581. function SourceMapConsumer_originalPositionFor(aArgs) {
  12582. var needle = {
  12583. generatedLine: util.getArg(aArgs, 'line'),
  12584. generatedColumn: util.getArg(aArgs, 'column')
  12585. };
  12586. var mapping = this._findMapping(needle,
  12587. this._generatedMappings,
  12588. "generatedLine",
  12589. "generatedColumn",
  12590. util.compareByGeneratedPositions);
  12591. if (mapping && mapping.generatedLine === needle.generatedLine) {
  12592. var source = util.getArg(mapping, 'source', null);
  12593. if (source && this.sourceRoot) {
  12594. source = util.join(this.sourceRoot, source);
  12595. }
  12596. return {
  12597. source: source,
  12598. line: util.getArg(mapping, 'originalLine', null),
  12599. column: util.getArg(mapping, 'originalColumn', null),
  12600. name: util.getArg(mapping, 'name', null)
  12601. };
  12602. }
  12603. return {
  12604. source: null,
  12605. line: null,
  12606. column: null,
  12607. name: null
  12608. };
  12609. };
  12610. /**
  12611. * Returns the original source content. The only argument is the url of the
  12612. * original source file. Returns null if no original source content is
  12613. * availible.
  12614. */
  12615. SourceMapConsumer.prototype.sourceContentFor =
  12616. function SourceMapConsumer_sourceContentFor(aSource) {
  12617. if (!this.sourcesContent) {
  12618. return null;
  12619. }
  12620. if (this.sourceRoot) {
  12621. aSource = util.relative(this.sourceRoot, aSource);
  12622. }
  12623. if (this._sources.has(aSource)) {
  12624. return this.sourcesContent[this._sources.indexOf(aSource)];
  12625. }
  12626. var url;
  12627. if (this.sourceRoot
  12628. && (url = util.urlParse(this.sourceRoot))) {
  12629. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  12630. // many users. We can help them out when they expect file:// URIs to
  12631. // behave like it would if they were running a local HTTP server. See
  12632. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  12633. var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
  12634. if (url.scheme == "file"
  12635. && this._sources.has(fileUriAbsPath)) {
  12636. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  12637. }
  12638. if ((!url.path || url.path == "/")
  12639. && this._sources.has("/" + aSource)) {
  12640. return this.sourcesContent[this._sources.indexOf("/" + aSource)];
  12641. }
  12642. }
  12643. throw new Error('"' + aSource + '" is not in the SourceMap.');
  12644. };
  12645. /**
  12646. * Returns the generated line and column information for the original source,
  12647. * line, and column positions provided. The only argument is an object with
  12648. * the following properties:
  12649. *
  12650. * - source: The filename of the original source.
  12651. * - line: The line number in the original source.
  12652. * - column: The column number in the original source.
  12653. *
  12654. * and an object is returned with the following properties:
  12655. *
  12656. * - line: The line number in the generated source, or null.
  12657. * - column: The column number in the generated source, or null.
  12658. */
  12659. SourceMapConsumer.prototype.generatedPositionFor =
  12660. function SourceMapConsumer_generatedPositionFor(aArgs) {
  12661. var needle = {
  12662. source: util.getArg(aArgs, 'source'),
  12663. originalLine: util.getArg(aArgs, 'line'),
  12664. originalColumn: util.getArg(aArgs, 'column')
  12665. };
  12666. if (this.sourceRoot) {
  12667. needle.source = util.relative(this.sourceRoot, needle.source);
  12668. }
  12669. var mapping = this._findMapping(needle,
  12670. this._originalMappings,
  12671. "originalLine",
  12672. "originalColumn",
  12673. util.compareByOriginalPositions);
  12674. if (mapping) {
  12675. return {
  12676. line: util.getArg(mapping, 'generatedLine', null),
  12677. column: util.getArg(mapping, 'generatedColumn', null)
  12678. };
  12679. }
  12680. return {
  12681. line: null,
  12682. column: null
  12683. };
  12684. };
  12685. SourceMapConsumer.GENERATED_ORDER = 1;
  12686. SourceMapConsumer.ORIGINAL_ORDER = 2;
  12687. /**
  12688. * Iterate over each mapping between an original source/line/column and a
  12689. * generated line/column in this source map.
  12690. *
  12691. * @param Function aCallback
  12692. * The function that is called with each mapping.
  12693. * @param Object aContext
  12694. * Optional. If specified, this object will be the value of `this` every
  12695. * time that `aCallback` is called.
  12696. * @param aOrder
  12697. * Either `SourceMapConsumer.GENERATED_ORDER` or
  12698. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  12699. * iterate over the mappings sorted by the generated file's line/column
  12700. * order or the original's source/line/column order, respectively. Defaults to
  12701. * `SourceMapConsumer.GENERATED_ORDER`.
  12702. */
  12703. SourceMapConsumer.prototype.eachMapping =
  12704. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  12705. var context = aContext || null;
  12706. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  12707. var mappings;
  12708. switch (order) {
  12709. case SourceMapConsumer.GENERATED_ORDER:
  12710. mappings = this._generatedMappings;
  12711. break;
  12712. case SourceMapConsumer.ORIGINAL_ORDER:
  12713. mappings = this._originalMappings;
  12714. break;
  12715. default:
  12716. throw new Error("Unknown order of iteration.");
  12717. }
  12718. var sourceRoot = this.sourceRoot;
  12719. mappings.map(function (mapping) {
  12720. var source = mapping.source;
  12721. if (source && sourceRoot) {
  12722. source = util.join(sourceRoot, source);
  12723. }
  12724. return {
  12725. source: source,
  12726. generatedLine: mapping.generatedLine,
  12727. generatedColumn: mapping.generatedColumn,
  12728. originalLine: mapping.originalLine,
  12729. originalColumn: mapping.originalColumn,
  12730. name: mapping.name
  12731. };
  12732. }).forEach(aCallback, context);
  12733. };
  12734. exports.SourceMapConsumer = SourceMapConsumer;
  12735. });
  12736. /* -*- Mode: js; js-indent-level: 2; -*- */
  12737. /*
  12738. * Copyright 2011 Mozilla Foundation and contributors
  12739. * Licensed under the New BSD license. See LICENSE or:
  12740. * http://opensource.org/licenses/BSD-3-Clause
  12741. */
  12742. define('source-map/source-map-generator', function (require, exports, module) {
  12743. var base64VLQ = require('./base64-vlq');
  12744. var util = require('./util');
  12745. var ArraySet = require('./array-set').ArraySet;
  12746. /**
  12747. * An instance of the SourceMapGenerator represents a source map which is
  12748. * being built incrementally. You may pass an object with the following
  12749. * properties:
  12750. *
  12751. * - file: The filename of the generated source.
  12752. * - sourceRoot: A root for all relative URLs in this source map.
  12753. */
  12754. function SourceMapGenerator(aArgs) {
  12755. if (!aArgs) {
  12756. aArgs = {};
  12757. }
  12758. this._file = util.getArg(aArgs, 'file', null);
  12759. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  12760. this._sources = new ArraySet();
  12761. this._names = new ArraySet();
  12762. this._mappings = [];
  12763. this._sourcesContents = null;
  12764. }
  12765. SourceMapGenerator.prototype._version = 3;
  12766. /**
  12767. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  12768. *
  12769. * @param aSourceMapConsumer The SourceMap.
  12770. */
  12771. SourceMapGenerator.fromSourceMap =
  12772. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  12773. var sourceRoot = aSourceMapConsumer.sourceRoot;
  12774. var generator = new SourceMapGenerator({
  12775. file: aSourceMapConsumer.file,
  12776. sourceRoot: sourceRoot
  12777. });
  12778. aSourceMapConsumer.eachMapping(function (mapping) {
  12779. var newMapping = {
  12780. generated: {
  12781. line: mapping.generatedLine,
  12782. column: mapping.generatedColumn
  12783. }
  12784. };
  12785. if (mapping.source) {
  12786. newMapping.source = mapping.source;
  12787. if (sourceRoot) {
  12788. newMapping.source = util.relative(sourceRoot, newMapping.source);
  12789. }
  12790. newMapping.original = {
  12791. line: mapping.originalLine,
  12792. column: mapping.originalColumn
  12793. };
  12794. if (mapping.name) {
  12795. newMapping.name = mapping.name;
  12796. }
  12797. }
  12798. generator.addMapping(newMapping);
  12799. });
  12800. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  12801. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  12802. if (content) {
  12803. generator.setSourceContent(sourceFile, content);
  12804. }
  12805. });
  12806. return generator;
  12807. };
  12808. /**
  12809. * Add a single mapping from original source line and column to the generated
  12810. * source's line and column for this source map being created. The mapping
  12811. * object should have the following properties:
  12812. *
  12813. * - generated: An object with the generated line and column positions.
  12814. * - original: An object with the original line and column positions.
  12815. * - source: The original source file (relative to the sourceRoot).
  12816. * - name: An optional original token name for this mapping.
  12817. */
  12818. SourceMapGenerator.prototype.addMapping =
  12819. function SourceMapGenerator_addMapping(aArgs) {
  12820. var generated = util.getArg(aArgs, 'generated');
  12821. var original = util.getArg(aArgs, 'original', null);
  12822. var source = util.getArg(aArgs, 'source', null);
  12823. var name = util.getArg(aArgs, 'name', null);
  12824. this._validateMapping(generated, original, source, name);
  12825. if (source && !this._sources.has(source)) {
  12826. this._sources.add(source);
  12827. }
  12828. if (name && !this._names.has(name)) {
  12829. this._names.add(name);
  12830. }
  12831. this._mappings.push({
  12832. generatedLine: generated.line,
  12833. generatedColumn: generated.column,
  12834. originalLine: original != null && original.line,
  12835. originalColumn: original != null && original.column,
  12836. source: source,
  12837. name: name
  12838. });
  12839. };
  12840. /**
  12841. * Set the source content for a source file.
  12842. */
  12843. SourceMapGenerator.prototype.setSourceContent =
  12844. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  12845. var source = aSourceFile;
  12846. if (this._sourceRoot) {
  12847. source = util.relative(this._sourceRoot, source);
  12848. }
  12849. if (aSourceContent !== null) {
  12850. // Add the source content to the _sourcesContents map.
  12851. // Create a new _sourcesContents map if the property is null.
  12852. if (!this._sourcesContents) {
  12853. this._sourcesContents = {};
  12854. }
  12855. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  12856. } else {
  12857. // Remove the source file from the _sourcesContents map.
  12858. // If the _sourcesContents map is empty, set the property to null.
  12859. delete this._sourcesContents[util.toSetString(source)];
  12860. if (Object.keys(this._sourcesContents).length === 0) {
  12861. this._sourcesContents = null;
  12862. }
  12863. }
  12864. };
  12865. /**
  12866. * Applies the mappings of a sub-source-map for a specific source file to the
  12867. * source map being generated. Each mapping to the supplied source file is
  12868. * rewritten using the supplied source map. Note: The resolution for the
  12869. * resulting mappings is the minimium of this map and the supplied map.
  12870. *
  12871. * @param aSourceMapConsumer The source map to be applied.
  12872. * @param aSourceFile Optional. The filename of the source file.
  12873. * If omitted, SourceMapConsumer's file property will be used.
  12874. * @param aSourceMapPath Optional. The dirname of the path to the source map
  12875. * to be applied. If relative, it is relative to the SourceMapConsumer.
  12876. * This parameter is needed when the two source maps aren't in the same
  12877. * directory, and the source map to be applied contains relative source
  12878. * paths. If so, those relative source paths need to be rewritten
  12879. * relative to the SourceMapGenerator.
  12880. */
  12881. SourceMapGenerator.prototype.applySourceMap =
  12882. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  12883. // If aSourceFile is omitted, we will use the file property of the SourceMap
  12884. if (!aSourceFile) {
  12885. if (!aSourceMapConsumer.file) {
  12886. throw new Error(
  12887. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  12888. 'or the source map\'s "file" property. Both were omitted.'
  12889. );
  12890. }
  12891. aSourceFile = aSourceMapConsumer.file;
  12892. }
  12893. var sourceRoot = this._sourceRoot;
  12894. // Make "aSourceFile" relative if an absolute Url is passed.
  12895. if (sourceRoot) {
  12896. aSourceFile = util.relative(sourceRoot, aSourceFile);
  12897. }
  12898. // Applying the SourceMap can add and remove items from the sources and
  12899. // the names array.
  12900. var newSources = new ArraySet();
  12901. var newNames = new ArraySet();
  12902. // Find mappings for the "aSourceFile"
  12903. this._mappings.forEach(function (mapping) {
  12904. if (mapping.source === aSourceFile && mapping.originalLine) {
  12905. // Check if it can be mapped by the source map, then update the mapping.
  12906. var original = aSourceMapConsumer.originalPositionFor({
  12907. line: mapping.originalLine,
  12908. column: mapping.originalColumn
  12909. });
  12910. if (original.source !== null) {
  12911. // Copy mapping
  12912. mapping.source = original.source;
  12913. if (aSourceMapPath) {
  12914. mapping.source = util.join(aSourceMapPath, mapping.source)
  12915. }
  12916. if (sourceRoot) {
  12917. mapping.source = util.relative(sourceRoot, mapping.source);
  12918. }
  12919. mapping.originalLine = original.line;
  12920. mapping.originalColumn = original.column;
  12921. if (original.name !== null && mapping.name !== null) {
  12922. // Only use the identifier name if it's an identifier
  12923. // in both SourceMaps
  12924. mapping.name = original.name;
  12925. }
  12926. }
  12927. }
  12928. var source = mapping.source;
  12929. if (source && !newSources.has(source)) {
  12930. newSources.add(source);
  12931. }
  12932. var name = mapping.name;
  12933. if (name && !newNames.has(name)) {
  12934. newNames.add(name);
  12935. }
  12936. }, this);
  12937. this._sources = newSources;
  12938. this._names = newNames;
  12939. // Copy sourcesContents of applied map.
  12940. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  12941. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  12942. if (content) {
  12943. if (aSourceMapPath) {
  12944. sourceFile = util.join(aSourceMapPath, sourceFile);
  12945. }
  12946. if (sourceRoot) {
  12947. sourceFile = util.relative(sourceRoot, sourceFile);
  12948. }
  12949. this.setSourceContent(sourceFile, content);
  12950. }
  12951. }, this);
  12952. };
  12953. /**
  12954. * A mapping can have one of the three levels of data:
  12955. *
  12956. * 1. Just the generated position.
  12957. * 2. The Generated position, original position, and original source.
  12958. * 3. Generated and original position, original source, as well as a name
  12959. * token.
  12960. *
  12961. * To maintain consistency, we validate that any new mapping being added falls
  12962. * in to one of these categories.
  12963. */
  12964. SourceMapGenerator.prototype._validateMapping =
  12965. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  12966. aName) {
  12967. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  12968. && aGenerated.line > 0 && aGenerated.column >= 0
  12969. && !aOriginal && !aSource && !aName) {
  12970. // Case 1.
  12971. return;
  12972. }
  12973. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  12974. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  12975. && aGenerated.line > 0 && aGenerated.column >= 0
  12976. && aOriginal.line > 0 && aOriginal.column >= 0
  12977. && aSource) {
  12978. // Cases 2 and 3.
  12979. return;
  12980. }
  12981. else {
  12982. throw new Error('Invalid mapping: ' + JSON.stringify({
  12983. generated: aGenerated,
  12984. source: aSource,
  12985. original: aOriginal,
  12986. name: aName
  12987. }));
  12988. }
  12989. };
  12990. /**
  12991. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  12992. * specified by the source map format.
  12993. */
  12994. SourceMapGenerator.prototype._serializeMappings =
  12995. function SourceMapGenerator_serializeMappings() {
  12996. var previousGeneratedColumn = 0;
  12997. var previousGeneratedLine = 1;
  12998. var previousOriginalColumn = 0;
  12999. var previousOriginalLine = 0;
  13000. var previousName = 0;
  13001. var previousSource = 0;
  13002. var result = '';
  13003. var mapping;
  13004. // The mappings must be guaranteed to be in sorted order before we start
  13005. // serializing them or else the generated line numbers (which are defined
  13006. // via the ';' separators) will be all messed up. Note: it might be more
  13007. // performant to maintain the sorting as we insert them, rather than as we
  13008. // serialize them, but the big O is the same either way.
  13009. this._mappings.sort(util.compareByGeneratedPositions);
  13010. for (var i = 0, len = this._mappings.length; i < len; i++) {
  13011. mapping = this._mappings[i];
  13012. if (mapping.generatedLine !== previousGeneratedLine) {
  13013. previousGeneratedColumn = 0;
  13014. while (mapping.generatedLine !== previousGeneratedLine) {
  13015. result += ';';
  13016. previousGeneratedLine++;
  13017. }
  13018. }
  13019. else {
  13020. if (i > 0) {
  13021. if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
  13022. continue;
  13023. }
  13024. result += ',';
  13025. }
  13026. }
  13027. result += base64VLQ.encode(mapping.generatedColumn
  13028. - previousGeneratedColumn);
  13029. previousGeneratedColumn = mapping.generatedColumn;
  13030. if (mapping.source) {
  13031. result += base64VLQ.encode(this._sources.indexOf(mapping.source)
  13032. - previousSource);
  13033. previousSource = this._sources.indexOf(mapping.source);
  13034. // lines are stored 0-based in SourceMap spec version 3
  13035. result += base64VLQ.encode(mapping.originalLine - 1
  13036. - previousOriginalLine);
  13037. previousOriginalLine = mapping.originalLine - 1;
  13038. result += base64VLQ.encode(mapping.originalColumn
  13039. - previousOriginalColumn);
  13040. previousOriginalColumn = mapping.originalColumn;
  13041. if (mapping.name) {
  13042. result += base64VLQ.encode(this._names.indexOf(mapping.name)
  13043. - previousName);
  13044. previousName = this._names.indexOf(mapping.name);
  13045. }
  13046. }
  13047. }
  13048. return result;
  13049. };
  13050. SourceMapGenerator.prototype._generateSourcesContent =
  13051. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  13052. return aSources.map(function (source) {
  13053. if (!this._sourcesContents) {
  13054. return null;
  13055. }
  13056. if (aSourceRoot) {
  13057. source = util.relative(aSourceRoot, source);
  13058. }
  13059. var key = util.toSetString(source);
  13060. return Object.prototype.hasOwnProperty.call(this._sourcesContents,
  13061. key)
  13062. ? this._sourcesContents[key]
  13063. : null;
  13064. }, this);
  13065. };
  13066. /**
  13067. * Externalize the source map.
  13068. */
  13069. SourceMapGenerator.prototype.toJSON =
  13070. function SourceMapGenerator_toJSON() {
  13071. var map = {
  13072. version: this._version,
  13073. file: this._file,
  13074. sources: this._sources.toArray(),
  13075. names: this._names.toArray(),
  13076. mappings: this._serializeMappings()
  13077. };
  13078. if (this._sourceRoot) {
  13079. map.sourceRoot = this._sourceRoot;
  13080. }
  13081. if (this._sourcesContents) {
  13082. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  13083. }
  13084. return map;
  13085. };
  13086. /**
  13087. * Render the source map being generated to a string.
  13088. */
  13089. SourceMapGenerator.prototype.toString =
  13090. function SourceMapGenerator_toString() {
  13091. return JSON.stringify(this);
  13092. };
  13093. exports.SourceMapGenerator = SourceMapGenerator;
  13094. });
  13095. /* -*- Mode: js; js-indent-level: 2; -*- */
  13096. /*
  13097. * Copyright 2011 Mozilla Foundation and contributors
  13098. * Licensed under the New BSD license. See LICENSE or:
  13099. * http://opensource.org/licenses/BSD-3-Clause
  13100. */
  13101. define('source-map/source-node', function (require, exports, module) {
  13102. var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
  13103. var util = require('./util');
  13104. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  13105. // operating systems these days (capturing the result).
  13106. var REGEX_NEWLINE = /(\r?\n)/g;
  13107. // Matches a Windows-style newline, or any character.
  13108. var REGEX_CHARACTER = /\r\n|[\s\S]/g;
  13109. /**
  13110. * SourceNodes provide a way to abstract over interpolating/concatenating
  13111. * snippets of generated JavaScript source code while maintaining the line and
  13112. * column information associated with the original source code.
  13113. *
  13114. * @param aLine The original line number.
  13115. * @param aColumn The original column number.
  13116. * @param aSource The original source's filename.
  13117. * @param aChunks Optional. An array of strings which are snippets of
  13118. * generated JS, or other SourceNodes.
  13119. * @param aName The original identifier.
  13120. */
  13121. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  13122. this.children = [];
  13123. this.sourceContents = {};
  13124. this.line = aLine === undefined ? null : aLine;
  13125. this.column = aColumn === undefined ? null : aColumn;
  13126. this.source = aSource === undefined ? null : aSource;
  13127. this.name = aName === undefined ? null : aName;
  13128. if (aChunks != null) this.add(aChunks);
  13129. }
  13130. /**
  13131. * Creates a SourceNode from generated code and a SourceMapConsumer.
  13132. *
  13133. * @param aGeneratedCode The generated code
  13134. * @param aSourceMapConsumer The SourceMap for the generated code
  13135. */
  13136. SourceNode.fromStringWithSourceMap =
  13137. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
  13138. // The SourceNode we want to fill with the generated code
  13139. // and the SourceMap
  13140. var node = new SourceNode();
  13141. // All even indices of this array are one line of the generated code,
  13142. // while all odd indices are the newlines between two adjacent lines
  13143. // (since `REGEX_NEWLINE` captures its match).
  13144. // Processed fragments are removed from this array, by calling `shiftNextLine`.
  13145. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  13146. var shiftNextLine = function() {
  13147. var lineContents = remainingLines.shift();
  13148. // The last line of a file might not have a newline.
  13149. var newLine = remainingLines.shift() || "";
  13150. return lineContents + newLine;
  13151. };
  13152. // We need to remember the position of "remainingLines"
  13153. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  13154. // The generate SourceNodes we need a code range.
  13155. // To extract it current and last mapping is used.
  13156. // Here we store the last mapping.
  13157. var lastMapping = null;
  13158. aSourceMapConsumer.eachMapping(function (mapping) {
  13159. if (lastMapping !== null) {
  13160. // We add the code from "lastMapping" to "mapping":
  13161. // First check if there is a new line in between.
  13162. if (lastGeneratedLine < mapping.generatedLine) {
  13163. var code = "";
  13164. // Associate first line with "lastMapping"
  13165. addMappingWithCode(lastMapping, shiftNextLine());
  13166. lastGeneratedLine++;
  13167. lastGeneratedColumn = 0;
  13168. // The remaining code is added without mapping
  13169. } else {
  13170. // There is no new line in between.
  13171. // Associate the code between "lastGeneratedColumn" and
  13172. // "mapping.generatedColumn" with "lastMapping"
  13173. var nextLine = remainingLines[0];
  13174. var code = nextLine.substr(0, mapping.generatedColumn -
  13175. lastGeneratedColumn);
  13176. remainingLines[0] = nextLine.substr(mapping.generatedColumn -
  13177. lastGeneratedColumn);
  13178. lastGeneratedColumn = mapping.generatedColumn;
  13179. addMappingWithCode(lastMapping, code);
  13180. // No more remaining code, continue
  13181. lastMapping = mapping;
  13182. return;
  13183. }
  13184. }
  13185. // We add the generated code until the first mapping
  13186. // to the SourceNode without any mapping.
  13187. // Each line is added as separate string.
  13188. while (lastGeneratedLine < mapping.generatedLine) {
  13189. node.add(shiftNextLine());
  13190. lastGeneratedLine++;
  13191. }
  13192. if (lastGeneratedColumn < mapping.generatedColumn) {
  13193. var nextLine = remainingLines[0];
  13194. node.add(nextLine.substr(0, mapping.generatedColumn));
  13195. remainingLines[0] = nextLine.substr(mapping.generatedColumn);
  13196. lastGeneratedColumn = mapping.generatedColumn;
  13197. }
  13198. lastMapping = mapping;
  13199. }, this);
  13200. // We have processed all mappings.
  13201. if (remainingLines.length > 0) {
  13202. if (lastMapping) {
  13203. // Associate the remaining code in the current line with "lastMapping"
  13204. addMappingWithCode(lastMapping, shiftNextLine());
  13205. }
  13206. // and add the remaining lines without any mapping
  13207. node.add(remainingLines.join(""));
  13208. }
  13209. // Copy sourcesContent into SourceNode
  13210. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  13211. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  13212. if (content) {
  13213. node.setSourceContent(sourceFile, content);
  13214. }
  13215. });
  13216. return node;
  13217. function addMappingWithCode(mapping, code) {
  13218. if (mapping === null || mapping.source === undefined) {
  13219. node.add(code);
  13220. } else {
  13221. node.add(new SourceNode(mapping.originalLine,
  13222. mapping.originalColumn,
  13223. mapping.source,
  13224. code,
  13225. mapping.name));
  13226. }
  13227. }
  13228. };
  13229. /**
  13230. * Add a chunk of generated JS to this source node.
  13231. *
  13232. * @param aChunk A string snippet of generated JS code, another instance of
  13233. * SourceNode, or an array where each member is one of those things.
  13234. */
  13235. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  13236. if (Array.isArray(aChunk)) {
  13237. aChunk.forEach(function (chunk) {
  13238. this.add(chunk);
  13239. }, this);
  13240. }
  13241. else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
  13242. if (aChunk) {
  13243. this.children.push(aChunk);
  13244. }
  13245. }
  13246. else {
  13247. throw new TypeError(
  13248. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  13249. );
  13250. }
  13251. return this;
  13252. };
  13253. /**
  13254. * Add a chunk of generated JS to the beginning of this source node.
  13255. *
  13256. * @param aChunk A string snippet of generated JS code, another instance of
  13257. * SourceNode, or an array where each member is one of those things.
  13258. */
  13259. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  13260. if (Array.isArray(aChunk)) {
  13261. for (var i = aChunk.length-1; i >= 0; i--) {
  13262. this.prepend(aChunk[i]);
  13263. }
  13264. }
  13265. else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
  13266. this.children.unshift(aChunk);
  13267. }
  13268. else {
  13269. throw new TypeError(
  13270. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  13271. );
  13272. }
  13273. return this;
  13274. };
  13275. /**
  13276. * Walk over the tree of JS snippets in this node and its children. The
  13277. * walking function is called once for each snippet of JS and is passed that
  13278. * snippet and the its original associated source's line/column location.
  13279. *
  13280. * @param aFn The traversal function.
  13281. */
  13282. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  13283. var chunk;
  13284. for (var i = 0, len = this.children.length; i < len; i++) {
  13285. chunk = this.children[i];
  13286. if (chunk instanceof SourceNode) {
  13287. chunk.walk(aFn);
  13288. }
  13289. else {
  13290. if (chunk !== '') {
  13291. aFn(chunk, { source: this.source,
  13292. line: this.line,
  13293. column: this.column,
  13294. name: this.name });
  13295. }
  13296. }
  13297. }
  13298. };
  13299. /**
  13300. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  13301. * each of `this.children`.
  13302. *
  13303. * @param aSep The separator.
  13304. */
  13305. SourceNode.prototype.join = function SourceNode_join(aSep) {
  13306. var newChildren;
  13307. var i;
  13308. var len = this.children.length;
  13309. if (len > 0) {
  13310. newChildren = [];
  13311. for (i = 0; i < len-1; i++) {
  13312. newChildren.push(this.children[i]);
  13313. newChildren.push(aSep);
  13314. }
  13315. newChildren.push(this.children[i]);
  13316. this.children = newChildren;
  13317. }
  13318. return this;
  13319. };
  13320. /**
  13321. * Call String.prototype.replace on the very right-most source snippet. Useful
  13322. * for trimming whitespace from the end of a source node, etc.
  13323. *
  13324. * @param aPattern The pattern to replace.
  13325. * @param aReplacement The thing to replace the pattern with.
  13326. */
  13327. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  13328. var lastChild = this.children[this.children.length - 1];
  13329. if (lastChild instanceof SourceNode) {
  13330. lastChild.replaceRight(aPattern, aReplacement);
  13331. }
  13332. else if (typeof lastChild === 'string') {
  13333. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  13334. }
  13335. else {
  13336. this.children.push(''.replace(aPattern, aReplacement));
  13337. }
  13338. return this;
  13339. };
  13340. /**
  13341. * Set the source content for a source file. This will be added to the SourceMapGenerator
  13342. * in the sourcesContent field.
  13343. *
  13344. * @param aSourceFile The filename of the source file
  13345. * @param aSourceContent The content of the source file
  13346. */
  13347. SourceNode.prototype.setSourceContent =
  13348. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  13349. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  13350. };
  13351. /**
  13352. * Walk over the tree of SourceNodes. The walking function is called for each
  13353. * source file content and is passed the filename and source content.
  13354. *
  13355. * @param aFn The traversal function.
  13356. */
  13357. SourceNode.prototype.walkSourceContents =
  13358. function SourceNode_walkSourceContents(aFn) {
  13359. for (var i = 0, len = this.children.length; i < len; i++) {
  13360. if (this.children[i] instanceof SourceNode) {
  13361. this.children[i].walkSourceContents(aFn);
  13362. }
  13363. }
  13364. var sources = Object.keys(this.sourceContents);
  13365. for (var i = 0, len = sources.length; i < len; i++) {
  13366. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  13367. }
  13368. };
  13369. /**
  13370. * Return the string representation of this source node. Walks over the tree
  13371. * and concatenates all the various snippets together to one string.
  13372. */
  13373. SourceNode.prototype.toString = function SourceNode_toString() {
  13374. var str = "";
  13375. this.walk(function (chunk) {
  13376. str += chunk;
  13377. });
  13378. return str;
  13379. };
  13380. /**
  13381. * Returns the string representation of this source node along with a source
  13382. * map.
  13383. */
  13384. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  13385. var generated = {
  13386. code: "",
  13387. line: 1,
  13388. column: 0
  13389. };
  13390. var map = new SourceMapGenerator(aArgs);
  13391. var sourceMappingActive = false;
  13392. var lastOriginalSource = null;
  13393. var lastOriginalLine = null;
  13394. var lastOriginalColumn = null;
  13395. var lastOriginalName = null;
  13396. this.walk(function (chunk, original) {
  13397. generated.code += chunk;
  13398. if (original.source !== null
  13399. && original.line !== null
  13400. && original.column !== null) {
  13401. if(lastOriginalSource !== original.source
  13402. || lastOriginalLine !== original.line
  13403. || lastOriginalColumn !== original.column
  13404. || lastOriginalName !== original.name) {
  13405. map.addMapping({
  13406. source: original.source,
  13407. original: {
  13408. line: original.line,
  13409. column: original.column
  13410. },
  13411. generated: {
  13412. line: generated.line,
  13413. column: generated.column
  13414. },
  13415. name: original.name
  13416. });
  13417. }
  13418. lastOriginalSource = original.source;
  13419. lastOriginalLine = original.line;
  13420. lastOriginalColumn = original.column;
  13421. lastOriginalName = original.name;
  13422. sourceMappingActive = true;
  13423. } else if (sourceMappingActive) {
  13424. map.addMapping({
  13425. generated: {
  13426. line: generated.line,
  13427. column: generated.column
  13428. }
  13429. });
  13430. lastOriginalSource = null;
  13431. sourceMappingActive = false;
  13432. }
  13433. chunk.match(REGEX_CHARACTER).forEach(function (ch, idx, array) {
  13434. if (REGEX_NEWLINE.test(ch)) {
  13435. generated.line++;
  13436. generated.column = 0;
  13437. // Mappings end at eol
  13438. if (idx + 1 === array.length) {
  13439. lastOriginalSource = null;
  13440. sourceMappingActive = false;
  13441. } else if (sourceMappingActive) {
  13442. map.addMapping({
  13443. source: original.source,
  13444. original: {
  13445. line: original.line,
  13446. column: original.column
  13447. },
  13448. generated: {
  13449. line: generated.line,
  13450. column: generated.column
  13451. },
  13452. name: original.name
  13453. });
  13454. }
  13455. } else {
  13456. generated.column += ch.length;
  13457. }
  13458. });
  13459. });
  13460. this.walkSourceContents(function (sourceFile, sourceContent) {
  13461. map.setSourceContent(sourceFile, sourceContent);
  13462. });
  13463. return { code: generated.code, map: map };
  13464. };
  13465. exports.SourceNode = SourceNode;
  13466. });
  13467. /* -*- Mode: js; js-indent-level: 2; -*- */
  13468. /*
  13469. * Copyright 2011 Mozilla Foundation and contributors
  13470. * Licensed under the New BSD license. See LICENSE or:
  13471. * http://opensource.org/licenses/BSD-3-Clause
  13472. */
  13473. define('source-map/util', function (require, exports, module) {
  13474. /**
  13475. * This is a helper function for getting values from parameter/options
  13476. * objects.
  13477. *
  13478. * @param args The object we are extracting values from
  13479. * @param name The name of the property we are getting.
  13480. * @param defaultValue An optional value to return if the property is missing
  13481. * from the object. If this is not specified and the property is missing, an
  13482. * error will be thrown.
  13483. */
  13484. function getArg(aArgs, aName, aDefaultValue) {
  13485. if (aName in aArgs) {
  13486. return aArgs[aName];
  13487. } else if (arguments.length === 3) {
  13488. return aDefaultValue;
  13489. } else {
  13490. throw new Error('"' + aName + '" is a required argument.');
  13491. }
  13492. }
  13493. exports.getArg = getArg;
  13494. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
  13495. var dataUrlRegexp = /^data:.+\,.+$/;
  13496. function urlParse(aUrl) {
  13497. var match = aUrl.match(urlRegexp);
  13498. if (!match) {
  13499. return null;
  13500. }
  13501. return {
  13502. scheme: match[1],
  13503. auth: match[2],
  13504. host: match[3],
  13505. port: match[4],
  13506. path: match[5]
  13507. };
  13508. }
  13509. exports.urlParse = urlParse;
  13510. function urlGenerate(aParsedUrl) {
  13511. var url = '';
  13512. if (aParsedUrl.scheme) {
  13513. url += aParsedUrl.scheme + ':';
  13514. }
  13515. url += '//';
  13516. if (aParsedUrl.auth) {
  13517. url += aParsedUrl.auth + '@';
  13518. }
  13519. if (aParsedUrl.host) {
  13520. url += aParsedUrl.host;
  13521. }
  13522. if (aParsedUrl.port) {
  13523. url += ":" + aParsedUrl.port
  13524. }
  13525. if (aParsedUrl.path) {
  13526. url += aParsedUrl.path;
  13527. }
  13528. return url;
  13529. }
  13530. exports.urlGenerate = urlGenerate;
  13531. /**
  13532. * Normalizes a path, or the path portion of a URL:
  13533. *
  13534. * - Replaces consequtive slashes with one slash.
  13535. * - Removes unnecessary '.' parts.
  13536. * - Removes unnecessary '<dir>/..' parts.
  13537. *
  13538. * Based on code in the Node.js 'path' core module.
  13539. *
  13540. * @param aPath The path or url to normalize.
  13541. */
  13542. function normalize(aPath) {
  13543. var path = aPath;
  13544. var url = urlParse(aPath);
  13545. if (url) {
  13546. if (!url.path) {
  13547. return aPath;
  13548. }
  13549. path = url.path;
  13550. }
  13551. var isAbsolute = (path.charAt(0) === '/');
  13552. var parts = path.split(/\/+/);
  13553. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  13554. part = parts[i];
  13555. if (part === '.') {
  13556. parts.splice(i, 1);
  13557. } else if (part === '..') {
  13558. up++;
  13559. } else if (up > 0) {
  13560. if (part === '') {
  13561. // The first part is blank if the path is absolute. Trying to go
  13562. // above the root is a no-op. Therefore we can remove all '..' parts
  13563. // directly after the root.
  13564. parts.splice(i + 1, up);
  13565. up = 0;
  13566. } else {
  13567. parts.splice(i, 2);
  13568. up--;
  13569. }
  13570. }
  13571. }
  13572. path = parts.join('/');
  13573. if (path === '') {
  13574. path = isAbsolute ? '/' : '.';
  13575. }
  13576. if (url) {
  13577. url.path = path;
  13578. return urlGenerate(url);
  13579. }
  13580. return path;
  13581. }
  13582. exports.normalize = normalize;
  13583. /**
  13584. * Joins two paths/URLs.
  13585. *
  13586. * @param aRoot The root path or URL.
  13587. * @param aPath The path or URL to be joined with the root.
  13588. *
  13589. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  13590. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  13591. * first.
  13592. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  13593. * is updated with the result and aRoot is returned. Otherwise the result
  13594. * is returned.
  13595. * - If aPath is absolute, the result is aPath.
  13596. * - Otherwise the two paths are joined with a slash.
  13597. * - Joining for example 'http://' and 'www.example.com' is also supported.
  13598. */
  13599. function join(aRoot, aPath) {
  13600. var aPathUrl = urlParse(aPath);
  13601. var aRootUrl = urlParse(aRoot);
  13602. if (aRootUrl) {
  13603. aRoot = aRootUrl.path || '/';
  13604. }
  13605. // `join(foo, '//www.example.org')`
  13606. if (aPathUrl && !aPathUrl.scheme) {
  13607. if (aRootUrl) {
  13608. aPathUrl.scheme = aRootUrl.scheme;
  13609. }
  13610. return urlGenerate(aPathUrl);
  13611. }
  13612. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  13613. return aPath;
  13614. }
  13615. // `join('http://', 'www.example.com')`
  13616. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  13617. aRootUrl.host = aPath;
  13618. return urlGenerate(aRootUrl);
  13619. }
  13620. var joined = aPath.charAt(0) === '/'
  13621. ? aPath
  13622. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  13623. if (aRootUrl) {
  13624. aRootUrl.path = joined;
  13625. return urlGenerate(aRootUrl);
  13626. }
  13627. return joined;
  13628. }
  13629. exports.join = join;
  13630. /**
  13631. * Because behavior goes wacky when you set `__proto__` on objects, we
  13632. * have to prefix all the strings in our set with an arbitrary character.
  13633. *
  13634. * See https://github.com/mozilla/source-map/pull/31 and
  13635. * https://github.com/mozilla/source-map/issues/30
  13636. *
  13637. * @param String aStr
  13638. */
  13639. function toSetString(aStr) {
  13640. return '$' + aStr;
  13641. }
  13642. exports.toSetString = toSetString;
  13643. function fromSetString(aStr) {
  13644. return aStr.substr(1);
  13645. }
  13646. exports.fromSetString = fromSetString;
  13647. function relative(aRoot, aPath) {
  13648. aRoot = aRoot.replace(/\/$/, '');
  13649. var url = urlParse(aRoot);
  13650. if (aPath.charAt(0) == "/" && url && url.path == "/") {
  13651. return aPath.slice(1);
  13652. }
  13653. return aPath.indexOf(aRoot + '/') === 0
  13654. ? aPath.substr(aRoot.length + 1)
  13655. : aPath;
  13656. }
  13657. exports.relative = relative;
  13658. function strcmp(aStr1, aStr2) {
  13659. var s1 = aStr1 || "";
  13660. var s2 = aStr2 || "";
  13661. return (s1 > s2) - (s1 < s2);
  13662. }
  13663. /**
  13664. * Comparator between two mappings where the original positions are compared.
  13665. *
  13666. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  13667. * mappings with the same original source/line/column, but different generated
  13668. * line and column the same. Useful when searching for a mapping with a
  13669. * stubbed out mapping.
  13670. */
  13671. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  13672. var cmp;
  13673. cmp = strcmp(mappingA.source, mappingB.source);
  13674. if (cmp) {
  13675. return cmp;
  13676. }
  13677. cmp = mappingA.originalLine - mappingB.originalLine;
  13678. if (cmp) {
  13679. return cmp;
  13680. }
  13681. cmp = mappingA.originalColumn - mappingB.originalColumn;
  13682. if (cmp || onlyCompareOriginal) {
  13683. return cmp;
  13684. }
  13685. cmp = strcmp(mappingA.name, mappingB.name);
  13686. if (cmp) {
  13687. return cmp;
  13688. }
  13689. cmp = mappingA.generatedLine - mappingB.generatedLine;
  13690. if (cmp) {
  13691. return cmp;
  13692. }
  13693. return mappingA.generatedColumn - mappingB.generatedColumn;
  13694. };
  13695. exports.compareByOriginalPositions = compareByOriginalPositions;
  13696. /**
  13697. * Comparator between two mappings where the generated positions are
  13698. * compared.
  13699. *
  13700. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  13701. * mappings with the same generated line and column, but different
  13702. * source/name/original line and column the same. Useful when searching for a
  13703. * mapping with a stubbed out mapping.
  13704. */
  13705. function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
  13706. var cmp;
  13707. cmp = mappingA.generatedLine - mappingB.generatedLine;
  13708. if (cmp) {
  13709. return cmp;
  13710. }
  13711. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  13712. if (cmp || onlyCompareGenerated) {
  13713. return cmp;
  13714. }
  13715. cmp = strcmp(mappingA.source, mappingB.source);
  13716. if (cmp) {
  13717. return cmp;
  13718. }
  13719. cmp = mappingA.originalLine - mappingB.originalLine;
  13720. if (cmp) {
  13721. return cmp;
  13722. }
  13723. cmp = mappingA.originalColumn - mappingB.originalColumn;
  13724. if (cmp) {
  13725. return cmp;
  13726. }
  13727. return strcmp(mappingA.name, mappingB.name);
  13728. };
  13729. exports.compareByGeneratedPositions = compareByGeneratedPositions;
  13730. });
  13731. define('source-map', function (require, exports, module) {
  13732. /*
  13733. * Copyright 2009-2011 Mozilla Foundation and contributors
  13734. * Licensed under the New BSD license. See LICENSE.txt or:
  13735. * http://opensource.org/licenses/BSD-3-Clause
  13736. */
  13737. exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;
  13738. exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;
  13739. exports.SourceNode = require('./source-map/source-node').SourceNode;
  13740. });
  13741. //Distributed under the BSD license:
  13742. //Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13743. define('uglifyjs2', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) {
  13744. /***********************************************************************
  13745. A JavaScript tokenizer / parser / beautifier / compressor.
  13746. https://github.com/mishoo/UglifyJS2
  13747. -------------------------------- (C) ---------------------------------
  13748. Author: Mihai Bazon
  13749. <mihai.bazon@gmail.com>
  13750. http://mihai.bazon.net/blog
  13751. Distributed under the BSD license:
  13752. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13753. Redistribution and use in source and binary forms, with or without
  13754. modification, are permitted provided that the following conditions
  13755. are met:
  13756. * Redistributions of source code must retain the above
  13757. copyright notice, this list of conditions and the following
  13758. disclaimer.
  13759. * Redistributions in binary form must reproduce the above
  13760. copyright notice, this list of conditions and the following
  13761. disclaimer in the documentation and/or other materials
  13762. provided with the distribution.
  13763. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  13764. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13765. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  13766. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  13767. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  13768. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  13769. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  13770. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13771. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  13772. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  13773. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13774. SUCH DAMAGE.
  13775. ***********************************************************************/
  13776. "use strict";
  13777. function array_to_hash(a) {
  13778. var ret = Object.create(null);
  13779. for (var i = 0; i < a.length; ++i)
  13780. ret[a[i]] = true;
  13781. return ret;
  13782. };
  13783. function slice(a, start) {
  13784. return Array.prototype.slice.call(a, start || 0);
  13785. };
  13786. function characters(str) {
  13787. return str.split("");
  13788. };
  13789. function member(name, array) {
  13790. for (var i = array.length; --i >= 0;)
  13791. if (array[i] == name)
  13792. return true;
  13793. return false;
  13794. };
  13795. function find_if(func, array) {
  13796. for (var i = 0, n = array.length; i < n; ++i) {
  13797. if (func(array[i]))
  13798. return array[i];
  13799. }
  13800. };
  13801. function repeat_string(str, i) {
  13802. if (i <= 0) return "";
  13803. if (i == 1) return str;
  13804. var d = repeat_string(str, i >> 1);
  13805. d += d;
  13806. if (i & 1) d += str;
  13807. return d;
  13808. };
  13809. function DefaultsError(msg, defs) {
  13810. Error.call(this, msg);
  13811. this.msg = msg;
  13812. this.defs = defs;
  13813. };
  13814. DefaultsError.prototype = Object.create(Error.prototype);
  13815. DefaultsError.prototype.constructor = DefaultsError;
  13816. DefaultsError.croak = function(msg, defs) {
  13817. throw new DefaultsError(msg, defs);
  13818. };
  13819. function defaults(args, defs, croak) {
  13820. if (args === true)
  13821. args = {};
  13822. var ret = args || {};
  13823. if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i))
  13824. DefaultsError.croak("`" + i + "` is not a supported option", defs);
  13825. for (var i in defs) if (defs.hasOwnProperty(i)) {
  13826. ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i];
  13827. }
  13828. return ret;
  13829. };
  13830. function merge(obj, ext) {
  13831. for (var i in ext) if (ext.hasOwnProperty(i)) {
  13832. obj[i] = ext[i];
  13833. }
  13834. return obj;
  13835. };
  13836. function noop() {};
  13837. var MAP = (function(){
  13838. function MAP(a, f, backwards) {
  13839. var ret = [], top = [], i;
  13840. function doit() {
  13841. var val = f(a[i], i);
  13842. var is_last = val instanceof Last;
  13843. if (is_last) val = val.v;
  13844. if (val instanceof AtTop) {
  13845. val = val.v;
  13846. if (val instanceof Splice) {
  13847. top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
  13848. } else {
  13849. top.push(val);
  13850. }
  13851. }
  13852. else if (val !== skip) {
  13853. if (val instanceof Splice) {
  13854. ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
  13855. } else {
  13856. ret.push(val);
  13857. }
  13858. }
  13859. return is_last;
  13860. };
  13861. if (a instanceof Array) {
  13862. if (backwards) {
  13863. for (i = a.length; --i >= 0;) if (doit()) break;
  13864. ret.reverse();
  13865. top.reverse();
  13866. } else {
  13867. for (i = 0; i < a.length; ++i) if (doit()) break;
  13868. }
  13869. }
  13870. else {
  13871. for (i in a) if (a.hasOwnProperty(i)) if (doit()) break;
  13872. }
  13873. return top.concat(ret);
  13874. };
  13875. MAP.at_top = function(val) { return new AtTop(val) };
  13876. MAP.splice = function(val) { return new Splice(val) };
  13877. MAP.last = function(val) { return new Last(val) };
  13878. var skip = MAP.skip = {};
  13879. function AtTop(val) { this.v = val };
  13880. function Splice(val) { this.v = val };
  13881. function Last(val) { this.v = val };
  13882. return MAP;
  13883. })();
  13884. function push_uniq(array, el) {
  13885. if (array.indexOf(el) < 0)
  13886. array.push(el);
  13887. };
  13888. function string_template(text, props) {
  13889. return text.replace(/\{(.+?)\}/g, function(str, p){
  13890. return props[p];
  13891. });
  13892. };
  13893. function remove(array, el) {
  13894. for (var i = array.length; --i >= 0;) {
  13895. if (array[i] === el) array.splice(i, 1);
  13896. }
  13897. };
  13898. function mergeSort(array, cmp) {
  13899. if (array.length < 2) return array.slice();
  13900. function merge(a, b) {
  13901. var r = [], ai = 0, bi = 0, i = 0;
  13902. while (ai < a.length && bi < b.length) {
  13903. cmp(a[ai], b[bi]) <= 0
  13904. ? r[i++] = a[ai++]
  13905. : r[i++] = b[bi++];
  13906. }
  13907. if (ai < a.length) r.push.apply(r, a.slice(ai));
  13908. if (bi < b.length) r.push.apply(r, b.slice(bi));
  13909. return r;
  13910. };
  13911. function _ms(a) {
  13912. if (a.length <= 1)
  13913. return a;
  13914. var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
  13915. left = _ms(left);
  13916. right = _ms(right);
  13917. return merge(left, right);
  13918. };
  13919. return _ms(array);
  13920. };
  13921. function set_difference(a, b) {
  13922. return a.filter(function(el){
  13923. return b.indexOf(el) < 0;
  13924. });
  13925. };
  13926. function set_intersection(a, b) {
  13927. return a.filter(function(el){
  13928. return b.indexOf(el) >= 0;
  13929. });
  13930. };
  13931. // this function is taken from Acorn [1], written by Marijn Haverbeke
  13932. // [1] https://github.com/marijnh/acorn
  13933. function makePredicate(words) {
  13934. if (!(words instanceof Array)) words = words.split(" ");
  13935. var f = "", cats = [];
  13936. out: for (var i = 0; i < words.length; ++i) {
  13937. for (var j = 0; j < cats.length; ++j)
  13938. if (cats[j][0].length == words[i].length) {
  13939. cats[j].push(words[i]);
  13940. continue out;
  13941. }
  13942. cats.push([words[i]]);
  13943. }
  13944. function compareTo(arr) {
  13945. if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
  13946. f += "switch(str){";
  13947. for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
  13948. f += "return true}return false;";
  13949. }
  13950. // When there are more than three length categories, an outer
  13951. // switch first dispatches on the lengths, to save on comparisons.
  13952. if (cats.length > 3) {
  13953. cats.sort(function(a, b) {return b.length - a.length;});
  13954. f += "switch(str.length){";
  13955. for (var i = 0; i < cats.length; ++i) {
  13956. var cat = cats[i];
  13957. f += "case " + cat[0].length + ":";
  13958. compareTo(cat);
  13959. }
  13960. f += "}";
  13961. // Otherwise, simply generate a flat `switch` statement.
  13962. } else {
  13963. compareTo(words);
  13964. }
  13965. return new Function("str", f);
  13966. };
  13967. function all(array, predicate) {
  13968. for (var i = array.length; --i >= 0;)
  13969. if (!predicate(array[i]))
  13970. return false;
  13971. return true;
  13972. };
  13973. function Dictionary() {
  13974. this._values = Object.create(null);
  13975. this._size = 0;
  13976. };
  13977. Dictionary.prototype = {
  13978. set: function(key, val) {
  13979. if (!this.has(key)) ++this._size;
  13980. this._values["$" + key] = val;
  13981. return this;
  13982. },
  13983. add: function(key, val) {
  13984. if (this.has(key)) {
  13985. this.get(key).push(val);
  13986. } else {
  13987. this.set(key, [ val ]);
  13988. }
  13989. return this;
  13990. },
  13991. get: function(key) { return this._values["$" + key] },
  13992. del: function(key) {
  13993. if (this.has(key)) {
  13994. --this._size;
  13995. delete this._values["$" + key];
  13996. }
  13997. return this;
  13998. },
  13999. has: function(key) { return ("$" + key) in this._values },
  14000. each: function(f) {
  14001. for (var i in this._values)
  14002. f(this._values[i], i.substr(1));
  14003. },
  14004. size: function() {
  14005. return this._size;
  14006. },
  14007. map: function(f) {
  14008. var ret = [];
  14009. for (var i in this._values)
  14010. ret.push(f(this._values[i], i.substr(1)));
  14011. return ret;
  14012. }
  14013. };
  14014. /***********************************************************************
  14015. A JavaScript tokenizer / parser / beautifier / compressor.
  14016. https://github.com/mishoo/UglifyJS2
  14017. -------------------------------- (C) ---------------------------------
  14018. Author: Mihai Bazon
  14019. <mihai.bazon@gmail.com>
  14020. http://mihai.bazon.net/blog
  14021. Distributed under the BSD license:
  14022. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  14023. Redistribution and use in source and binary forms, with or without
  14024. modification, are permitted provided that the following conditions
  14025. are met:
  14026. * Redistributions of source code must retain the above
  14027. copyright notice, this list of conditions and the following
  14028. disclaimer.
  14029. * Redistributions in binary form must reproduce the above
  14030. copyright notice, this list of conditions and the following
  14031. disclaimer in the documentation and/or other materials
  14032. provided with the distribution.
  14033. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  14034. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14035. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  14036. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  14037. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  14038. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  14039. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  14040. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  14041. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  14042. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  14043. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  14044. SUCH DAMAGE.
  14045. ***********************************************************************/
  14046. "use strict";
  14047. function DEFNODE(type, props, methods, base) {
  14048. if (arguments.length < 4) base = AST_Node;
  14049. if (!props) props = [];
  14050. else props = props.split(/\s+/);
  14051. var self_props = props;
  14052. if (base && base.PROPS)
  14053. props = props.concat(base.PROPS);
  14054. var code = "return function AST_" + type + "(props){ if (props) { ";
  14055. for (var i = props.length; --i >= 0;) {
  14056. code += "this." + props[i] + " = props." + props[i] + ";";
  14057. }
  14058. var proto = base && new base;
  14059. if (proto && proto.initialize || (methods && methods.initialize))
  14060. code += "this.initialize();";
  14061. code += "}}";
  14062. var ctor = new Function(code)();
  14063. if (proto) {
  14064. ctor.prototype = proto;
  14065. ctor.BASE = base;
  14066. }
  14067. if (base) base.SUBCLASSES.push(ctor);
  14068. ctor.prototype.CTOR = ctor;
  14069. ctor.PROPS = props || null;
  14070. ctor.SELF_PROPS = self_props;
  14071. ctor.SUBCLASSES = [];
  14072. if (type) {
  14073. ctor.prototype.TYPE = ctor.TYPE = type;
  14074. }
  14075. if (methods) for (i in methods) if (methods.hasOwnProperty(i)) {
  14076. if (/^\$/.test(i)) {
  14077. ctor[i.substr(1)] = methods[i];
  14078. } else {
  14079. ctor.prototype[i] = methods[i];
  14080. }
  14081. }
  14082. ctor.DEFMETHOD = function(name, method) {
  14083. this.prototype[name] = method;
  14084. };
  14085. return ctor;
  14086. };
  14087. var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", {
  14088. }, null);
  14089. var AST_Node = DEFNODE("Node", "start end", {
  14090. clone: function() {
  14091. return new this.CTOR(this);
  14092. },
  14093. $documentation: "Base class of all AST nodes",
  14094. $propdoc: {
  14095. start: "[AST_Token] The first token of this node",
  14096. end: "[AST_Token] The last token of this node"
  14097. },
  14098. _walk: function(visitor) {
  14099. return visitor._visit(this);
  14100. },
  14101. walk: function(visitor) {
  14102. return this._walk(visitor); // not sure the indirection will be any help
  14103. }
  14104. }, null);
  14105. AST_Node.warn_function = null;
  14106. AST_Node.warn = function(txt, props) {
  14107. if (AST_Node.warn_function)
  14108. AST_Node.warn_function(string_template(txt, props));
  14109. };
  14110. /* -----[ statements ]----- */
  14111. var AST_Statement = DEFNODE("Statement", null, {
  14112. $documentation: "Base class of all statements",
  14113. });
  14114. var AST_Debugger = DEFNODE("Debugger", null, {
  14115. $documentation: "Represents a debugger statement",
  14116. }, AST_Statement);
  14117. var AST_Directive = DEFNODE("Directive", "value scope", {
  14118. $documentation: "Represents a directive, like \"use strict\";",
  14119. $propdoc: {
  14120. value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
  14121. scope: "[AST_Scope/S] The scope that this directive affects"
  14122. },
  14123. }, AST_Statement);
  14124. var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
  14125. $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
  14126. $propdoc: {
  14127. body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
  14128. },
  14129. _walk: function(visitor) {
  14130. return visitor._visit(this, function(){
  14131. this.body._walk(visitor);
  14132. });
  14133. }
  14134. }, AST_Statement);
  14135. function walk_body(node, visitor) {
  14136. if (node.body instanceof AST_Statement) {
  14137. node.body._walk(visitor);
  14138. }
  14139. else node.body.forEach(function(stat){
  14140. stat._walk(visitor);
  14141. });
  14142. };
  14143. var AST_Block = DEFNODE("Block", "body", {
  14144. $documentation: "A body of statements (usually bracketed)",
  14145. $propdoc: {
  14146. body: "[AST_Statement*] an array of statements"
  14147. },
  14148. _walk: function(visitor) {
  14149. return visitor._visit(this, function(){
  14150. walk_body(this, visitor);
  14151. });
  14152. }
  14153. }, AST_Statement);
  14154. var AST_BlockStatement = DEFNODE("BlockStatement", null, {
  14155. $documentation: "A block statement",
  14156. }, AST_Block);
  14157. var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
  14158. $documentation: "The empty statement (empty block or simply a semicolon)",
  14159. _walk: function(visitor) {
  14160. return visitor._visit(this);
  14161. }
  14162. }, AST_Statement);
  14163. var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
  14164. $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
  14165. $propdoc: {
  14166. body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
  14167. },
  14168. _walk: function(visitor) {
  14169. return visitor._visit(this, function(){
  14170. this.body._walk(visitor);
  14171. });
  14172. }
  14173. }, AST_Statement);
  14174. var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
  14175. $documentation: "Statement with a label",
  14176. $propdoc: {
  14177. label: "[AST_Label] a label definition"
  14178. },
  14179. _walk: function(visitor) {
  14180. return visitor._visit(this, function(){
  14181. this.label._walk(visitor);
  14182. this.body._walk(visitor);
  14183. });
  14184. }
  14185. }, AST_StatementWithBody);
  14186. var AST_IterationStatement = DEFNODE("IterationStatement", null, {
  14187. $documentation: "Internal class. All loops inherit from it."
  14188. }, AST_StatementWithBody);
  14189. var AST_DWLoop = DEFNODE("DWLoop", "condition", {
  14190. $documentation: "Base class for do/while statements",
  14191. $propdoc: {
  14192. condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
  14193. },
  14194. _walk: function(visitor) {
  14195. return visitor._visit(this, function(){
  14196. this.condition._walk(visitor);
  14197. this.body._walk(visitor);
  14198. });
  14199. }
  14200. }, AST_IterationStatement);
  14201. var AST_Do = DEFNODE("Do", null, {
  14202. $documentation: "A `do` statement",
  14203. }, AST_DWLoop);
  14204. var AST_While = DEFNODE("While", null, {
  14205. $documentation: "A `while` statement",
  14206. }, AST_DWLoop);
  14207. var AST_For = DEFNODE("For", "init condition step", {
  14208. $documentation: "A `for` statement",
  14209. $propdoc: {
  14210. init: "[AST_Node?] the `for` initialization code, or null if empty",
  14211. condition: "[AST_Node?] the `for` termination clause, or null if empty",
  14212. step: "[AST_Node?] the `for` update clause, or null if empty"
  14213. },
  14214. _walk: function(visitor) {
  14215. return visitor._visit(this, function(){
  14216. if (this.init) this.init._walk(visitor);
  14217. if (this.condition) this.condition._walk(visitor);
  14218. if (this.step) this.step._walk(visitor);
  14219. this.body._walk(visitor);
  14220. });
  14221. }
  14222. }, AST_IterationStatement);
  14223. var AST_ForIn = DEFNODE("ForIn", "init name object", {
  14224. $documentation: "A `for ... in` statement",
  14225. $propdoc: {
  14226. init: "[AST_Node] the `for/in` initialization code",
  14227. name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
  14228. object: "[AST_Node] the object that we're looping through"
  14229. },
  14230. _walk: function(visitor) {
  14231. return visitor._visit(this, function(){
  14232. this.init._walk(visitor);
  14233. this.object._walk(visitor);
  14234. this.body._walk(visitor);
  14235. });
  14236. }
  14237. }, AST_IterationStatement);
  14238. var AST_With = DEFNODE("With", "expression", {
  14239. $documentation: "A `with` statement",
  14240. $propdoc: {
  14241. expression: "[AST_Node] the `with` expression"
  14242. },
  14243. _walk: function(visitor) {
  14244. return visitor._visit(this, function(){
  14245. this.expression._walk(visitor);
  14246. this.body._walk(visitor);
  14247. });
  14248. }
  14249. }, AST_StatementWithBody);
  14250. /* -----[ scope and functions ]----- */
  14251. var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
  14252. $documentation: "Base class for all statements introducing a lexical scope",
  14253. $propdoc: {
  14254. directives: "[string*/S] an array of directives declared in this scope",
  14255. variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
  14256. functions: "[Object/S] like `variables`, but only lists function declarations",
  14257. uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
  14258. uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
  14259. parent_scope: "[AST_Scope?/S] link to the parent scope",
  14260. enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
  14261. cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
  14262. },
  14263. }, AST_Block);
  14264. var AST_Toplevel = DEFNODE("Toplevel", "globals", {
  14265. $documentation: "The toplevel scope",
  14266. $propdoc: {
  14267. globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
  14268. },
  14269. wrap_enclose: function(arg_parameter_pairs) {
  14270. var self = this;
  14271. var args = [];
  14272. var parameters = [];
  14273. arg_parameter_pairs.forEach(function(pair) {
  14274. var splitAt = pair.lastIndexOf(":");
  14275. args.push(pair.substr(0, splitAt));
  14276. parameters.push(pair.substr(splitAt + 1));
  14277. });
  14278. var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")";
  14279. wrapped_tl = parse(wrapped_tl);
  14280. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  14281. if (node instanceof AST_Directive && node.value == "$ORIG") {
  14282. return MAP.splice(self.body);
  14283. }
  14284. }));
  14285. return wrapped_tl;
  14286. },
  14287. wrap_commonjs: function(name, export_all) {
  14288. var self = this;
  14289. var to_export = [];
  14290. if (export_all) {
  14291. self.figure_out_scope();
  14292. self.walk(new TreeWalker(function(node){
  14293. if (node instanceof AST_SymbolDeclaration && node.definition().global) {
  14294. if (!find_if(function(n){ return n.name == node.name }, to_export))
  14295. to_export.push(node);
  14296. }
  14297. }));
  14298. }
  14299. var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))";
  14300. wrapped_tl = parse(wrapped_tl);
  14301. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  14302. if (node instanceof AST_SimpleStatement) {
  14303. node = node.body;
  14304. if (node instanceof AST_String) switch (node.getValue()) {
  14305. case "$ORIG":
  14306. return MAP.splice(self.body);
  14307. case "$EXPORTS":
  14308. var body = [];
  14309. to_export.forEach(function(sym){
  14310. body.push(new AST_SimpleStatement({
  14311. body: new AST_Assign({
  14312. left: new AST_Sub({
  14313. expression: new AST_SymbolRef({ name: "exports" }),
  14314. property: new AST_String({ value: sym.name }),
  14315. }),
  14316. operator: "=",
  14317. right: new AST_SymbolRef(sym),
  14318. }),
  14319. }));
  14320. });
  14321. return MAP.splice(body);
  14322. }
  14323. }
  14324. }));
  14325. return wrapped_tl;
  14326. }
  14327. }, AST_Scope);
  14328. var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
  14329. $documentation: "Base class for functions",
  14330. $propdoc: {
  14331. name: "[AST_SymbolDeclaration?] the name of this function",
  14332. argnames: "[AST_SymbolFunarg*] array of function arguments",
  14333. uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
  14334. },
  14335. _walk: function(visitor) {
  14336. return visitor._visit(this, function(){
  14337. if (this.name) this.name._walk(visitor);
  14338. this.argnames.forEach(function(arg){
  14339. arg._walk(visitor);
  14340. });
  14341. walk_body(this, visitor);
  14342. });
  14343. }
  14344. }, AST_Scope);
  14345. var AST_Accessor = DEFNODE("Accessor", null, {
  14346. $documentation: "A setter/getter function. The `name` property is always null."
  14347. }, AST_Lambda);
  14348. var AST_Function = DEFNODE("Function", null, {
  14349. $documentation: "A function expression"
  14350. }, AST_Lambda);
  14351. var AST_Defun = DEFNODE("Defun", null, {
  14352. $documentation: "A function definition"
  14353. }, AST_Lambda);
  14354. /* -----[ JUMPS ]----- */
  14355. var AST_Jump = DEFNODE("Jump", null, {
  14356. $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
  14357. }, AST_Statement);
  14358. var AST_Exit = DEFNODE("Exit", "value", {
  14359. $documentation: "Base class for “exits” (`return` and `throw`)",
  14360. $propdoc: {
  14361. value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
  14362. },
  14363. _walk: function(visitor) {
  14364. return visitor._visit(this, this.value && function(){
  14365. this.value._walk(visitor);
  14366. });
  14367. }
  14368. }, AST_Jump);
  14369. var AST_Return = DEFNODE("Return", null, {
  14370. $documentation: "A `return` statement"
  14371. }, AST_Exit);
  14372. var AST_Throw = DEFNODE("Throw", null, {
  14373. $documentation: "A `throw` statement"
  14374. }, AST_Exit);
  14375. var AST_LoopControl = DEFNODE("LoopControl", "label", {
  14376. $documentation: "Base class for loop control statements (`break` and `continue`)",
  14377. $propdoc: {
  14378. label: "[AST_LabelRef?] the label, or null if none",
  14379. },
  14380. _walk: function(visitor) {
  14381. return visitor._visit(this, this.label && function(){
  14382. this.label._walk(visitor);
  14383. });
  14384. }
  14385. }, AST_Jump);
  14386. var AST_Break = DEFNODE("Break", null, {
  14387. $documentation: "A `break` statement"
  14388. }, AST_LoopControl);
  14389. var AST_Continue = DEFNODE("Continue", null, {
  14390. $documentation: "A `continue` statement"
  14391. }, AST_LoopControl);
  14392. /* -----[ IF ]----- */
  14393. var AST_If = DEFNODE("If", "condition alternative", {
  14394. $documentation: "A `if` statement",
  14395. $propdoc: {
  14396. condition: "[AST_Node] the `if` condition",
  14397. alternative: "[AST_Statement?] the `else` part, or null if not present"
  14398. },
  14399. _walk: function(visitor) {
  14400. return visitor._visit(this, function(){
  14401. this.condition._walk(visitor);
  14402. this.body._walk(visitor);
  14403. if (this.alternative) this.alternative._walk(visitor);
  14404. });
  14405. }
  14406. }, AST_StatementWithBody);
  14407. /* -----[ SWITCH ]----- */
  14408. var AST_Switch = DEFNODE("Switch", "expression", {
  14409. $documentation: "A `switch` statement",
  14410. $propdoc: {
  14411. expression: "[AST_Node] the `switch` “discriminant”"
  14412. },
  14413. _walk: function(visitor) {
  14414. return visitor._visit(this, function(){
  14415. this.expression._walk(visitor);
  14416. walk_body(this, visitor);
  14417. });
  14418. }
  14419. }, AST_Block);
  14420. var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
  14421. $documentation: "Base class for `switch` branches",
  14422. }, AST_Block);
  14423. var AST_Default = DEFNODE("Default", null, {
  14424. $documentation: "A `default` switch branch",
  14425. }, AST_SwitchBranch);
  14426. var AST_Case = DEFNODE("Case", "expression", {
  14427. $documentation: "A `case` switch branch",
  14428. $propdoc: {
  14429. expression: "[AST_Node] the `case` expression"
  14430. },
  14431. _walk: function(visitor) {
  14432. return visitor._visit(this, function(){
  14433. this.expression._walk(visitor);
  14434. walk_body(this, visitor);
  14435. });
  14436. }
  14437. }, AST_SwitchBranch);
  14438. /* -----[ EXCEPTIONS ]----- */
  14439. var AST_Try = DEFNODE("Try", "bcatch bfinally", {
  14440. $documentation: "A `try` statement",
  14441. $propdoc: {
  14442. bcatch: "[AST_Catch?] the catch block, or null if not present",
  14443. bfinally: "[AST_Finally?] the finally block, or null if not present"
  14444. },
  14445. _walk: function(visitor) {
  14446. return visitor._visit(this, function(){
  14447. walk_body(this, visitor);
  14448. if (this.bcatch) this.bcatch._walk(visitor);
  14449. if (this.bfinally) this.bfinally._walk(visitor);
  14450. });
  14451. }
  14452. }, AST_Block);
  14453. var AST_Catch = DEFNODE("Catch", "argname", {
  14454. $documentation: "A `catch` node; only makes sense as part of a `try` statement",
  14455. $propdoc: {
  14456. argname: "[AST_SymbolCatch] symbol for the exception"
  14457. },
  14458. _walk: function(visitor) {
  14459. return visitor._visit(this, function(){
  14460. this.argname._walk(visitor);
  14461. walk_body(this, visitor);
  14462. });
  14463. }
  14464. }, AST_Block);
  14465. var AST_Finally = DEFNODE("Finally", null, {
  14466. $documentation: "A `finally` node; only makes sense as part of a `try` statement"
  14467. }, AST_Block);
  14468. /* -----[ VAR/CONST ]----- */
  14469. var AST_Definitions = DEFNODE("Definitions", "definitions", {
  14470. $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
  14471. $propdoc: {
  14472. definitions: "[AST_VarDef*] array of variable definitions"
  14473. },
  14474. _walk: function(visitor) {
  14475. return visitor._visit(this, function(){
  14476. this.definitions.forEach(function(def){
  14477. def._walk(visitor);
  14478. });
  14479. });
  14480. }
  14481. }, AST_Statement);
  14482. var AST_Var = DEFNODE("Var", null, {
  14483. $documentation: "A `var` statement"
  14484. }, AST_Definitions);
  14485. var AST_Const = DEFNODE("Const", null, {
  14486. $documentation: "A `const` statement"
  14487. }, AST_Definitions);
  14488. var AST_VarDef = DEFNODE("VarDef", "name value", {
  14489. $documentation: "A variable declaration; only appears in a AST_Definitions node",
  14490. $propdoc: {
  14491. name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
  14492. value: "[AST_Node?] initializer, or null of there's no initializer"
  14493. },
  14494. _walk: function(visitor) {
  14495. return visitor._visit(this, function(){
  14496. this.name._walk(visitor);
  14497. if (this.value) this.value._walk(visitor);
  14498. });
  14499. }
  14500. });
  14501. /* -----[ OTHER ]----- */
  14502. var AST_Call = DEFNODE("Call", "expression args", {
  14503. $documentation: "A function call expression",
  14504. $propdoc: {
  14505. expression: "[AST_Node] expression to invoke as function",
  14506. args: "[AST_Node*] array of arguments"
  14507. },
  14508. _walk: function(visitor) {
  14509. return visitor._visit(this, function(){
  14510. this.expression._walk(visitor);
  14511. this.args.forEach(function(arg){
  14512. arg._walk(visitor);
  14513. });
  14514. });
  14515. }
  14516. });
  14517. var AST_New = DEFNODE("New", null, {
  14518. $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
  14519. }, AST_Call);
  14520. var AST_Seq = DEFNODE("Seq", "car cdr", {
  14521. $documentation: "A sequence expression (two comma-separated expressions)",
  14522. $propdoc: {
  14523. car: "[AST_Node] first element in sequence",
  14524. cdr: "[AST_Node] second element in sequence"
  14525. },
  14526. $cons: function(x, y) {
  14527. var seq = new AST_Seq(x);
  14528. seq.car = x;
  14529. seq.cdr = y;
  14530. return seq;
  14531. },
  14532. $from_array: function(array) {
  14533. if (array.length == 0) return null;
  14534. if (array.length == 1) return array[0].clone();
  14535. var list = null;
  14536. for (var i = array.length; --i >= 0;) {
  14537. list = AST_Seq.cons(array[i], list);
  14538. }
  14539. var p = list;
  14540. while (p) {
  14541. if (p.cdr && !p.cdr.cdr) {
  14542. p.cdr = p.cdr.car;
  14543. break;
  14544. }
  14545. p = p.cdr;
  14546. }
  14547. return list;
  14548. },
  14549. to_array: function() {
  14550. var p = this, a = [];
  14551. while (p) {
  14552. a.push(p.car);
  14553. if (p.cdr && !(p.cdr instanceof AST_Seq)) {
  14554. a.push(p.cdr);
  14555. break;
  14556. }
  14557. p = p.cdr;
  14558. }
  14559. return a;
  14560. },
  14561. add: function(node) {
  14562. var p = this;
  14563. while (p) {
  14564. if (!(p.cdr instanceof AST_Seq)) {
  14565. var cell = AST_Seq.cons(p.cdr, node);
  14566. return p.cdr = cell;
  14567. }
  14568. p = p.cdr;
  14569. }
  14570. },
  14571. _walk: function(visitor) {
  14572. return visitor._visit(this, function(){
  14573. this.car._walk(visitor);
  14574. if (this.cdr) this.cdr._walk(visitor);
  14575. });
  14576. }
  14577. });
  14578. var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
  14579. $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
  14580. $propdoc: {
  14581. expression: "[AST_Node] the “container” expression",
  14582. property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"
  14583. }
  14584. });
  14585. var AST_Dot = DEFNODE("Dot", null, {
  14586. $documentation: "A dotted property access expression",
  14587. _walk: function(visitor) {
  14588. return visitor._visit(this, function(){
  14589. this.expression._walk(visitor);
  14590. });
  14591. }
  14592. }, AST_PropAccess);
  14593. var AST_Sub = DEFNODE("Sub", null, {
  14594. $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
  14595. _walk: function(visitor) {
  14596. return visitor._visit(this, function(){
  14597. this.expression._walk(visitor);
  14598. this.property._walk(visitor);
  14599. });
  14600. }
  14601. }, AST_PropAccess);
  14602. var AST_Unary = DEFNODE("Unary", "operator expression", {
  14603. $documentation: "Base class for unary expressions",
  14604. $propdoc: {
  14605. operator: "[string] the operator",
  14606. expression: "[AST_Node] expression that this unary operator applies to"
  14607. },
  14608. _walk: function(visitor) {
  14609. return visitor._visit(this, function(){
  14610. this.expression._walk(visitor);
  14611. });
  14612. }
  14613. });
  14614. var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
  14615. $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
  14616. }, AST_Unary);
  14617. var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
  14618. $documentation: "Unary postfix expression, i.e. `i++`"
  14619. }, AST_Unary);
  14620. var AST_Binary = DEFNODE("Binary", "left operator right", {
  14621. $documentation: "Binary expression, i.e. `a + b`",
  14622. $propdoc: {
  14623. left: "[AST_Node] left-hand side expression",
  14624. operator: "[string] the operator",
  14625. right: "[AST_Node] right-hand side expression"
  14626. },
  14627. _walk: function(visitor) {
  14628. return visitor._visit(this, function(){
  14629. this.left._walk(visitor);
  14630. this.right._walk(visitor);
  14631. });
  14632. }
  14633. });
  14634. var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
  14635. $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
  14636. $propdoc: {
  14637. condition: "[AST_Node]",
  14638. consequent: "[AST_Node]",
  14639. alternative: "[AST_Node]"
  14640. },
  14641. _walk: function(visitor) {
  14642. return visitor._visit(this, function(){
  14643. this.condition._walk(visitor);
  14644. this.consequent._walk(visitor);
  14645. this.alternative._walk(visitor);
  14646. });
  14647. }
  14648. });
  14649. var AST_Assign = DEFNODE("Assign", null, {
  14650. $documentation: "An assignment expression — `a = b + 5`",
  14651. }, AST_Binary);
  14652. /* -----[ LITERALS ]----- */
  14653. var AST_Array = DEFNODE("Array", "elements", {
  14654. $documentation: "An array literal",
  14655. $propdoc: {
  14656. elements: "[AST_Node*] array of elements"
  14657. },
  14658. _walk: function(visitor) {
  14659. return visitor._visit(this, function(){
  14660. this.elements.forEach(function(el){
  14661. el._walk(visitor);
  14662. });
  14663. });
  14664. }
  14665. });
  14666. var AST_Object = DEFNODE("Object", "properties", {
  14667. $documentation: "An object literal",
  14668. $propdoc: {
  14669. properties: "[AST_ObjectProperty*] array of properties"
  14670. },
  14671. _walk: function(visitor) {
  14672. return visitor._visit(this, function(){
  14673. this.properties.forEach(function(prop){
  14674. prop._walk(visitor);
  14675. });
  14676. });
  14677. }
  14678. });
  14679. var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
  14680. $documentation: "Base class for literal object properties",
  14681. $propdoc: {
  14682. key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.",
  14683. value: "[AST_Node] property value. For setters and getters this is an AST_Function."
  14684. },
  14685. _walk: function(visitor) {
  14686. return visitor._visit(this, function(){
  14687. this.value._walk(visitor);
  14688. });
  14689. }
  14690. });
  14691. var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, {
  14692. $documentation: "A key: value object property",
  14693. }, AST_ObjectProperty);
  14694. var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
  14695. $documentation: "An object setter property",
  14696. }, AST_ObjectProperty);
  14697. var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
  14698. $documentation: "An object getter property",
  14699. }, AST_ObjectProperty);
  14700. var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
  14701. $propdoc: {
  14702. name: "[string] name of this symbol",
  14703. scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
  14704. thedef: "[SymbolDef/S] the definition of this symbol"
  14705. },
  14706. $documentation: "Base class for all symbols",
  14707. });
  14708. var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
  14709. $documentation: "The name of a property accessor (setter/getter function)"
  14710. }, AST_Symbol);
  14711. var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
  14712. $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
  14713. $propdoc: {
  14714. init: "[AST_Node*/S] array of initializers for this declaration."
  14715. }
  14716. }, AST_Symbol);
  14717. var AST_SymbolVar = DEFNODE("SymbolVar", null, {
  14718. $documentation: "Symbol defining a variable",
  14719. }, AST_SymbolDeclaration);
  14720. var AST_SymbolConst = DEFNODE("SymbolConst", null, {
  14721. $documentation: "A constant declaration"
  14722. }, AST_SymbolDeclaration);
  14723. var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
  14724. $documentation: "Symbol naming a function argument",
  14725. }, AST_SymbolVar);
  14726. var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
  14727. $documentation: "Symbol defining a function",
  14728. }, AST_SymbolDeclaration);
  14729. var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
  14730. $documentation: "Symbol naming a function expression",
  14731. }, AST_SymbolDeclaration);
  14732. var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
  14733. $documentation: "Symbol naming the exception in catch",
  14734. }, AST_SymbolDeclaration);
  14735. var AST_Label = DEFNODE("Label", "references", {
  14736. $documentation: "Symbol naming a label (declaration)",
  14737. $propdoc: {
  14738. references: "[AST_LoopControl*] a list of nodes referring to this label"
  14739. },
  14740. initialize: function() {
  14741. this.references = [];
  14742. this.thedef = this;
  14743. }
  14744. }, AST_Symbol);
  14745. var AST_SymbolRef = DEFNODE("SymbolRef", null, {
  14746. $documentation: "Reference to some symbol (not definition/declaration)",
  14747. }, AST_Symbol);
  14748. var AST_LabelRef = DEFNODE("LabelRef", null, {
  14749. $documentation: "Reference to a label symbol",
  14750. }, AST_Symbol);
  14751. var AST_This = DEFNODE("This", null, {
  14752. $documentation: "The `this` symbol",
  14753. }, AST_Symbol);
  14754. var AST_Constant = DEFNODE("Constant", null, {
  14755. $documentation: "Base class for all constants",
  14756. getValue: function() {
  14757. return this.value;
  14758. }
  14759. });
  14760. var AST_String = DEFNODE("String", "value", {
  14761. $documentation: "A string literal",
  14762. $propdoc: {
  14763. value: "[string] the contents of this string"
  14764. }
  14765. }, AST_Constant);
  14766. var AST_Number = DEFNODE("Number", "value", {
  14767. $documentation: "A number literal",
  14768. $propdoc: {
  14769. value: "[number] the numeric value"
  14770. }
  14771. }, AST_Constant);
  14772. var AST_RegExp = DEFNODE("RegExp", "value", {
  14773. $documentation: "A regexp literal",
  14774. $propdoc: {
  14775. value: "[RegExp] the actual regexp"
  14776. }
  14777. }, AST_Constant);
  14778. var AST_Atom = DEFNODE("Atom", null, {
  14779. $documentation: "Base class for atoms",
  14780. }, AST_Constant);
  14781. var AST_Null = DEFNODE("Null", null, {
  14782. $documentation: "The `null` atom",
  14783. value: null
  14784. }, AST_Atom);
  14785. var AST_NaN = DEFNODE("NaN", null, {
  14786. $documentation: "The impossible value",
  14787. value: 0/0
  14788. }, AST_Atom);
  14789. var AST_Undefined = DEFNODE("Undefined", null, {
  14790. $documentation: "The `undefined` value",
  14791. value: (function(){}())
  14792. }, AST_Atom);
  14793. var AST_Hole = DEFNODE("Hole", null, {
  14794. $documentation: "A hole in an array",
  14795. value: (function(){}())
  14796. }, AST_Atom);
  14797. var AST_Infinity = DEFNODE("Infinity", null, {
  14798. $documentation: "The `Infinity` value",
  14799. value: 1/0
  14800. }, AST_Atom);
  14801. var AST_Boolean = DEFNODE("Boolean", null, {
  14802. $documentation: "Base class for booleans",
  14803. }, AST_Atom);
  14804. var AST_False = DEFNODE("False", null, {
  14805. $documentation: "The `false` atom",
  14806. value: false
  14807. }, AST_Boolean);
  14808. var AST_True = DEFNODE("True", null, {
  14809. $documentation: "The `true` atom",
  14810. value: true
  14811. }, AST_Boolean);
  14812. /* -----[ TreeWalker ]----- */
  14813. function TreeWalker(callback) {
  14814. this.visit = callback;
  14815. this.stack = [];
  14816. };
  14817. TreeWalker.prototype = {
  14818. _visit: function(node, descend) {
  14819. this.stack.push(node);
  14820. var ret = this.visit(node, descend ? function(){
  14821. descend.call(node);
  14822. } : noop);
  14823. if (!ret && descend) {
  14824. descend.call(node);
  14825. }
  14826. this.stack.pop();
  14827. return ret;
  14828. },
  14829. parent: function(n) {
  14830. return this.stack[this.stack.length - 2 - (n || 0)];
  14831. },
  14832. push: function (node) {
  14833. this.stack.push(node);
  14834. },
  14835. pop: function() {
  14836. return this.stack.pop();
  14837. },
  14838. self: function() {
  14839. return this.stack[this.stack.length - 1];
  14840. },
  14841. find_parent: function(type) {
  14842. var stack = this.stack;
  14843. for (var i = stack.length; --i >= 0;) {
  14844. var x = stack[i];
  14845. if (x instanceof type) return x;
  14846. }
  14847. },
  14848. has_directive: function(type) {
  14849. return this.find_parent(AST_Scope).has_directive(type);
  14850. },
  14851. in_boolean_context: function() {
  14852. var stack = this.stack;
  14853. var i = stack.length, self = stack[--i];
  14854. while (i > 0) {
  14855. var p = stack[--i];
  14856. if ((p instanceof AST_If && p.condition === self) ||
  14857. (p instanceof AST_Conditional && p.condition === self) ||
  14858. (p instanceof AST_DWLoop && p.condition === self) ||
  14859. (p instanceof AST_For && p.condition === self) ||
  14860. (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self))
  14861. {
  14862. return true;
  14863. }
  14864. if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")))
  14865. return false;
  14866. self = p;
  14867. }
  14868. },
  14869. loopcontrol_target: function(label) {
  14870. var stack = this.stack;
  14871. if (label) for (var i = stack.length; --i >= 0;) {
  14872. var x = stack[i];
  14873. if (x instanceof AST_LabeledStatement && x.label.name == label.name) {
  14874. return x.body;
  14875. }
  14876. } else for (var i = stack.length; --i >= 0;) {
  14877. var x = stack[i];
  14878. if (x instanceof AST_Switch || x instanceof AST_IterationStatement)
  14879. return x;
  14880. }
  14881. }
  14882. };
  14883. /***********************************************************************
  14884. A JavaScript tokenizer / parser / beautifier / compressor.
  14885. https://github.com/mishoo/UglifyJS2
  14886. -------------------------------- (C) ---------------------------------
  14887. Author: Mihai Bazon
  14888. <mihai.bazon@gmail.com>
  14889. http://mihai.bazon.net/blog
  14890. Distributed under the BSD license:
  14891. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  14892. Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  14893. Redistribution and use in source and binary forms, with or without
  14894. modification, are permitted provided that the following conditions
  14895. are met:
  14896. * Redistributions of source code must retain the above
  14897. copyright notice, this list of conditions and the following
  14898. disclaimer.
  14899. * Redistributions in binary form must reproduce the above
  14900. copyright notice, this list of conditions and the following
  14901. disclaimer in the documentation and/or other materials
  14902. provided with the distribution.
  14903. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  14904. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14905. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  14906. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  14907. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  14908. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  14909. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  14910. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  14911. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  14912. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  14913. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  14914. SUCH DAMAGE.
  14915. ***********************************************************************/
  14916. "use strict";
  14917. var KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with';
  14918. var KEYWORDS_ATOM = 'false null true';
  14919. var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized this throws transient volatile yield'
  14920. + " " + KEYWORDS_ATOM + " " + KEYWORDS;
  14921. var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case';
  14922. KEYWORDS = makePredicate(KEYWORDS);
  14923. RESERVED_WORDS = makePredicate(RESERVED_WORDS);
  14924. KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
  14925. KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
  14926. var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^"));
  14927. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  14928. var RE_OCT_NUMBER = /^0[0-7]+$/;
  14929. var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
  14930. var OPERATORS = makePredicate([
  14931. "in",
  14932. "instanceof",
  14933. "typeof",
  14934. "new",
  14935. "void",
  14936. "delete",
  14937. "++",
  14938. "--",
  14939. "+",
  14940. "-",
  14941. "!",
  14942. "~",
  14943. "&",
  14944. "|",
  14945. "^",
  14946. "*",
  14947. "/",
  14948. "%",
  14949. ">>",
  14950. "<<",
  14951. ">>>",
  14952. "<",
  14953. ">",
  14954. "<=",
  14955. ">=",
  14956. "==",
  14957. "===",
  14958. "!=",
  14959. "!==",
  14960. "?",
  14961. "=",
  14962. "+=",
  14963. "-=",
  14964. "/=",
  14965. "*=",
  14966. "%=",
  14967. ">>=",
  14968. "<<=",
  14969. ">>>=",
  14970. "|=",
  14971. "^=",
  14972. "&=",
  14973. "&&",
  14974. "||"
  14975. ]);
  14976. var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"));
  14977. var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:"));
  14978. var PUNC_CHARS = makePredicate(characters("[]{}(),;:"));
  14979. var REGEXP_MODIFIERS = makePredicate(characters("gmsiy"));
  14980. /* -----[ Tokenizer ]----- */
  14981. // regexps adapted from http://xregexp.com/plugins/#unicode
  14982. var UNICODE = {
  14983. letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u097B-\\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\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\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\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1159\\u115F-\\u11A2\\u11A8-\\u11F9\\u1200-\\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-\\u1676\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19A9\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\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-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2C6F\\u2C71-\\u2C7D\\u2C80-\\u2CE4\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400\\u4DB5\\u4E00\\u9FC3\\uA000-\\uA48C\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA90A-\\uA925\\uA930-\\uA946\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAC00\\uD7A3\\uF900-\\uFA2D\\uFA30-\\uFA6A\\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]"),
  14984. non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
  14985. space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"),
  14986. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
  14987. };
  14988. function is_letter(code) {
  14989. return (code >= 97 && code <= 122)
  14990. || (code >= 65 && code <= 90)
  14991. || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code)));
  14992. };
  14993. function is_digit(code) {
  14994. return code >= 48 && code <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9
  14995. };
  14996. function is_alphanumeric_char(code) {
  14997. return is_digit(code) || is_letter(code);
  14998. };
  14999. function is_unicode_combining_mark(ch) {
  15000. return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
  15001. };
  15002. function is_unicode_connector_punctuation(ch) {
  15003. return UNICODE.connector_punctuation.test(ch);
  15004. };
  15005. function is_identifier(name) {
  15006. return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name);
  15007. };
  15008. function is_identifier_start(code) {
  15009. return code == 36 || code == 95 || is_letter(code);
  15010. };
  15011. function is_identifier_char(ch) {
  15012. var code = ch.charCodeAt(0);
  15013. return is_identifier_start(code)
  15014. || is_digit(code)
  15015. || code == 8204 // \u200c: zero-width non-joiner <ZWNJ>
  15016. || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  15017. || is_unicode_combining_mark(ch)
  15018. || is_unicode_connector_punctuation(ch)
  15019. ;
  15020. };
  15021. function is_identifier_string(str){
  15022. return /^[a-z_$][a-z0-9_$]*$/i.test(str);
  15023. };
  15024. function parse_js_number(num) {
  15025. if (RE_HEX_NUMBER.test(num)) {
  15026. return parseInt(num.substr(2), 16);
  15027. } else if (RE_OCT_NUMBER.test(num)) {
  15028. return parseInt(num.substr(1), 8);
  15029. } else if (RE_DEC_NUMBER.test(num)) {
  15030. return parseFloat(num);
  15031. }
  15032. };
  15033. function JS_Parse_Error(message, line, col, pos) {
  15034. this.message = message;
  15035. this.line = line;
  15036. this.col = col;
  15037. this.pos = pos;
  15038. this.stack = new Error().stack;
  15039. };
  15040. JS_Parse_Error.prototype.toString = function() {
  15041. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  15042. };
  15043. function js_error(message, filename, line, col, pos) {
  15044. throw new JS_Parse_Error(message, line, col, pos);
  15045. };
  15046. function is_token(token, type, val) {
  15047. return token.type == type && (val == null || token.value == val);
  15048. };
  15049. var EX_EOF = {};
  15050. function tokenizer($TEXT, filename, html5_comments) {
  15051. var S = {
  15052. text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/\uFEFF/g, ''),
  15053. filename : filename,
  15054. pos : 0,
  15055. tokpos : 0,
  15056. line : 1,
  15057. tokline : 0,
  15058. col : 0,
  15059. tokcol : 0,
  15060. newline_before : false,
  15061. regex_allowed : false,
  15062. comments_before : []
  15063. };
  15064. function peek() { return S.text.charAt(S.pos); };
  15065. function next(signal_eof, in_string) {
  15066. var ch = S.text.charAt(S.pos++);
  15067. if (signal_eof && !ch)
  15068. throw EX_EOF;
  15069. if (ch == "\n") {
  15070. S.newline_before = S.newline_before || !in_string;
  15071. ++S.line;
  15072. S.col = 0;
  15073. } else {
  15074. ++S.col;
  15075. }
  15076. return ch;
  15077. };
  15078. function forward(i) {
  15079. while (i-- > 0) next();
  15080. };
  15081. function looking_at(str) {
  15082. return S.text.substr(S.pos, str.length) == str;
  15083. };
  15084. function find(what, signal_eof) {
  15085. var pos = S.text.indexOf(what, S.pos);
  15086. if (signal_eof && pos == -1) throw EX_EOF;
  15087. return pos;
  15088. };
  15089. function start_token() {
  15090. S.tokline = S.line;
  15091. S.tokcol = S.col;
  15092. S.tokpos = S.pos;
  15093. };
  15094. var prev_was_dot = false;
  15095. function token(type, value, is_comment) {
  15096. S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) ||
  15097. (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) ||
  15098. (type == "punc" && PUNC_BEFORE_EXPRESSION(value)));
  15099. prev_was_dot = (type == "punc" && value == ".");
  15100. var ret = {
  15101. type : type,
  15102. value : value,
  15103. line : S.tokline,
  15104. col : S.tokcol,
  15105. pos : S.tokpos,
  15106. endpos : S.pos,
  15107. nlb : S.newline_before,
  15108. file : filename
  15109. };
  15110. if (!is_comment) {
  15111. ret.comments_before = S.comments_before;
  15112. S.comments_before = [];
  15113. // make note of any newlines in the comments that came before
  15114. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  15115. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  15116. }
  15117. }
  15118. S.newline_before = false;
  15119. return new AST_Token(ret);
  15120. };
  15121. function skip_whitespace() {
  15122. while (WHITESPACE_CHARS(peek()))
  15123. next();
  15124. };
  15125. function read_while(pred) {
  15126. var ret = "", ch, i = 0;
  15127. while ((ch = peek()) && pred(ch, i++))
  15128. ret += next();
  15129. return ret;
  15130. };
  15131. function parse_error(err) {
  15132. js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
  15133. };
  15134. function read_num(prefix) {
  15135. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  15136. var num = read_while(function(ch, i){
  15137. var code = ch.charCodeAt(0);
  15138. switch (code) {
  15139. case 120: case 88: // xX
  15140. return has_x ? false : (has_x = true);
  15141. case 101: case 69: // eE
  15142. return has_x ? true : has_e ? false : (has_e = after_e = true);
  15143. case 45: // -
  15144. return after_e || (i == 0 && !prefix);
  15145. case 43: // +
  15146. return after_e;
  15147. case (after_e = false, 46): // .
  15148. return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false;
  15149. }
  15150. return is_alphanumeric_char(code);
  15151. });
  15152. if (prefix) num = prefix + num;
  15153. var valid = parse_js_number(num);
  15154. if (!isNaN(valid)) {
  15155. return token("num", valid);
  15156. } else {
  15157. parse_error("Invalid syntax: " + num);
  15158. }
  15159. };
  15160. function read_escaped_char(in_string) {
  15161. var ch = next(true, in_string);
  15162. switch (ch.charCodeAt(0)) {
  15163. case 110 : return "\n";
  15164. case 114 : return "\r";
  15165. case 116 : return "\t";
  15166. case 98 : return "\b";
  15167. case 118 : return "\u000b"; // \v
  15168. case 102 : return "\f";
  15169. case 48 : return "\0";
  15170. case 120 : return String.fromCharCode(hex_bytes(2)); // \x
  15171. case 117 : return String.fromCharCode(hex_bytes(4)); // \u
  15172. case 10 : return ""; // newline
  15173. default : return ch;
  15174. }
  15175. };
  15176. function hex_bytes(n) {
  15177. var num = 0;
  15178. for (; n > 0; --n) {
  15179. var digit = parseInt(next(true), 16);
  15180. if (isNaN(digit))
  15181. parse_error("Invalid hex-character pattern in string");
  15182. num = (num << 4) | digit;
  15183. }
  15184. return num;
  15185. };
  15186. var read_string = with_eof_error("Unterminated string constant", function(){
  15187. var quote = next(), ret = "";
  15188. for (;;) {
  15189. var ch = next(true);
  15190. if (ch == "\\") {
  15191. // read OctalEscapeSequence (XXX: deprecated if "strict mode")
  15192. // https://github.com/mishoo/UglifyJS/issues/178
  15193. var octal_len = 0, first = null;
  15194. ch = read_while(function(ch){
  15195. if (ch >= "0" && ch <= "7") {
  15196. if (!first) {
  15197. first = ch;
  15198. return ++octal_len;
  15199. }
  15200. else if (first <= "3" && octal_len <= 2) return ++octal_len;
  15201. else if (first >= "4" && octal_len <= 1) return ++octal_len;
  15202. }
  15203. return false;
  15204. });
  15205. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
  15206. else ch = read_escaped_char(true);
  15207. }
  15208. else if (ch == quote) break;
  15209. ret += ch;
  15210. }
  15211. return token("string", ret);
  15212. });
  15213. function skip_line_comment(type) {
  15214. var regex_allowed = S.regex_allowed;
  15215. var i = find("\n"), ret;
  15216. if (i == -1) {
  15217. ret = S.text.substr(S.pos);
  15218. S.pos = S.text.length;
  15219. } else {
  15220. ret = S.text.substring(S.pos, i);
  15221. S.pos = i;
  15222. }
  15223. S.comments_before.push(token(type, ret, true));
  15224. S.regex_allowed = regex_allowed;
  15225. return next_token();
  15226. };
  15227. var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){
  15228. var regex_allowed = S.regex_allowed;
  15229. var i = find("*/", true);
  15230. var text = S.text.substring(S.pos, i);
  15231. var a = text.split("\n"), n = a.length;
  15232. // update stream position
  15233. S.pos = i + 2;
  15234. S.line += n - 1;
  15235. if (n > 1) S.col = a[n - 1].length;
  15236. else S.col += a[n - 1].length;
  15237. S.col += 2;
  15238. var nlb = S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  15239. S.comments_before.push(token("comment2", text, true));
  15240. S.regex_allowed = regex_allowed;
  15241. S.newline_before = nlb;
  15242. return next_token();
  15243. });
  15244. function read_name() {
  15245. var backslash = false, name = "", ch, escaped = false, hex;
  15246. while ((ch = peek()) != null) {
  15247. if (!backslash) {
  15248. if (ch == "\\") escaped = backslash = true, next();
  15249. else if (is_identifier_char(ch)) name += next();
  15250. else break;
  15251. }
  15252. else {
  15253. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  15254. ch = read_escaped_char();
  15255. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  15256. name += ch;
  15257. backslash = false;
  15258. }
  15259. }
  15260. if (KEYWORDS(name) && escaped) {
  15261. hex = name.charCodeAt(0).toString(16).toUpperCase();
  15262. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  15263. }
  15264. return name;
  15265. };
  15266. var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){
  15267. var prev_backslash = false, ch, in_class = false;
  15268. while ((ch = next(true))) if (prev_backslash) {
  15269. regexp += "\\" + ch;
  15270. prev_backslash = false;
  15271. } else if (ch == "[") {
  15272. in_class = true;
  15273. regexp += ch;
  15274. } else if (ch == "]" && in_class) {
  15275. in_class = false;
  15276. regexp += ch;
  15277. } else if (ch == "/" && !in_class) {
  15278. break;
  15279. } else if (ch == "\\") {
  15280. prev_backslash = true;
  15281. } else {
  15282. regexp += ch;
  15283. }
  15284. var mods = read_name();
  15285. return token("regexp", new RegExp(regexp, mods));
  15286. });
  15287. function read_operator(prefix) {
  15288. function grow(op) {
  15289. if (!peek()) return op;
  15290. var bigger = op + peek();
  15291. if (OPERATORS(bigger)) {
  15292. next();
  15293. return grow(bigger);
  15294. } else {
  15295. return op;
  15296. }
  15297. };
  15298. return token("operator", grow(prefix || next()));
  15299. };
  15300. function handle_slash() {
  15301. next();
  15302. switch (peek()) {
  15303. case "/":
  15304. next();
  15305. return skip_line_comment("comment1");
  15306. case "*":
  15307. next();
  15308. return skip_multiline_comment();
  15309. }
  15310. return S.regex_allowed ? read_regexp("") : read_operator("/");
  15311. };
  15312. function handle_dot() {
  15313. next();
  15314. return is_digit(peek().charCodeAt(0))
  15315. ? read_num(".")
  15316. : token("punc", ".");
  15317. };
  15318. function read_word() {
  15319. var word = read_name();
  15320. if (prev_was_dot) return token("name", word);
  15321. return KEYWORDS_ATOM(word) ? token("atom", word)
  15322. : !KEYWORDS(word) ? token("name", word)
  15323. : OPERATORS(word) ? token("operator", word)
  15324. : token("keyword", word);
  15325. };
  15326. function with_eof_error(eof_error, cont) {
  15327. return function(x) {
  15328. try {
  15329. return cont(x);
  15330. } catch(ex) {
  15331. if (ex === EX_EOF) parse_error(eof_error);
  15332. else throw ex;
  15333. }
  15334. };
  15335. };
  15336. function next_token(force_regexp) {
  15337. if (force_regexp != null)
  15338. return read_regexp(force_regexp);
  15339. skip_whitespace();
  15340. start_token();
  15341. if (html5_comments) {
  15342. if (looking_at("<!--")) {
  15343. forward(4);
  15344. return skip_line_comment("comment3");
  15345. }
  15346. if (looking_at("-->") && S.newline_before) {
  15347. forward(3);
  15348. return skip_line_comment("comment4");
  15349. }
  15350. }
  15351. var ch = peek();
  15352. if (!ch) return token("eof");
  15353. var code = ch.charCodeAt(0);
  15354. switch (code) {
  15355. case 34: case 39: return read_string();
  15356. case 46: return handle_dot();
  15357. case 47: return handle_slash();
  15358. }
  15359. if (is_digit(code)) return read_num();
  15360. if (PUNC_CHARS(ch)) return token("punc", next());
  15361. if (OPERATOR_CHARS(ch)) return read_operator();
  15362. if (code == 92 || is_identifier_start(code)) return read_word();
  15363. parse_error("Unexpected character '" + ch + "'");
  15364. };
  15365. next_token.context = function(nc) {
  15366. if (nc) S = nc;
  15367. return S;
  15368. };
  15369. return next_token;
  15370. };
  15371. /* -----[ Parser (constants) ]----- */
  15372. var UNARY_PREFIX = makePredicate([
  15373. "typeof",
  15374. "void",
  15375. "delete",
  15376. "--",
  15377. "++",
  15378. "!",
  15379. "~",
  15380. "-",
  15381. "+"
  15382. ]);
  15383. var UNARY_POSTFIX = makePredicate([ "--", "++" ]);
  15384. var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]);
  15385. var PRECEDENCE = (function(a, ret){
  15386. for (var i = 0; i < a.length; ++i) {
  15387. var b = a[i];
  15388. for (var j = 0; j < b.length; ++j) {
  15389. ret[b[j]] = i + 1;
  15390. }
  15391. }
  15392. return ret;
  15393. })(
  15394. [
  15395. ["||"],
  15396. ["&&"],
  15397. ["|"],
  15398. ["^"],
  15399. ["&"],
  15400. ["==", "===", "!=", "!=="],
  15401. ["<", ">", "<=", ">=", "in", "instanceof"],
  15402. [">>", "<<", ">>>"],
  15403. ["+", "-"],
  15404. ["*", "/", "%"]
  15405. ],
  15406. {}
  15407. );
  15408. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  15409. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  15410. /* -----[ Parser ]----- */
  15411. function parse($TEXT, options) {
  15412. options = defaults(options, {
  15413. strict : false,
  15414. filename : null,
  15415. toplevel : null,
  15416. expression : false,
  15417. html5_comments : true,
  15418. bare_returns : false,
  15419. });
  15420. var S = {
  15421. input : (typeof $TEXT == "string"
  15422. ? tokenizer($TEXT, options.filename,
  15423. options.html5_comments)
  15424. : $TEXT),
  15425. token : null,
  15426. prev : null,
  15427. peeked : null,
  15428. in_function : 0,
  15429. in_directives : true,
  15430. in_loop : 0,
  15431. labels : []
  15432. };
  15433. S.token = next();
  15434. function is(type, value) {
  15435. return is_token(S.token, type, value);
  15436. };
  15437. function peek() { return S.peeked || (S.peeked = S.input()); };
  15438. function next() {
  15439. S.prev = S.token;
  15440. if (S.peeked) {
  15441. S.token = S.peeked;
  15442. S.peeked = null;
  15443. } else {
  15444. S.token = S.input();
  15445. }
  15446. S.in_directives = S.in_directives && (
  15447. S.token.type == "string" || is("punc", ";")
  15448. );
  15449. return S.token;
  15450. };
  15451. function prev() {
  15452. return S.prev;
  15453. };
  15454. function croak(msg, line, col, pos) {
  15455. var ctx = S.input.context();
  15456. js_error(msg,
  15457. ctx.filename,
  15458. line != null ? line : ctx.tokline,
  15459. col != null ? col : ctx.tokcol,
  15460. pos != null ? pos : ctx.tokpos);
  15461. };
  15462. function token_error(token, msg) {
  15463. croak(msg, token.line, token.col);
  15464. };
  15465. function unexpected(token) {
  15466. if (token == null)
  15467. token = S.token;
  15468. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  15469. };
  15470. function expect_token(type, val) {
  15471. if (is(type, val)) {
  15472. return next();
  15473. }
  15474. token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");
  15475. };
  15476. function expect(punc) { return expect_token("punc", punc); };
  15477. function can_insert_semicolon() {
  15478. return !options.strict && (
  15479. S.token.nlb || is("eof") || is("punc", "}")
  15480. );
  15481. };
  15482. function semicolon() {
  15483. if (is("punc", ";")) next();
  15484. else if (!can_insert_semicolon()) unexpected();
  15485. };
  15486. function parenthesised() {
  15487. expect("(");
  15488. var exp = expression(true);
  15489. expect(")");
  15490. return exp;
  15491. };
  15492. function embed_tokens(parser) {
  15493. return function() {
  15494. var start = S.token;
  15495. var expr = parser();
  15496. var end = prev();
  15497. expr.start = start;
  15498. expr.end = end;
  15499. return expr;
  15500. };
  15501. };
  15502. function handle_regexp() {
  15503. if (is("operator", "/") || is("operator", "/=")) {
  15504. S.peeked = null;
  15505. S.token = S.input(S.token.value.substr(1)); // force regexp
  15506. }
  15507. };
  15508. var statement = embed_tokens(function() {
  15509. var tmp;
  15510. handle_regexp();
  15511. switch (S.token.type) {
  15512. case "string":
  15513. var dir = S.in_directives, stat = simple_statement();
  15514. // XXXv2: decide how to fix directives
  15515. if (dir && stat.body instanceof AST_String && !is("punc", ","))
  15516. return new AST_Directive({ value: stat.body.value });
  15517. return stat;
  15518. case "num":
  15519. case "regexp":
  15520. case "operator":
  15521. case "atom":
  15522. return simple_statement();
  15523. case "name":
  15524. return is_token(peek(), "punc", ":")
  15525. ? labeled_statement()
  15526. : simple_statement();
  15527. case "punc":
  15528. switch (S.token.value) {
  15529. case "{":
  15530. return new AST_BlockStatement({
  15531. start : S.token,
  15532. body : block_(),
  15533. end : prev()
  15534. });
  15535. case "[":
  15536. case "(":
  15537. return simple_statement();
  15538. case ";":
  15539. next();
  15540. return new AST_EmptyStatement();
  15541. default:
  15542. unexpected();
  15543. }
  15544. case "keyword":
  15545. switch (tmp = S.token.value, next(), tmp) {
  15546. case "break":
  15547. return break_cont(AST_Break);
  15548. case "continue":
  15549. return break_cont(AST_Continue);
  15550. case "debugger":
  15551. semicolon();
  15552. return new AST_Debugger();
  15553. case "do":
  15554. return new AST_Do({
  15555. body : in_loop(statement),
  15556. condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp)
  15557. });
  15558. case "while":
  15559. return new AST_While({
  15560. condition : parenthesised(),
  15561. body : in_loop(statement)
  15562. });
  15563. case "for":
  15564. return for_();
  15565. case "function":
  15566. return function_(AST_Defun);
  15567. case "if":
  15568. return if_();
  15569. case "return":
  15570. if (S.in_function == 0 && !options.bare_returns)
  15571. croak("'return' outside of function");
  15572. return new AST_Return({
  15573. value: ( is("punc", ";")
  15574. ? (next(), null)
  15575. : can_insert_semicolon()
  15576. ? null
  15577. : (tmp = expression(true), semicolon(), tmp) )
  15578. });
  15579. case "switch":
  15580. return new AST_Switch({
  15581. expression : parenthesised(),
  15582. body : in_loop(switch_body_)
  15583. });
  15584. case "throw":
  15585. if (S.token.nlb)
  15586. croak("Illegal newline after 'throw'");
  15587. return new AST_Throw({
  15588. value: (tmp = expression(true), semicolon(), tmp)
  15589. });
  15590. case "try":
  15591. return try_();
  15592. case "var":
  15593. return tmp = var_(), semicolon(), tmp;
  15594. case "const":
  15595. return tmp = const_(), semicolon(), tmp;
  15596. case "with":
  15597. return new AST_With({
  15598. expression : parenthesised(),
  15599. body : statement()
  15600. });
  15601. default:
  15602. unexpected();
  15603. }
  15604. }
  15605. });
  15606. function labeled_statement() {
  15607. var label = as_symbol(AST_Label);
  15608. if (find_if(function(l){ return l.name == label.name }, S.labels)) {
  15609. // ECMA-262, 12.12: An ECMAScript program is considered
  15610. // syntactically incorrect if it contains a
  15611. // LabelledStatement that is enclosed by a
  15612. // LabelledStatement with the same Identifier as label.
  15613. croak("Label " + label.name + " defined twice");
  15614. }
  15615. expect(":");
  15616. S.labels.push(label);
  15617. var stat = statement();
  15618. S.labels.pop();
  15619. if (!(stat instanceof AST_IterationStatement)) {
  15620. // check for `continue` that refers to this label.
  15621. // those should be reported as syntax errors.
  15622. // https://github.com/mishoo/UglifyJS2/issues/287
  15623. label.references.forEach(function(ref){
  15624. if (ref instanceof AST_Continue) {
  15625. ref = ref.label.start;
  15626. croak("Continue label `" + label.name + "` refers to non-IterationStatement.",
  15627. ref.line, ref.col, ref.pos);
  15628. }
  15629. });
  15630. }
  15631. return new AST_LabeledStatement({ body: stat, label: label });
  15632. };
  15633. function simple_statement(tmp) {
  15634. return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) });
  15635. };
  15636. function break_cont(type) {
  15637. var label = null, ldef;
  15638. if (!can_insert_semicolon()) {
  15639. label = as_symbol(AST_LabelRef, true);
  15640. }
  15641. if (label != null) {
  15642. ldef = find_if(function(l){ return l.name == label.name }, S.labels);
  15643. if (!ldef)
  15644. croak("Undefined label " + label.name);
  15645. label.thedef = ldef;
  15646. }
  15647. else if (S.in_loop == 0)
  15648. croak(type.TYPE + " not inside a loop or switch");
  15649. semicolon();
  15650. var stat = new type({ label: label });
  15651. if (ldef) ldef.references.push(stat);
  15652. return stat;
  15653. };
  15654. function for_() {
  15655. expect("(");
  15656. var init = null;
  15657. if (!is("punc", ";")) {
  15658. init = is("keyword", "var")
  15659. ? (next(), var_(true))
  15660. : expression(true, true);
  15661. if (is("operator", "in")) {
  15662. if (init instanceof AST_Var && init.definitions.length > 1)
  15663. croak("Only one variable declaration allowed in for..in loop");
  15664. next();
  15665. return for_in(init);
  15666. }
  15667. }
  15668. return regular_for(init);
  15669. };
  15670. function regular_for(init) {
  15671. expect(";");
  15672. var test = is("punc", ";") ? null : expression(true);
  15673. expect(";");
  15674. var step = is("punc", ")") ? null : expression(true);
  15675. expect(")");
  15676. return new AST_For({
  15677. init : init,
  15678. condition : test,
  15679. step : step,
  15680. body : in_loop(statement)
  15681. });
  15682. };
  15683. function for_in(init) {
  15684. var lhs = init instanceof AST_Var ? init.definitions[0].name : null;
  15685. var obj = expression(true);
  15686. expect(")");
  15687. return new AST_ForIn({
  15688. init : init,
  15689. name : lhs,
  15690. object : obj,
  15691. body : in_loop(statement)
  15692. });
  15693. };
  15694. var function_ = function(ctor) {
  15695. var in_statement = ctor === AST_Defun;
  15696. var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;
  15697. if (in_statement && !name)
  15698. unexpected();
  15699. expect("(");
  15700. return new ctor({
  15701. name: name,
  15702. argnames: (function(first, a){
  15703. while (!is("punc", ")")) {
  15704. if (first) first = false; else expect(",");
  15705. a.push(as_symbol(AST_SymbolFunarg));
  15706. }
  15707. next();
  15708. return a;
  15709. })(true, []),
  15710. body: (function(loop, labels){
  15711. ++S.in_function;
  15712. S.in_directives = true;
  15713. S.in_loop = 0;
  15714. S.labels = [];
  15715. var a = block_();
  15716. --S.in_function;
  15717. S.in_loop = loop;
  15718. S.labels = labels;
  15719. return a;
  15720. })(S.in_loop, S.labels)
  15721. });
  15722. };
  15723. function if_() {
  15724. var cond = parenthesised(), body = statement(), belse = null;
  15725. if (is("keyword", "else")) {
  15726. next();
  15727. belse = statement();
  15728. }
  15729. return new AST_If({
  15730. condition : cond,
  15731. body : body,
  15732. alternative : belse
  15733. });
  15734. };
  15735. function block_() {
  15736. expect("{");
  15737. var a = [];
  15738. while (!is("punc", "}")) {
  15739. if (is("eof")) unexpected();
  15740. a.push(statement());
  15741. }
  15742. next();
  15743. return a;
  15744. };
  15745. function switch_body_() {
  15746. expect("{");
  15747. var a = [], cur = null, branch = null, tmp;
  15748. while (!is("punc", "}")) {
  15749. if (is("eof")) unexpected();
  15750. if (is("keyword", "case")) {
  15751. if (branch) branch.end = prev();
  15752. cur = [];
  15753. branch = new AST_Case({
  15754. start : (tmp = S.token, next(), tmp),
  15755. expression : expression(true),
  15756. body : cur
  15757. });
  15758. a.push(branch);
  15759. expect(":");
  15760. }
  15761. else if (is("keyword", "default")) {
  15762. if (branch) branch.end = prev();
  15763. cur = [];
  15764. branch = new AST_Default({
  15765. start : (tmp = S.token, next(), expect(":"), tmp),
  15766. body : cur
  15767. });
  15768. a.push(branch);
  15769. }
  15770. else {
  15771. if (!cur) unexpected();
  15772. cur.push(statement());
  15773. }
  15774. }
  15775. if (branch) branch.end = prev();
  15776. next();
  15777. return a;
  15778. };
  15779. function try_() {
  15780. var body = block_(), bcatch = null, bfinally = null;
  15781. if (is("keyword", "catch")) {
  15782. var start = S.token;
  15783. next();
  15784. expect("(");
  15785. var name = as_symbol(AST_SymbolCatch);
  15786. expect(")");
  15787. bcatch = new AST_Catch({
  15788. start : start,
  15789. argname : name,
  15790. body : block_(),
  15791. end : prev()
  15792. });
  15793. }
  15794. if (is("keyword", "finally")) {
  15795. var start = S.token;
  15796. next();
  15797. bfinally = new AST_Finally({
  15798. start : start,
  15799. body : block_(),
  15800. end : prev()
  15801. });
  15802. }
  15803. if (!bcatch && !bfinally)
  15804. croak("Missing catch/finally blocks");
  15805. return new AST_Try({
  15806. body : body,
  15807. bcatch : bcatch,
  15808. bfinally : bfinally
  15809. });
  15810. };
  15811. function vardefs(no_in, in_const) {
  15812. var a = [];
  15813. for (;;) {
  15814. a.push(new AST_VarDef({
  15815. start : S.token,
  15816. name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),
  15817. value : is("operator", "=") ? (next(), expression(false, no_in)) : null,
  15818. end : prev()
  15819. }));
  15820. if (!is("punc", ","))
  15821. break;
  15822. next();
  15823. }
  15824. return a;
  15825. };
  15826. var var_ = function(no_in) {
  15827. return new AST_Var({
  15828. start : prev(),
  15829. definitions : vardefs(no_in, false),
  15830. end : prev()
  15831. });
  15832. };
  15833. var const_ = function() {
  15834. return new AST_Const({
  15835. start : prev(),
  15836. definitions : vardefs(false, true),
  15837. end : prev()
  15838. });
  15839. };
  15840. var new_ = function() {
  15841. var start = S.token;
  15842. expect_token("operator", "new");
  15843. var newexp = expr_atom(false), args;
  15844. if (is("punc", "(")) {
  15845. next();
  15846. args = expr_list(")");
  15847. } else {
  15848. args = [];
  15849. }
  15850. return subscripts(new AST_New({
  15851. start : start,
  15852. expression : newexp,
  15853. args : args,
  15854. end : prev()
  15855. }), true);
  15856. };
  15857. function as_atom_node() {
  15858. var tok = S.token, ret;
  15859. switch (tok.type) {
  15860. case "name":
  15861. case "keyword":
  15862. ret = _make_symbol(AST_SymbolRef);
  15863. break;
  15864. case "num":
  15865. ret = new AST_Number({ start: tok, end: tok, value: tok.value });
  15866. break;
  15867. case "string":
  15868. ret = new AST_String({ start: tok, end: tok, value: tok.value });
  15869. break;
  15870. case "regexp":
  15871. ret = new AST_RegExp({ start: tok, end: tok, value: tok.value });
  15872. break;
  15873. case "atom":
  15874. switch (tok.value) {
  15875. case "false":
  15876. ret = new AST_False({ start: tok, end: tok });
  15877. break;
  15878. case "true":
  15879. ret = new AST_True({ start: tok, end: tok });
  15880. break;
  15881. case "null":
  15882. ret = new AST_Null({ start: tok, end: tok });
  15883. break;
  15884. }
  15885. break;
  15886. }
  15887. next();
  15888. return ret;
  15889. };
  15890. var expr_atom = function(allow_calls) {
  15891. if (is("operator", "new")) {
  15892. return new_();
  15893. }
  15894. var start = S.token;
  15895. if (is("punc")) {
  15896. switch (start.value) {
  15897. case "(":
  15898. next();
  15899. var ex = expression(true);
  15900. ex.start = start;
  15901. ex.end = S.token;
  15902. expect(")");
  15903. return subscripts(ex, allow_calls);
  15904. case "[":
  15905. return subscripts(array_(), allow_calls);
  15906. case "{":
  15907. return subscripts(object_(), allow_calls);
  15908. }
  15909. unexpected();
  15910. }
  15911. if (is("keyword", "function")) {
  15912. next();
  15913. var func = function_(AST_Function);
  15914. func.start = start;
  15915. func.end = prev();
  15916. return subscripts(func, allow_calls);
  15917. }
  15918. if (ATOMIC_START_TOKEN[S.token.type]) {
  15919. return subscripts(as_atom_node(), allow_calls);
  15920. }
  15921. unexpected();
  15922. };
  15923. function expr_list(closing, allow_trailing_comma, allow_empty) {
  15924. var first = true, a = [];
  15925. while (!is("punc", closing)) {
  15926. if (first) first = false; else expect(",");
  15927. if (allow_trailing_comma && is("punc", closing)) break;
  15928. if (is("punc", ",") && allow_empty) {
  15929. a.push(new AST_Hole({ start: S.token, end: S.token }));
  15930. } else {
  15931. a.push(expression(false));
  15932. }
  15933. }
  15934. next();
  15935. return a;
  15936. };
  15937. var array_ = embed_tokens(function() {
  15938. expect("[");
  15939. return new AST_Array({
  15940. elements: expr_list("]", !options.strict, true)
  15941. });
  15942. });
  15943. var object_ = embed_tokens(function() {
  15944. expect("{");
  15945. var first = true, a = [];
  15946. while (!is("punc", "}")) {
  15947. if (first) first = false; else expect(",");
  15948. if (!options.strict && is("punc", "}"))
  15949. // allow trailing comma
  15950. break;
  15951. var start = S.token;
  15952. var type = start.type;
  15953. var name = as_property_name();
  15954. if (type == "name" && !is("punc", ":")) {
  15955. if (name == "get") {
  15956. a.push(new AST_ObjectGetter({
  15957. start : start,
  15958. key : as_atom_node(),
  15959. value : function_(AST_Accessor),
  15960. end : prev()
  15961. }));
  15962. continue;
  15963. }
  15964. if (name == "set") {
  15965. a.push(new AST_ObjectSetter({
  15966. start : start,
  15967. key : as_atom_node(),
  15968. value : function_(AST_Accessor),
  15969. end : prev()
  15970. }));
  15971. continue;
  15972. }
  15973. }
  15974. expect(":");
  15975. a.push(new AST_ObjectKeyVal({
  15976. start : start,
  15977. key : name,
  15978. value : expression(false),
  15979. end : prev()
  15980. }));
  15981. }
  15982. next();
  15983. return new AST_Object({ properties: a });
  15984. });
  15985. function as_property_name() {
  15986. var tmp = S.token;
  15987. next();
  15988. switch (tmp.type) {
  15989. case "num":
  15990. case "string":
  15991. case "name":
  15992. case "operator":
  15993. case "keyword":
  15994. case "atom":
  15995. return tmp.value;
  15996. default:
  15997. unexpected();
  15998. }
  15999. };
  16000. function as_name() {
  16001. var tmp = S.token;
  16002. next();
  16003. switch (tmp.type) {
  16004. case "name":
  16005. case "operator":
  16006. case "keyword":
  16007. case "atom":
  16008. return tmp.value;
  16009. default:
  16010. unexpected();
  16011. }
  16012. };
  16013. function _make_symbol(type) {
  16014. var name = S.token.value;
  16015. return new (name == "this" ? AST_This : type)({
  16016. name : String(name),
  16017. start : S.token,
  16018. end : S.token
  16019. });
  16020. };
  16021. function as_symbol(type, noerror) {
  16022. if (!is("name")) {
  16023. if (!noerror) croak("Name expected");
  16024. return null;
  16025. }
  16026. var sym = _make_symbol(type);
  16027. next();
  16028. return sym;
  16029. };
  16030. var subscripts = function(expr, allow_calls) {
  16031. var start = expr.start;
  16032. if (is("punc", ".")) {
  16033. next();
  16034. return subscripts(new AST_Dot({
  16035. start : start,
  16036. expression : expr,
  16037. property : as_name(),
  16038. end : prev()
  16039. }), allow_calls);
  16040. }
  16041. if (is("punc", "[")) {
  16042. next();
  16043. var prop = expression(true);
  16044. expect("]");
  16045. return subscripts(new AST_Sub({
  16046. start : start,
  16047. expression : expr,
  16048. property : prop,
  16049. end : prev()
  16050. }), allow_calls);
  16051. }
  16052. if (allow_calls && is("punc", "(")) {
  16053. next();
  16054. return subscripts(new AST_Call({
  16055. start : start,
  16056. expression : expr,
  16057. args : expr_list(")"),
  16058. end : prev()
  16059. }), true);
  16060. }
  16061. return expr;
  16062. };
  16063. var maybe_unary = function(allow_calls) {
  16064. var start = S.token;
  16065. if (is("operator") && UNARY_PREFIX(start.value)) {
  16066. next();
  16067. handle_regexp();
  16068. var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls));
  16069. ex.start = start;
  16070. ex.end = prev();
  16071. return ex;
  16072. }
  16073. var val = expr_atom(allow_calls);
  16074. while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {
  16075. val = make_unary(AST_UnaryPostfix, S.token.value, val);
  16076. val.start = start;
  16077. val.end = S.token;
  16078. next();
  16079. }
  16080. return val;
  16081. };
  16082. function make_unary(ctor, op, expr) {
  16083. if ((op == "++" || op == "--") && !is_assignable(expr))
  16084. croak("Invalid use of " + op + " operator");
  16085. return new ctor({ operator: op, expression: expr });
  16086. };
  16087. var expr_op = function(left, min_prec, no_in) {
  16088. var op = is("operator") ? S.token.value : null;
  16089. if (op == "in" && no_in) op = null;
  16090. var prec = op != null ? PRECEDENCE[op] : null;
  16091. if (prec != null && prec > min_prec) {
  16092. next();
  16093. var right = expr_op(maybe_unary(true), prec, no_in);
  16094. return expr_op(new AST_Binary({
  16095. start : left.start,
  16096. left : left,
  16097. operator : op,
  16098. right : right,
  16099. end : right.end
  16100. }), min_prec, no_in);
  16101. }
  16102. return left;
  16103. };
  16104. function expr_ops(no_in) {
  16105. return expr_op(maybe_unary(true), 0, no_in);
  16106. };
  16107. var maybe_conditional = function(no_in) {
  16108. var start = S.token;
  16109. var expr = expr_ops(no_in);
  16110. if (is("operator", "?")) {
  16111. next();
  16112. var yes = expression(false);
  16113. expect(":");
  16114. return new AST_Conditional({
  16115. start : start,
  16116. condition : expr,
  16117. consequent : yes,
  16118. alternative : expression(false, no_in),
  16119. end : prev()
  16120. });
  16121. }
  16122. return expr;
  16123. };
  16124. function is_assignable(expr) {
  16125. if (!options.strict) return true;
  16126. if (expr instanceof AST_This) return false;
  16127. return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol);
  16128. };
  16129. var maybe_assign = function(no_in) {
  16130. var start = S.token;
  16131. var left = maybe_conditional(no_in), val = S.token.value;
  16132. if (is("operator") && ASSIGNMENT(val)) {
  16133. if (is_assignable(left)) {
  16134. next();
  16135. return new AST_Assign({
  16136. start : start,
  16137. left : left,
  16138. operator : val,
  16139. right : maybe_assign(no_in),
  16140. end : prev()
  16141. });
  16142. }
  16143. croak("Invalid assignment");
  16144. }
  16145. return left;
  16146. };
  16147. var expression = function(commas, no_in) {
  16148. var start = S.token;
  16149. var expr = maybe_assign(no_in);
  16150. if (commas && is("punc", ",")) {
  16151. next();
  16152. return new AST_Seq({
  16153. start : start,
  16154. car : expr,
  16155. cdr : expression(true, no_in),
  16156. end : peek()
  16157. });
  16158. }
  16159. return expr;
  16160. };
  16161. function in_loop(cont) {
  16162. ++S.in_loop;
  16163. var ret = cont();
  16164. --S.in_loop;
  16165. return ret;
  16166. };
  16167. if (options.expression) {
  16168. return expression(true);
  16169. }
  16170. return (function(){
  16171. var start = S.token;
  16172. var body = [];
  16173. while (!is("eof"))
  16174. body.push(statement());
  16175. var end = prev();
  16176. var toplevel = options.toplevel;
  16177. if (toplevel) {
  16178. toplevel.body = toplevel.body.concat(body);
  16179. toplevel.end = end;
  16180. } else {
  16181. toplevel = new AST_Toplevel({ start: start, body: body, end: end });
  16182. }
  16183. return toplevel;
  16184. })();
  16185. };
  16186. /***********************************************************************
  16187. A JavaScript tokenizer / parser / beautifier / compressor.
  16188. https://github.com/mishoo/UglifyJS2
  16189. -------------------------------- (C) ---------------------------------
  16190. Author: Mihai Bazon
  16191. <mihai.bazon@gmail.com>
  16192. http://mihai.bazon.net/blog
  16193. Distributed under the BSD license:
  16194. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  16195. Redistribution and use in source and binary forms, with or without
  16196. modification, are permitted provided that the following conditions
  16197. are met:
  16198. * Redistributions of source code must retain the above
  16199. copyright notice, this list of conditions and the following
  16200. disclaimer.
  16201. * Redistributions in binary form must reproduce the above
  16202. copyright notice, this list of conditions and the following
  16203. disclaimer in the documentation and/or other materials
  16204. provided with the distribution.
  16205. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  16206. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16207. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16208. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  16209. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  16210. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  16211. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  16212. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  16213. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  16214. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  16215. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16216. SUCH DAMAGE.
  16217. ***********************************************************************/
  16218. "use strict";
  16219. // Tree transformer helpers.
  16220. function TreeTransformer(before, after) {
  16221. TreeWalker.call(this);
  16222. this.before = before;
  16223. this.after = after;
  16224. }
  16225. TreeTransformer.prototype = new TreeWalker;
  16226. (function(undefined){
  16227. function _(node, descend) {
  16228. node.DEFMETHOD("transform", function(tw, in_list){
  16229. var x, y;
  16230. tw.push(this);
  16231. if (tw.before) x = tw.before(this, descend, in_list);
  16232. if (x === undefined) {
  16233. if (!tw.after) {
  16234. x = this;
  16235. descend(x, tw);
  16236. } else {
  16237. tw.stack[tw.stack.length - 1] = x = this.clone();
  16238. descend(x, tw);
  16239. y = tw.after(x, in_list);
  16240. if (y !== undefined) x = y;
  16241. }
  16242. }
  16243. tw.pop();
  16244. return x;
  16245. });
  16246. };
  16247. function do_list(list, tw) {
  16248. return MAP(list, function(node){
  16249. return node.transform(tw, true);
  16250. });
  16251. };
  16252. _(AST_Node, noop);
  16253. _(AST_LabeledStatement, function(self, tw){
  16254. self.label = self.label.transform(tw);
  16255. self.body = self.body.transform(tw);
  16256. });
  16257. _(AST_SimpleStatement, function(self, tw){
  16258. self.body = self.body.transform(tw);
  16259. });
  16260. _(AST_Block, function(self, tw){
  16261. self.body = do_list(self.body, tw);
  16262. });
  16263. _(AST_DWLoop, function(self, tw){
  16264. self.condition = self.condition.transform(tw);
  16265. self.body = self.body.transform(tw);
  16266. });
  16267. _(AST_For, function(self, tw){
  16268. if (self.init) self.init = self.init.transform(tw);
  16269. if (self.condition) self.condition = self.condition.transform(tw);
  16270. if (self.step) self.step = self.step.transform(tw);
  16271. self.body = self.body.transform(tw);
  16272. });
  16273. _(AST_ForIn, function(self, tw){
  16274. self.init = self.init.transform(tw);
  16275. self.object = self.object.transform(tw);
  16276. self.body = self.body.transform(tw);
  16277. });
  16278. _(AST_With, function(self, tw){
  16279. self.expression = self.expression.transform(tw);
  16280. self.body = self.body.transform(tw);
  16281. });
  16282. _(AST_Exit, function(self, tw){
  16283. if (self.value) self.value = self.value.transform(tw);
  16284. });
  16285. _(AST_LoopControl, function(self, tw){
  16286. if (self.label) self.label = self.label.transform(tw);
  16287. });
  16288. _(AST_If, function(self, tw){
  16289. self.condition = self.condition.transform(tw);
  16290. self.body = self.body.transform(tw);
  16291. if (self.alternative) self.alternative = self.alternative.transform(tw);
  16292. });
  16293. _(AST_Switch, function(self, tw){
  16294. self.expression = self.expression.transform(tw);
  16295. self.body = do_list(self.body, tw);
  16296. });
  16297. _(AST_Case, function(self, tw){
  16298. self.expression = self.expression.transform(tw);
  16299. self.body = do_list(self.body, tw);
  16300. });
  16301. _(AST_Try, function(self, tw){
  16302. self.body = do_list(self.body, tw);
  16303. if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
  16304. if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
  16305. });
  16306. _(AST_Catch, function(self, tw){
  16307. self.argname = self.argname.transform(tw);
  16308. self.body = do_list(self.body, tw);
  16309. });
  16310. _(AST_Definitions, function(self, tw){
  16311. self.definitions = do_list(self.definitions, tw);
  16312. });
  16313. _(AST_VarDef, function(self, tw){
  16314. self.name = self.name.transform(tw);
  16315. if (self.value) self.value = self.value.transform(tw);
  16316. });
  16317. _(AST_Lambda, function(self, tw){
  16318. if (self.name) self.name = self.name.transform(tw);
  16319. self.argnames = do_list(self.argnames, tw);
  16320. self.body = do_list(self.body, tw);
  16321. });
  16322. _(AST_Call, function(self, tw){
  16323. self.expression = self.expression.transform(tw);
  16324. self.args = do_list(self.args, tw);
  16325. });
  16326. _(AST_Seq, function(self, tw){
  16327. self.car = self.car.transform(tw);
  16328. self.cdr = self.cdr.transform(tw);
  16329. });
  16330. _(AST_Dot, function(self, tw){
  16331. self.expression = self.expression.transform(tw);
  16332. });
  16333. _(AST_Sub, function(self, tw){
  16334. self.expression = self.expression.transform(tw);
  16335. self.property = self.property.transform(tw);
  16336. });
  16337. _(AST_Unary, function(self, tw){
  16338. self.expression = self.expression.transform(tw);
  16339. });
  16340. _(AST_Binary, function(self, tw){
  16341. self.left = self.left.transform(tw);
  16342. self.right = self.right.transform(tw);
  16343. });
  16344. _(AST_Conditional, function(self, tw){
  16345. self.condition = self.condition.transform(tw);
  16346. self.consequent = self.consequent.transform(tw);
  16347. self.alternative = self.alternative.transform(tw);
  16348. });
  16349. _(AST_Array, function(self, tw){
  16350. self.elements = do_list(self.elements, tw);
  16351. });
  16352. _(AST_Object, function(self, tw){
  16353. self.properties = do_list(self.properties, tw);
  16354. });
  16355. _(AST_ObjectProperty, function(self, tw){
  16356. self.value = self.value.transform(tw);
  16357. });
  16358. })();
  16359. /***********************************************************************
  16360. A JavaScript tokenizer / parser / beautifier / compressor.
  16361. https://github.com/mishoo/UglifyJS2
  16362. -------------------------------- (C) ---------------------------------
  16363. Author: Mihai Bazon
  16364. <mihai.bazon@gmail.com>
  16365. http://mihai.bazon.net/blog
  16366. Distributed under the BSD license:
  16367. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  16368. Redistribution and use in source and binary forms, with or without
  16369. modification, are permitted provided that the following conditions
  16370. are met:
  16371. * Redistributions of source code must retain the above
  16372. copyright notice, this list of conditions and the following
  16373. disclaimer.
  16374. * Redistributions in binary form must reproduce the above
  16375. copyright notice, this list of conditions and the following
  16376. disclaimer in the documentation and/or other materials
  16377. provided with the distribution.
  16378. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  16379. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16380. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16381. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  16382. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  16383. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  16384. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  16385. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  16386. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  16387. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  16388. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16389. SUCH DAMAGE.
  16390. ***********************************************************************/
  16391. "use strict";
  16392. function SymbolDef(scope, index, orig) {
  16393. this.name = orig.name;
  16394. this.orig = [ orig ];
  16395. this.scope = scope;
  16396. this.references = [];
  16397. this.global = false;
  16398. this.mangled_name = null;
  16399. this.undeclared = false;
  16400. this.constant = false;
  16401. this.index = index;
  16402. };
  16403. SymbolDef.prototype = {
  16404. unmangleable: function(options) {
  16405. return (this.global && !(options && options.toplevel))
  16406. || this.undeclared
  16407. || (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with));
  16408. },
  16409. mangle: function(options) {
  16410. if (!this.mangled_name && !this.unmangleable(options)) {
  16411. var s = this.scope;
  16412. if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda)
  16413. s = s.parent_scope;
  16414. this.mangled_name = s.next_mangled(options, this);
  16415. }
  16416. }
  16417. };
  16418. AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
  16419. options = defaults(options, {
  16420. screw_ie8: false
  16421. });
  16422. // pass 1: setup scope chaining and handle definitions
  16423. var self = this;
  16424. var scope = self.parent_scope = null;
  16425. var defun = null;
  16426. var nesting = 0;
  16427. var tw = new TreeWalker(function(node, descend){
  16428. if (options.screw_ie8 && node instanceof AST_Catch) {
  16429. var save_scope = scope;
  16430. scope = new AST_Scope(node);
  16431. scope.init_scope_vars(nesting);
  16432. scope.parent_scope = save_scope;
  16433. descend();
  16434. scope = save_scope;
  16435. return true;
  16436. }
  16437. if (node instanceof AST_Scope) {
  16438. node.init_scope_vars(nesting);
  16439. var save_scope = node.parent_scope = scope;
  16440. var save_defun = defun;
  16441. defun = scope = node;
  16442. ++nesting; descend(); --nesting;
  16443. scope = save_scope;
  16444. defun = save_defun;
  16445. return true; // don't descend again in TreeWalker
  16446. }
  16447. if (node instanceof AST_Directive) {
  16448. node.scope = scope;
  16449. push_uniq(scope.directives, node.value);
  16450. return true;
  16451. }
  16452. if (node instanceof AST_With) {
  16453. for (var s = scope; s; s = s.parent_scope)
  16454. s.uses_with = true;
  16455. return;
  16456. }
  16457. if (node instanceof AST_Symbol) {
  16458. node.scope = scope;
  16459. }
  16460. if (node instanceof AST_SymbolLambda) {
  16461. defun.def_function(node);
  16462. }
  16463. else if (node instanceof AST_SymbolDefun) {
  16464. // Careful here, the scope where this should be defined is
  16465. // the parent scope. The reason is that we enter a new
  16466. // scope when we encounter the AST_Defun node (which is
  16467. // instanceof AST_Scope) but we get to the symbol a bit
  16468. // later.
  16469. (node.scope = defun.parent_scope).def_function(node);
  16470. }
  16471. else if (node instanceof AST_SymbolVar
  16472. || node instanceof AST_SymbolConst) {
  16473. var def = defun.def_variable(node);
  16474. def.constant = node instanceof AST_SymbolConst;
  16475. def.init = tw.parent().value;
  16476. }
  16477. else if (node instanceof AST_SymbolCatch) {
  16478. (options.screw_ie8 ? scope : defun)
  16479. .def_variable(node);
  16480. }
  16481. });
  16482. self.walk(tw);
  16483. // pass 2: find back references and eval
  16484. var func = null;
  16485. var globals = self.globals = new Dictionary();
  16486. var tw = new TreeWalker(function(node, descend){
  16487. if (node instanceof AST_Lambda) {
  16488. var prev_func = func;
  16489. func = node;
  16490. descend();
  16491. func = prev_func;
  16492. return true;
  16493. }
  16494. if (node instanceof AST_SymbolRef) {
  16495. var name = node.name;
  16496. var sym = node.scope.find_variable(name);
  16497. if (!sym) {
  16498. var g;
  16499. if (globals.has(name)) {
  16500. g = globals.get(name);
  16501. } else {
  16502. g = new SymbolDef(self, globals.size(), node);
  16503. g.undeclared = true;
  16504. g.global = true;
  16505. globals.set(name, g);
  16506. }
  16507. node.thedef = g;
  16508. if (name == "eval" && tw.parent() instanceof AST_Call) {
  16509. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope)
  16510. s.uses_eval = true;
  16511. }
  16512. if (func && name == "arguments") {
  16513. func.uses_arguments = true;
  16514. }
  16515. } else {
  16516. node.thedef = sym;
  16517. }
  16518. node.reference();
  16519. return true;
  16520. }
  16521. });
  16522. self.walk(tw);
  16523. });
  16524. AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){
  16525. this.directives = []; // contains the directives defined in this scope, i.e. "use strict"
  16526. this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  16527. this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
  16528. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  16529. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  16530. this.parent_scope = null; // the parent scope
  16531. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  16532. this.cname = -1; // the current index for mangling functions/variables
  16533. this.nesting = nesting; // the nesting level of this scope (0 means toplevel)
  16534. });
  16535. AST_Scope.DEFMETHOD("strict", function(){
  16536. return this.has_directive("use strict");
  16537. });
  16538. AST_Lambda.DEFMETHOD("init_scope_vars", function(){
  16539. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  16540. this.uses_arguments = false;
  16541. });
  16542. AST_SymbolRef.DEFMETHOD("reference", function() {
  16543. var def = this.definition();
  16544. def.references.push(this);
  16545. var s = this.scope;
  16546. while (s) {
  16547. push_uniq(s.enclosed, def);
  16548. if (s === def.scope) break;
  16549. s = s.parent_scope;
  16550. }
  16551. this.frame = this.scope.nesting - def.scope.nesting;
  16552. });
  16553. AST_Scope.DEFMETHOD("find_variable", function(name){
  16554. if (name instanceof AST_Symbol) name = name.name;
  16555. return this.variables.get(name)
  16556. || (this.parent_scope && this.parent_scope.find_variable(name));
  16557. });
  16558. AST_Scope.DEFMETHOD("has_directive", function(value){
  16559. return this.parent_scope && this.parent_scope.has_directive(value)
  16560. || (this.directives.indexOf(value) >= 0 ? this : null);
  16561. });
  16562. AST_Scope.DEFMETHOD("def_function", function(symbol){
  16563. this.functions.set(symbol.name, this.def_variable(symbol));
  16564. });
  16565. AST_Scope.DEFMETHOD("def_variable", function(symbol){
  16566. var def;
  16567. if (!this.variables.has(symbol.name)) {
  16568. def = new SymbolDef(this, this.variables.size(), symbol);
  16569. this.variables.set(symbol.name, def);
  16570. def.global = !this.parent_scope;
  16571. } else {
  16572. def = this.variables.get(symbol.name);
  16573. def.orig.push(symbol);
  16574. }
  16575. return symbol.thedef = def;
  16576. });
  16577. AST_Scope.DEFMETHOD("next_mangled", function(options){
  16578. var ext = this.enclosed;
  16579. out: while (true) {
  16580. var m = base54(++this.cname);
  16581. if (!is_identifier(m)) continue; // skip over "do"
  16582. // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
  16583. // shadow a name excepted from mangling.
  16584. if (options.except.indexOf(m) >= 0) continue;
  16585. // we must ensure that the mangled name does not shadow a name
  16586. // from some parent scope that is referenced in this or in
  16587. // inner scopes.
  16588. for (var i = ext.length; --i >= 0;) {
  16589. var sym = ext[i];
  16590. var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
  16591. if (m == name) continue out;
  16592. }
  16593. return m;
  16594. }
  16595. });
  16596. AST_Function.DEFMETHOD("next_mangled", function(options, def){
  16597. // #179, #326
  16598. // in Safari strict mode, something like (function x(x){...}) is a syntax error;
  16599. // a function expression's argument cannot shadow the function expression's name
  16600. var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
  16601. while (true) {
  16602. var name = AST_Lambda.prototype.next_mangled.call(this, options, def);
  16603. if (!(tricky_def && tricky_def.mangled_name == name))
  16604. return name;
  16605. }
  16606. });
  16607. AST_Scope.DEFMETHOD("references", function(sym){
  16608. if (sym instanceof AST_Symbol) sym = sym.definition();
  16609. return this.enclosed.indexOf(sym) < 0 ? null : sym;
  16610. });
  16611. AST_Symbol.DEFMETHOD("unmangleable", function(options){
  16612. return this.definition().unmangleable(options);
  16613. });
  16614. // property accessors are not mangleable
  16615. AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){
  16616. return true;
  16617. });
  16618. // labels are always mangleable
  16619. AST_Label.DEFMETHOD("unmangleable", function(){
  16620. return false;
  16621. });
  16622. AST_Symbol.DEFMETHOD("unreferenced", function(){
  16623. return this.definition().references.length == 0
  16624. && !(this.scope.uses_eval || this.scope.uses_with);
  16625. });
  16626. AST_Symbol.DEFMETHOD("undeclared", function(){
  16627. return this.definition().undeclared;
  16628. });
  16629. AST_LabelRef.DEFMETHOD("undeclared", function(){
  16630. return false;
  16631. });
  16632. AST_Label.DEFMETHOD("undeclared", function(){
  16633. return false;
  16634. });
  16635. AST_Symbol.DEFMETHOD("definition", function(){
  16636. return this.thedef;
  16637. });
  16638. AST_Symbol.DEFMETHOD("global", function(){
  16639. return this.definition().global;
  16640. });
  16641. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
  16642. return defaults(options, {
  16643. except : [],
  16644. eval : false,
  16645. sort : false,
  16646. toplevel : false,
  16647. screw_ie8 : false
  16648. });
  16649. });
  16650. AST_Toplevel.DEFMETHOD("mangle_names", function(options){
  16651. options = this._default_mangler_options(options);
  16652. // We only need to mangle declaration nodes. Special logic wired
  16653. // into the code generator will display the mangled name if it's
  16654. // present (and for AST_SymbolRef-s it'll use the mangled name of
  16655. // the AST_SymbolDeclaration that it points to).
  16656. var lname = -1;
  16657. var to_mangle = [];
  16658. var tw = new TreeWalker(function(node, descend){
  16659. if (node instanceof AST_LabeledStatement) {
  16660. // lname is incremented when we get to the AST_Label
  16661. var save_nesting = lname;
  16662. descend();
  16663. lname = save_nesting;
  16664. return true; // don't descend again in TreeWalker
  16665. }
  16666. if (node instanceof AST_Scope) {
  16667. var p = tw.parent(), a = [];
  16668. node.variables.each(function(symbol){
  16669. if (options.except.indexOf(symbol.name) < 0) {
  16670. a.push(symbol);
  16671. }
  16672. });
  16673. if (options.sort) a.sort(function(a, b){
  16674. return b.references.length - a.references.length;
  16675. });
  16676. to_mangle.push.apply(to_mangle, a);
  16677. return;
  16678. }
  16679. if (node instanceof AST_Label) {
  16680. var name;
  16681. do name = base54(++lname); while (!is_identifier(name));
  16682. node.mangled_name = name;
  16683. return true;
  16684. }
  16685. if (options.screw_ie8 && node instanceof AST_SymbolCatch) {
  16686. to_mangle.push(node.definition());
  16687. return;
  16688. }
  16689. });
  16690. this.walk(tw);
  16691. to_mangle.forEach(function(def){ def.mangle(options) });
  16692. });
  16693. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
  16694. options = this._default_mangler_options(options);
  16695. var tw = new TreeWalker(function(node){
  16696. if (node instanceof AST_Constant)
  16697. base54.consider(node.print_to_string());
  16698. else if (node instanceof AST_Return)
  16699. base54.consider("return");
  16700. else if (node instanceof AST_Throw)
  16701. base54.consider("throw");
  16702. else if (node instanceof AST_Continue)
  16703. base54.consider("continue");
  16704. else if (node instanceof AST_Break)
  16705. base54.consider("break");
  16706. else if (node instanceof AST_Debugger)
  16707. base54.consider("debugger");
  16708. else if (node instanceof AST_Directive)
  16709. base54.consider(node.value);
  16710. else if (node instanceof AST_While)
  16711. base54.consider("while");
  16712. else if (node instanceof AST_Do)
  16713. base54.consider("do while");
  16714. else if (node instanceof AST_If) {
  16715. base54.consider("if");
  16716. if (node.alternative) base54.consider("else");
  16717. }
  16718. else if (node instanceof AST_Var)
  16719. base54.consider("var");
  16720. else if (node instanceof AST_Const)
  16721. base54.consider("const");
  16722. else if (node instanceof AST_Lambda)
  16723. base54.consider("function");
  16724. else if (node instanceof AST_For)
  16725. base54.consider("for");
  16726. else if (node instanceof AST_ForIn)
  16727. base54.consider("for in");
  16728. else if (node instanceof AST_Switch)
  16729. base54.consider("switch");
  16730. else if (node instanceof AST_Case)
  16731. base54.consider("case");
  16732. else if (node instanceof AST_Default)
  16733. base54.consider("default");
  16734. else if (node instanceof AST_With)
  16735. base54.consider("with");
  16736. else if (node instanceof AST_ObjectSetter)
  16737. base54.consider("set" + node.key);
  16738. else if (node instanceof AST_ObjectGetter)
  16739. base54.consider("get" + node.key);
  16740. else if (node instanceof AST_ObjectKeyVal)
  16741. base54.consider(node.key);
  16742. else if (node instanceof AST_New)
  16743. base54.consider("new");
  16744. else if (node instanceof AST_This)
  16745. base54.consider("this");
  16746. else if (node instanceof AST_Try)
  16747. base54.consider("try");
  16748. else if (node instanceof AST_Catch)
  16749. base54.consider("catch");
  16750. else if (node instanceof AST_Finally)
  16751. base54.consider("finally");
  16752. else if (node instanceof AST_Symbol && node.unmangleable(options))
  16753. base54.consider(node.name);
  16754. else if (node instanceof AST_Unary || node instanceof AST_Binary)
  16755. base54.consider(node.operator);
  16756. else if (node instanceof AST_Dot)
  16757. base54.consider(node.property);
  16758. });
  16759. this.walk(tw);
  16760. base54.sort();
  16761. });
  16762. var base54 = (function() {
  16763. var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
  16764. var chars, frequency;
  16765. function reset() {
  16766. frequency = Object.create(null);
  16767. chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });
  16768. chars.forEach(function(ch){ frequency[ch] = 0 });
  16769. }
  16770. base54.consider = function(str){
  16771. for (var i = str.length; --i >= 0;) {
  16772. var code = str.charCodeAt(i);
  16773. if (code in frequency) ++frequency[code];
  16774. }
  16775. };
  16776. base54.sort = function() {
  16777. chars = mergeSort(chars, function(a, b){
  16778. if (is_digit(a) && !is_digit(b)) return 1;
  16779. if (is_digit(b) && !is_digit(a)) return -1;
  16780. return frequency[b] - frequency[a];
  16781. });
  16782. };
  16783. base54.reset = reset;
  16784. reset();
  16785. base54.get = function(){ return chars };
  16786. base54.freq = function(){ return frequency };
  16787. function base54(num) {
  16788. var ret = "", base = 54;
  16789. do {
  16790. ret += String.fromCharCode(chars[num % base]);
  16791. num = Math.floor(num / base);
  16792. base = 64;
  16793. } while (num > 0);
  16794. return ret;
  16795. };
  16796. return base54;
  16797. })();
  16798. AST_Toplevel.DEFMETHOD("scope_warnings", function(options){
  16799. options = defaults(options, {
  16800. undeclared : false, // this makes a lot of noise
  16801. unreferenced : true,
  16802. assign_to_global : true,
  16803. func_arguments : true,
  16804. nested_defuns : true,
  16805. eval : true
  16806. });
  16807. var tw = new TreeWalker(function(node){
  16808. if (options.undeclared
  16809. && node instanceof AST_SymbolRef
  16810. && node.undeclared())
  16811. {
  16812. // XXX: this also warns about JS standard names,
  16813. // i.e. Object, Array, parseInt etc. Should add a list of
  16814. // exceptions.
  16815. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
  16816. name: node.name,
  16817. file: node.start.file,
  16818. line: node.start.line,
  16819. col: node.start.col
  16820. });
  16821. }
  16822. if (options.assign_to_global)
  16823. {
  16824. var sym = null;
  16825. if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)
  16826. sym = node.left;
  16827. else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)
  16828. sym = node.init;
  16829. if (sym
  16830. && (sym.undeclared()
  16831. || (sym.global() && sym.scope !== sym.definition().scope))) {
  16832. AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
  16833. msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
  16834. name: sym.name,
  16835. file: sym.start.file,
  16836. line: sym.start.line,
  16837. col: sym.start.col
  16838. });
  16839. }
  16840. }
  16841. if (options.eval
  16842. && node instanceof AST_SymbolRef
  16843. && node.undeclared()
  16844. && node.name == "eval") {
  16845. AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
  16846. }
  16847. if (options.unreferenced
  16848. && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)
  16849. && !(node instanceof AST_SymbolCatch)
  16850. && node.unreferenced()) {
  16851. AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
  16852. type: node instanceof AST_Label ? "Label" : "Symbol",
  16853. name: node.name,
  16854. file: node.start.file,
  16855. line: node.start.line,
  16856. col: node.start.col
  16857. });
  16858. }
  16859. if (options.func_arguments
  16860. && node instanceof AST_Lambda
  16861. && node.uses_arguments) {
  16862. AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
  16863. name: node.name ? node.name.name : "anonymous",
  16864. file: node.start.file,
  16865. line: node.start.line,
  16866. col: node.start.col
  16867. });
  16868. }
  16869. if (options.nested_defuns
  16870. && node instanceof AST_Defun
  16871. && !(tw.parent() instanceof AST_Scope)) {
  16872. AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {
  16873. name: node.name.name,
  16874. type: tw.parent().TYPE,
  16875. file: node.start.file,
  16876. line: node.start.line,
  16877. col: node.start.col
  16878. });
  16879. }
  16880. });
  16881. this.walk(tw);
  16882. });
  16883. /***********************************************************************
  16884. A JavaScript tokenizer / parser / beautifier / compressor.
  16885. https://github.com/mishoo/UglifyJS2
  16886. -------------------------------- (C) ---------------------------------
  16887. Author: Mihai Bazon
  16888. <mihai.bazon@gmail.com>
  16889. http://mihai.bazon.net/blog
  16890. Distributed under the BSD license:
  16891. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  16892. Redistribution and use in source and binary forms, with or without
  16893. modification, are permitted provided that the following conditions
  16894. are met:
  16895. * Redistributions of source code must retain the above
  16896. copyright notice, this list of conditions and the following
  16897. disclaimer.
  16898. * Redistributions in binary form must reproduce the above
  16899. copyright notice, this list of conditions and the following
  16900. disclaimer in the documentation and/or other materials
  16901. provided with the distribution.
  16902. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  16903. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16904. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16905. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  16906. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  16907. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  16908. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  16909. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  16910. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  16911. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  16912. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16913. SUCH DAMAGE.
  16914. ***********************************************************************/
  16915. "use strict";
  16916. function OutputStream(options) {
  16917. options = defaults(options, {
  16918. indent_start : 0,
  16919. indent_level : 4,
  16920. quote_keys : false,
  16921. space_colon : true,
  16922. ascii_only : false,
  16923. unescape_regexps : false,
  16924. inline_script : false,
  16925. width : 80,
  16926. max_line_len : 32000,
  16927. beautify : false,
  16928. source_map : null,
  16929. bracketize : false,
  16930. semicolons : true,
  16931. comments : false,
  16932. preserve_line : false,
  16933. screw_ie8 : false,
  16934. preamble : null,
  16935. }, true);
  16936. var indentation = 0;
  16937. var current_col = 0;
  16938. var current_line = 1;
  16939. var current_pos = 0;
  16940. var OUTPUT = "";
  16941. function to_ascii(str, identifier) {
  16942. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  16943. var code = ch.charCodeAt(0).toString(16);
  16944. if (code.length <= 2 && !identifier) {
  16945. while (code.length < 2) code = "0" + code;
  16946. return "\\x" + code;
  16947. } else {
  16948. while (code.length < 4) code = "0" + code;
  16949. return "\\u" + code;
  16950. }
  16951. });
  16952. };
  16953. function make_string(str) {
  16954. var dq = 0, sq = 0;
  16955. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
  16956. switch (s) {
  16957. case "\\": return "\\\\";
  16958. case "\b": return "\\b";
  16959. case "\f": return "\\f";
  16960. case "\n": return "\\n";
  16961. case "\r": return "\\r";
  16962. case "\u2028": return "\\u2028";
  16963. case "\u2029": return "\\u2029";
  16964. case '"': ++dq; return '"';
  16965. case "'": ++sq; return "'";
  16966. case "\0": return "\\x00";
  16967. }
  16968. return s;
  16969. });
  16970. if (options.ascii_only) str = to_ascii(str);
  16971. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
  16972. else return '"' + str.replace(/\x22/g, '\\"') + '"';
  16973. };
  16974. function encode_string(str) {
  16975. var ret = make_string(str);
  16976. if (options.inline_script)
  16977. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  16978. return ret;
  16979. };
  16980. function make_name(name) {
  16981. name = name.toString();
  16982. if (options.ascii_only)
  16983. name = to_ascii(name, true);
  16984. return name;
  16985. };
  16986. function make_indent(back) {
  16987. return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
  16988. };
  16989. /* -----[ beautification/minification ]----- */
  16990. var might_need_space = false;
  16991. var might_need_semicolon = false;
  16992. var last = null;
  16993. function last_char() {
  16994. return last.charAt(last.length - 1);
  16995. };
  16996. function maybe_newline() {
  16997. if (options.max_line_len && current_col > options.max_line_len)
  16998. print("\n");
  16999. };
  17000. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  17001. function print(str) {
  17002. str = String(str);
  17003. var ch = str.charAt(0);
  17004. if (might_need_semicolon) {
  17005. if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) {
  17006. if (options.semicolons || requireSemicolonChars(ch)) {
  17007. OUTPUT += ";";
  17008. current_col++;
  17009. current_pos++;
  17010. } else {
  17011. OUTPUT += "\n";
  17012. current_pos++;
  17013. current_line++;
  17014. current_col = 0;
  17015. }
  17016. if (!options.beautify)
  17017. might_need_space = false;
  17018. }
  17019. might_need_semicolon = false;
  17020. maybe_newline();
  17021. }
  17022. if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
  17023. var target_line = stack[stack.length - 1].start.line;
  17024. while (current_line < target_line) {
  17025. OUTPUT += "\n";
  17026. current_pos++;
  17027. current_line++;
  17028. current_col = 0;
  17029. might_need_space = false;
  17030. }
  17031. }
  17032. if (might_need_space) {
  17033. var prev = last_char();
  17034. if ((is_identifier_char(prev)
  17035. && (is_identifier_char(ch) || ch == "\\"))
  17036. || (/^[\+\-\/]$/.test(ch) && ch == prev))
  17037. {
  17038. OUTPUT += " ";
  17039. current_col++;
  17040. current_pos++;
  17041. }
  17042. might_need_space = false;
  17043. }
  17044. var a = str.split(/\r?\n/), n = a.length - 1;
  17045. current_line += n;
  17046. if (n == 0) {
  17047. current_col += a[n].length;
  17048. } else {
  17049. current_col = a[n].length;
  17050. }
  17051. current_pos += str.length;
  17052. last = str;
  17053. OUTPUT += str;
  17054. };
  17055. var space = options.beautify ? function() {
  17056. print(" ");
  17057. } : function() {
  17058. might_need_space = true;
  17059. };
  17060. var indent = options.beautify ? function(half) {
  17061. if (options.beautify) {
  17062. print(make_indent(half ? 0.5 : 0));
  17063. }
  17064. } : noop;
  17065. var with_indent = options.beautify ? function(col, cont) {
  17066. if (col === true) col = next_indent();
  17067. var save_indentation = indentation;
  17068. indentation = col;
  17069. var ret = cont();
  17070. indentation = save_indentation;
  17071. return ret;
  17072. } : function(col, cont) { return cont() };
  17073. var newline = options.beautify ? function() {
  17074. print("\n");
  17075. } : noop;
  17076. var semicolon = options.beautify ? function() {
  17077. print(";");
  17078. } : function() {
  17079. might_need_semicolon = true;
  17080. };
  17081. function force_semicolon() {
  17082. might_need_semicolon = false;
  17083. print(";");
  17084. };
  17085. function next_indent() {
  17086. return indentation + options.indent_level;
  17087. };
  17088. function with_block(cont) {
  17089. var ret;
  17090. print("{");
  17091. newline();
  17092. with_indent(next_indent(), function(){
  17093. ret = cont();
  17094. });
  17095. indent();
  17096. print("}");
  17097. return ret;
  17098. };
  17099. function with_parens(cont) {
  17100. print("(");
  17101. //XXX: still nice to have that for argument lists
  17102. //var ret = with_indent(current_col, cont);
  17103. var ret = cont();
  17104. print(")");
  17105. return ret;
  17106. };
  17107. function with_square(cont) {
  17108. print("[");
  17109. //var ret = with_indent(current_col, cont);
  17110. var ret = cont();
  17111. print("]");
  17112. return ret;
  17113. };
  17114. function comma() {
  17115. print(",");
  17116. space();
  17117. };
  17118. function colon() {
  17119. print(":");
  17120. if (options.space_colon) space();
  17121. };
  17122. var add_mapping = options.source_map ? function(token, name) {
  17123. try {
  17124. if (token) options.source_map.add(
  17125. token.file || "?",
  17126. current_line, current_col,
  17127. token.line, token.col,
  17128. (!name && token.type == "name") ? token.value : name
  17129. );
  17130. } catch(ex) {
  17131. AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
  17132. file: token.file,
  17133. line: token.line,
  17134. col: token.col,
  17135. cline: current_line,
  17136. ccol: current_col,
  17137. name: name || ""
  17138. })
  17139. }
  17140. } : noop;
  17141. function get() {
  17142. return OUTPUT;
  17143. };
  17144. if (options.preamble) {
  17145. print(options.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
  17146. }
  17147. var stack = [];
  17148. return {
  17149. get : get,
  17150. toString : get,
  17151. indent : indent,
  17152. indentation : function() { return indentation },
  17153. current_width : function() { return current_col - indentation },
  17154. should_break : function() { return options.width && this.current_width() >= options.width },
  17155. newline : newline,
  17156. print : print,
  17157. space : space,
  17158. comma : comma,
  17159. colon : colon,
  17160. last : function() { return last },
  17161. semicolon : semicolon,
  17162. force_semicolon : force_semicolon,
  17163. to_ascii : to_ascii,
  17164. print_name : function(name) { print(make_name(name)) },
  17165. print_string : function(str) { print(encode_string(str)) },
  17166. next_indent : next_indent,
  17167. with_indent : with_indent,
  17168. with_block : with_block,
  17169. with_parens : with_parens,
  17170. with_square : with_square,
  17171. add_mapping : add_mapping,
  17172. option : function(opt) { return options[opt] },
  17173. line : function() { return current_line },
  17174. col : function() { return current_col },
  17175. pos : function() { return current_pos },
  17176. push_node : function(node) { stack.push(node) },
  17177. pop_node : function() { return stack.pop() },
  17178. stack : function() { return stack },
  17179. parent : function(n) {
  17180. return stack[stack.length - 2 - (n || 0)];
  17181. }
  17182. };
  17183. };
  17184. /* -----[ code generators ]----- */
  17185. (function(){
  17186. /* -----[ utils ]----- */
  17187. function DEFPRINT(nodetype, generator) {
  17188. nodetype.DEFMETHOD("_codegen", generator);
  17189. };
  17190. AST_Node.DEFMETHOD("print", function(stream, force_parens){
  17191. var self = this, generator = self._codegen;
  17192. function doit() {
  17193. self.add_comments(stream);
  17194. self.add_source_map(stream);
  17195. generator(self, stream);
  17196. }
  17197. stream.push_node(self);
  17198. if (force_parens || self.needs_parens(stream)) {
  17199. stream.with_parens(doit);
  17200. } else {
  17201. doit();
  17202. }
  17203. stream.pop_node();
  17204. });
  17205. AST_Node.DEFMETHOD("print_to_string", function(options){
  17206. var s = OutputStream(options);
  17207. this.print(s);
  17208. return s.get();
  17209. });
  17210. /* -----[ comments ]----- */
  17211. AST_Node.DEFMETHOD("add_comments", function(output){
  17212. var c = output.option("comments"), self = this;
  17213. if (c) {
  17214. var start = self.start;
  17215. if (start && !start._comments_dumped) {
  17216. start._comments_dumped = true;
  17217. var comments = start.comments_before || [];
  17218. // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112
  17219. // and https://github.com/mishoo/UglifyJS2/issues/372
  17220. if (self instanceof AST_Exit && self.value) {
  17221. self.value.walk(new TreeWalker(function(node){
  17222. if (node.start && node.start.comments_before) {
  17223. comments = comments.concat(node.start.comments_before);
  17224. node.start.comments_before = [];
  17225. }
  17226. if (node instanceof AST_Function ||
  17227. node instanceof AST_Array ||
  17228. node instanceof AST_Object)
  17229. {
  17230. return true; // don't go inside.
  17231. }
  17232. }));
  17233. }
  17234. if (c.test) {
  17235. comments = comments.filter(function(comment){
  17236. return c.test(comment.value);
  17237. });
  17238. } else if (typeof c == "function") {
  17239. comments = comments.filter(function(comment){
  17240. return c(self, comment);
  17241. });
  17242. }
  17243. comments.forEach(function(c){
  17244. if (/comment[134]/.test(c.type)) {
  17245. output.print("//" + c.value + "\n");
  17246. output.indent();
  17247. }
  17248. else if (c.type == "comment2") {
  17249. output.print("/*" + c.value + "*/");
  17250. if (start.nlb) {
  17251. output.print("\n");
  17252. output.indent();
  17253. } else {
  17254. output.space();
  17255. }
  17256. }
  17257. });
  17258. }
  17259. }
  17260. });
  17261. /* -----[ PARENTHESES ]----- */
  17262. function PARENS(nodetype, func) {
  17263. if (Array.isArray(nodetype)) {
  17264. nodetype.forEach(function(nodetype){
  17265. PARENS(nodetype, func);
  17266. });
  17267. } else {
  17268. nodetype.DEFMETHOD("needs_parens", func);
  17269. }
  17270. };
  17271. PARENS(AST_Node, function(){
  17272. return false;
  17273. });
  17274. // a function expression needs parens around it when it's provably
  17275. // the first token to appear in a statement.
  17276. PARENS(AST_Function, function(output){
  17277. return first_in_statement(output);
  17278. });
  17279. // same goes for an object literal, because otherwise it would be
  17280. // interpreted as a block of code.
  17281. PARENS(AST_Object, function(output){
  17282. return first_in_statement(output);
  17283. });
  17284. PARENS([ AST_Unary, AST_Undefined ], function(output){
  17285. var p = output.parent();
  17286. return p instanceof AST_PropAccess && p.expression === this;
  17287. });
  17288. PARENS(AST_Seq, function(output){
  17289. var p = output.parent();
  17290. return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
  17291. || p instanceof AST_Unary // !(foo, bar, baz)
  17292. || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
  17293. || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
  17294. || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
  17295. || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
  17296. || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
  17297. || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
  17298. * ==> 20 (side effect, set a := 10 and b := 20) */
  17299. ;
  17300. });
  17301. PARENS(AST_Binary, function(output){
  17302. var p = output.parent();
  17303. // (foo && bar)()
  17304. if (p instanceof AST_Call && p.expression === this)
  17305. return true;
  17306. // typeof (foo && bar)
  17307. if (p instanceof AST_Unary)
  17308. return true;
  17309. // (foo && bar)["prop"], (foo && bar).prop
  17310. if (p instanceof AST_PropAccess && p.expression === this)
  17311. return true;
  17312. // this deals with precedence: 3 * (2 + 1)
  17313. if (p instanceof AST_Binary) {
  17314. var po = p.operator, pp = PRECEDENCE[po];
  17315. var so = this.operator, sp = PRECEDENCE[so];
  17316. if (pp > sp
  17317. || (pp == sp
  17318. && this === p.right)) {
  17319. return true;
  17320. }
  17321. }
  17322. });
  17323. PARENS(AST_PropAccess, function(output){
  17324. var p = output.parent();
  17325. if (p instanceof AST_New && p.expression === this) {
  17326. // i.e. new (foo.bar().baz)
  17327. //
  17328. // if there's one call into this subtree, then we need
  17329. // parens around it too, otherwise the call will be
  17330. // interpreted as passing the arguments to the upper New
  17331. // expression.
  17332. try {
  17333. this.walk(new TreeWalker(function(node){
  17334. if (node instanceof AST_Call) throw p;
  17335. }));
  17336. } catch(ex) {
  17337. if (ex !== p) throw ex;
  17338. return true;
  17339. }
  17340. }
  17341. });
  17342. PARENS(AST_Call, function(output){
  17343. var p = output.parent(), p1;
  17344. if (p instanceof AST_New && p.expression === this)
  17345. return true;
  17346. // workaround for Safari bug.
  17347. // https://bugs.webkit.org/show_bug.cgi?id=123506
  17348. return this.expression instanceof AST_Function
  17349. && p instanceof AST_PropAccess
  17350. && p.expression === this
  17351. && (p1 = output.parent(1)) instanceof AST_Assign
  17352. && p1.left === p;
  17353. });
  17354. PARENS(AST_New, function(output){
  17355. var p = output.parent();
  17356. if (no_constructor_parens(this, output)
  17357. && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
  17358. || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)
  17359. return true;
  17360. });
  17361. PARENS(AST_Number, function(output){
  17362. var p = output.parent();
  17363. if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this)
  17364. return true;
  17365. });
  17366. PARENS(AST_NaN, function(output){
  17367. var p = output.parent();
  17368. if (p instanceof AST_PropAccess && p.expression === this)
  17369. return true;
  17370. });
  17371. PARENS([ AST_Assign, AST_Conditional ], function (output){
  17372. var p = output.parent();
  17373. // !(a = false) → true
  17374. if (p instanceof AST_Unary)
  17375. return true;
  17376. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  17377. if (p instanceof AST_Binary && !(p instanceof AST_Assign))
  17378. return true;
  17379. // (a = func)() —or— new (a = Object)()
  17380. if (p instanceof AST_Call && p.expression === this)
  17381. return true;
  17382. // (a = foo) ? bar : baz
  17383. if (p instanceof AST_Conditional && p.condition === this)
  17384. return true;
  17385. // (a = foo)["prop"] —or— (a = foo).prop
  17386. if (p instanceof AST_PropAccess && p.expression === this)
  17387. return true;
  17388. });
  17389. /* -----[ PRINTERS ]----- */
  17390. DEFPRINT(AST_Directive, function(self, output){
  17391. output.print_string(self.value);
  17392. output.semicolon();
  17393. });
  17394. DEFPRINT(AST_Debugger, function(self, output){
  17395. output.print("debugger");
  17396. output.semicolon();
  17397. });
  17398. /* -----[ statements ]----- */
  17399. function display_body(body, is_toplevel, output) {
  17400. var last = body.length - 1;
  17401. body.forEach(function(stmt, i){
  17402. if (!(stmt instanceof AST_EmptyStatement)) {
  17403. output.indent();
  17404. stmt.print(output);
  17405. if (!(i == last && is_toplevel)) {
  17406. output.newline();
  17407. if (is_toplevel) output.newline();
  17408. }
  17409. }
  17410. });
  17411. };
  17412. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){
  17413. force_statement(this.body, output);
  17414. });
  17415. DEFPRINT(AST_Statement, function(self, output){
  17416. self.body.print(output);
  17417. output.semicolon();
  17418. });
  17419. DEFPRINT(AST_Toplevel, function(self, output){
  17420. display_body(self.body, true, output);
  17421. output.print("");
  17422. });
  17423. DEFPRINT(AST_LabeledStatement, function(self, output){
  17424. self.label.print(output);
  17425. output.colon();
  17426. self.body.print(output);
  17427. });
  17428. DEFPRINT(AST_SimpleStatement, function(self, output){
  17429. self.body.print(output);
  17430. output.semicolon();
  17431. });
  17432. function print_bracketed(body, output) {
  17433. if (body.length > 0) output.with_block(function(){
  17434. display_body(body, false, output);
  17435. });
  17436. else output.print("{}");
  17437. };
  17438. DEFPRINT(AST_BlockStatement, function(self, output){
  17439. print_bracketed(self.body, output);
  17440. });
  17441. DEFPRINT(AST_EmptyStatement, function(self, output){
  17442. output.semicolon();
  17443. });
  17444. DEFPRINT(AST_Do, function(self, output){
  17445. output.print("do");
  17446. output.space();
  17447. self._do_print_body(output);
  17448. output.space();
  17449. output.print("while");
  17450. output.space();
  17451. output.with_parens(function(){
  17452. self.condition.print(output);
  17453. });
  17454. output.semicolon();
  17455. });
  17456. DEFPRINT(AST_While, function(self, output){
  17457. output.print("while");
  17458. output.space();
  17459. output.with_parens(function(){
  17460. self.condition.print(output);
  17461. });
  17462. output.space();
  17463. self._do_print_body(output);
  17464. });
  17465. DEFPRINT(AST_For, function(self, output){
  17466. output.print("for");
  17467. output.space();
  17468. output.with_parens(function(){
  17469. if (self.init && !(self.init instanceof AST_EmptyStatement)) {
  17470. if (self.init instanceof AST_Definitions) {
  17471. self.init.print(output);
  17472. } else {
  17473. parenthesize_for_noin(self.init, output, true);
  17474. }
  17475. output.print(";");
  17476. output.space();
  17477. } else {
  17478. output.print(";");
  17479. }
  17480. if (self.condition) {
  17481. self.condition.print(output);
  17482. output.print(";");
  17483. output.space();
  17484. } else {
  17485. output.print(";");
  17486. }
  17487. if (self.step) {
  17488. self.step.print(output);
  17489. }
  17490. });
  17491. output.space();
  17492. self._do_print_body(output);
  17493. });
  17494. DEFPRINT(AST_ForIn, function(self, output){
  17495. output.print("for");
  17496. output.space();
  17497. output.with_parens(function(){
  17498. self.init.print(output);
  17499. output.space();
  17500. output.print("in");
  17501. output.space();
  17502. self.object.print(output);
  17503. });
  17504. output.space();
  17505. self._do_print_body(output);
  17506. });
  17507. DEFPRINT(AST_With, function(self, output){
  17508. output.print("with");
  17509. output.space();
  17510. output.with_parens(function(){
  17511. self.expression.print(output);
  17512. });
  17513. output.space();
  17514. self._do_print_body(output);
  17515. });
  17516. /* -----[ functions ]----- */
  17517. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){
  17518. var self = this;
  17519. if (!nokeyword) {
  17520. output.print("function");
  17521. }
  17522. if (self.name) {
  17523. output.space();
  17524. self.name.print(output);
  17525. }
  17526. output.with_parens(function(){
  17527. self.argnames.forEach(function(arg, i){
  17528. if (i) output.comma();
  17529. arg.print(output);
  17530. });
  17531. });
  17532. output.space();
  17533. print_bracketed(self.body, output);
  17534. });
  17535. DEFPRINT(AST_Lambda, function(self, output){
  17536. self._do_print(output);
  17537. });
  17538. /* -----[ exits ]----- */
  17539. AST_Exit.DEFMETHOD("_do_print", function(output, kind){
  17540. output.print(kind);
  17541. if (this.value) {
  17542. output.space();
  17543. this.value.print(output);
  17544. }
  17545. output.semicolon();
  17546. });
  17547. DEFPRINT(AST_Return, function(self, output){
  17548. self._do_print(output, "return");
  17549. });
  17550. DEFPRINT(AST_Throw, function(self, output){
  17551. self._do_print(output, "throw");
  17552. });
  17553. /* -----[ loop control ]----- */
  17554. AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){
  17555. output.print(kind);
  17556. if (this.label) {
  17557. output.space();
  17558. this.label.print(output);
  17559. }
  17560. output.semicolon();
  17561. });
  17562. DEFPRINT(AST_Break, function(self, output){
  17563. self._do_print(output, "break");
  17564. });
  17565. DEFPRINT(AST_Continue, function(self, output){
  17566. self._do_print(output, "continue");
  17567. });
  17568. /* -----[ if ]----- */
  17569. function make_then(self, output) {
  17570. if (output.option("bracketize")) {
  17571. make_block(self.body, output);
  17572. return;
  17573. }
  17574. // The squeezer replaces "block"-s that contain only a single
  17575. // statement with the statement itself; technically, the AST
  17576. // is correct, but this can create problems when we output an
  17577. // IF having an ELSE clause where the THEN clause ends in an
  17578. // IF *without* an ELSE block (then the outer ELSE would refer
  17579. // to the inner IF). This function checks for this case and
  17580. // adds the block brackets if needed.
  17581. if (!self.body)
  17582. return output.force_semicolon();
  17583. if (self.body instanceof AST_Do
  17584. && !output.option("screw_ie8")) {
  17585. // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE
  17586. // croaks with "syntax error" on code like this: if (foo)
  17587. // do ... while(cond); else ... we need block brackets
  17588. // around do/while
  17589. make_block(self.body, output);
  17590. return;
  17591. }
  17592. var b = self.body;
  17593. while (true) {
  17594. if (b instanceof AST_If) {
  17595. if (!b.alternative) {
  17596. make_block(self.body, output);
  17597. return;
  17598. }
  17599. b = b.alternative;
  17600. }
  17601. else if (b instanceof AST_StatementWithBody) {
  17602. b = b.body;
  17603. }
  17604. else break;
  17605. }
  17606. force_statement(self.body, output);
  17607. };
  17608. DEFPRINT(AST_If, function(self, output){
  17609. output.print("if");
  17610. output.space();
  17611. output.with_parens(function(){
  17612. self.condition.print(output);
  17613. });
  17614. output.space();
  17615. if (self.alternative) {
  17616. make_then(self, output);
  17617. output.space();
  17618. output.print("else");
  17619. output.space();
  17620. force_statement(self.alternative, output);
  17621. } else {
  17622. self._do_print_body(output);
  17623. }
  17624. });
  17625. /* -----[ switch ]----- */
  17626. DEFPRINT(AST_Switch, function(self, output){
  17627. output.print("switch");
  17628. output.space();
  17629. output.with_parens(function(){
  17630. self.expression.print(output);
  17631. });
  17632. output.space();
  17633. if (self.body.length > 0) output.with_block(function(){
  17634. self.body.forEach(function(stmt, i){
  17635. if (i) output.newline();
  17636. output.indent(true);
  17637. stmt.print(output);
  17638. });
  17639. });
  17640. else output.print("{}");
  17641. });
  17642. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){
  17643. if (this.body.length > 0) {
  17644. output.newline();
  17645. this.body.forEach(function(stmt){
  17646. output.indent();
  17647. stmt.print(output);
  17648. output.newline();
  17649. });
  17650. }
  17651. });
  17652. DEFPRINT(AST_Default, function(self, output){
  17653. output.print("default:");
  17654. self._do_print_body(output);
  17655. });
  17656. DEFPRINT(AST_Case, function(self, output){
  17657. output.print("case");
  17658. output.space();
  17659. self.expression.print(output);
  17660. output.print(":");
  17661. self._do_print_body(output);
  17662. });
  17663. /* -----[ exceptions ]----- */
  17664. DEFPRINT(AST_Try, function(self, output){
  17665. output.print("try");
  17666. output.space();
  17667. print_bracketed(self.body, output);
  17668. if (self.bcatch) {
  17669. output.space();
  17670. self.bcatch.print(output);
  17671. }
  17672. if (self.bfinally) {
  17673. output.space();
  17674. self.bfinally.print(output);
  17675. }
  17676. });
  17677. DEFPRINT(AST_Catch, function(self, output){
  17678. output.print("catch");
  17679. output.space();
  17680. output.with_parens(function(){
  17681. self.argname.print(output);
  17682. });
  17683. output.space();
  17684. print_bracketed(self.body, output);
  17685. });
  17686. DEFPRINT(AST_Finally, function(self, output){
  17687. output.print("finally");
  17688. output.space();
  17689. print_bracketed(self.body, output);
  17690. });
  17691. /* -----[ var/const ]----- */
  17692. AST_Definitions.DEFMETHOD("_do_print", function(output, kind){
  17693. output.print(kind);
  17694. output.space();
  17695. this.definitions.forEach(function(def, i){
  17696. if (i) output.comma();
  17697. def.print(output);
  17698. });
  17699. var p = output.parent();
  17700. var in_for = p instanceof AST_For || p instanceof AST_ForIn;
  17701. var avoid_semicolon = in_for && p.init === this;
  17702. if (!avoid_semicolon)
  17703. output.semicolon();
  17704. });
  17705. DEFPRINT(AST_Var, function(self, output){
  17706. self._do_print(output, "var");
  17707. });
  17708. DEFPRINT(AST_Const, function(self, output){
  17709. self._do_print(output, "const");
  17710. });
  17711. function parenthesize_for_noin(node, output, noin) {
  17712. if (!noin) node.print(output);
  17713. else try {
  17714. // need to take some precautions here:
  17715. // https://github.com/mishoo/UglifyJS2/issues/60
  17716. node.walk(new TreeWalker(function(node){
  17717. if (node instanceof AST_Binary && node.operator == "in")
  17718. throw output;
  17719. }));
  17720. node.print(output);
  17721. } catch(ex) {
  17722. if (ex !== output) throw ex;
  17723. node.print(output, true);
  17724. }
  17725. };
  17726. DEFPRINT(AST_VarDef, function(self, output){
  17727. self.name.print(output);
  17728. if (self.value) {
  17729. output.space();
  17730. output.print("=");
  17731. output.space();
  17732. var p = output.parent(1);
  17733. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  17734. parenthesize_for_noin(self.value, output, noin);
  17735. }
  17736. });
  17737. /* -----[ other expressions ]----- */
  17738. DEFPRINT(AST_Call, function(self, output){
  17739. self.expression.print(output);
  17740. if (self instanceof AST_New && no_constructor_parens(self, output))
  17741. return;
  17742. output.with_parens(function(){
  17743. self.args.forEach(function(expr, i){
  17744. if (i) output.comma();
  17745. expr.print(output);
  17746. });
  17747. });
  17748. });
  17749. DEFPRINT(AST_New, function(self, output){
  17750. output.print("new");
  17751. output.space();
  17752. AST_Call.prototype._codegen(self, output);
  17753. });
  17754. AST_Seq.DEFMETHOD("_do_print", function(output){
  17755. this.car.print(output);
  17756. if (this.cdr) {
  17757. output.comma();
  17758. if (output.should_break()) {
  17759. output.newline();
  17760. output.indent();
  17761. }
  17762. this.cdr.print(output);
  17763. }
  17764. });
  17765. DEFPRINT(AST_Seq, function(self, output){
  17766. self._do_print(output);
  17767. // var p = output.parent();
  17768. // if (p instanceof AST_Statement) {
  17769. // output.with_indent(output.next_indent(), function(){
  17770. // self._do_print(output);
  17771. // });
  17772. // } else {
  17773. // self._do_print(output);
  17774. // }
  17775. });
  17776. DEFPRINT(AST_Dot, function(self, output){
  17777. var expr = self.expression;
  17778. expr.print(output);
  17779. if (expr instanceof AST_Number && expr.getValue() >= 0) {
  17780. if (!/[xa-f.]/i.test(output.last())) {
  17781. output.print(".");
  17782. }
  17783. }
  17784. output.print(".");
  17785. // the name after dot would be mapped about here.
  17786. output.add_mapping(self.end);
  17787. output.print_name(self.property);
  17788. });
  17789. DEFPRINT(AST_Sub, function(self, output){
  17790. self.expression.print(output);
  17791. output.print("[");
  17792. self.property.print(output);
  17793. output.print("]");
  17794. });
  17795. DEFPRINT(AST_UnaryPrefix, function(self, output){
  17796. var op = self.operator;
  17797. output.print(op);
  17798. if (/^[a-z]/i.test(op)
  17799. || (/[+-]$/.test(op)
  17800. && self.expression instanceof AST_UnaryPrefix
  17801. && /^[+-]/.test(self.expression.operator))) {
  17802. output.space();
  17803. }
  17804. self.expression.print(output);
  17805. });
  17806. DEFPRINT(AST_UnaryPostfix, function(self, output){
  17807. self.expression.print(output);
  17808. output.print(self.operator);
  17809. });
  17810. DEFPRINT(AST_Binary, function(self, output){
  17811. self.left.print(output);
  17812. output.space();
  17813. output.print(self.operator);
  17814. if (self.operator == "<"
  17815. && self.right instanceof AST_UnaryPrefix
  17816. && self.right.operator == "!"
  17817. && self.right.expression instanceof AST_UnaryPrefix
  17818. && self.right.expression.operator == "--") {
  17819. // space is mandatory to avoid outputting <!--
  17820. // http://javascript.spec.whatwg.org/#comment-syntax
  17821. output.print(" ");
  17822. } else {
  17823. // the space is optional depending on "beautify"
  17824. output.space();
  17825. }
  17826. self.right.print(output);
  17827. });
  17828. DEFPRINT(AST_Conditional, function(self, output){
  17829. self.condition.print(output);
  17830. output.space();
  17831. output.print("?");
  17832. output.space();
  17833. self.consequent.print(output);
  17834. output.space();
  17835. output.colon();
  17836. self.alternative.print(output);
  17837. });
  17838. /* -----[ literals ]----- */
  17839. DEFPRINT(AST_Array, function(self, output){
  17840. output.with_square(function(){
  17841. var a = self.elements, len = a.length;
  17842. if (len > 0) output.space();
  17843. a.forEach(function(exp, i){
  17844. if (i) output.comma();
  17845. exp.print(output);
  17846. // If the final element is a hole, we need to make sure it
  17847. // doesn't look like a trailing comma, by inserting an actual
  17848. // trailing comma.
  17849. if (i === len - 1 && exp instanceof AST_Hole)
  17850. output.comma();
  17851. });
  17852. if (len > 0) output.space();
  17853. });
  17854. });
  17855. DEFPRINT(AST_Object, function(self, output){
  17856. if (self.properties.length > 0) output.with_block(function(){
  17857. self.properties.forEach(function(prop, i){
  17858. if (i) {
  17859. output.print(",");
  17860. output.newline();
  17861. }
  17862. output.indent();
  17863. prop.print(output);
  17864. });
  17865. output.newline();
  17866. });
  17867. else output.print("{}");
  17868. });
  17869. DEFPRINT(AST_ObjectKeyVal, function(self, output){
  17870. var key = self.key;
  17871. if (output.option("quote_keys")) {
  17872. output.print_string(key + "");
  17873. } else if ((typeof key == "number"
  17874. || !output.option("beautify")
  17875. && +key + "" == key)
  17876. && parseFloat(key) >= 0) {
  17877. output.print(make_num(key));
  17878. } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) {
  17879. output.print_name(key);
  17880. } else {
  17881. output.print_string(key);
  17882. }
  17883. output.colon();
  17884. self.value.print(output);
  17885. });
  17886. DEFPRINT(AST_ObjectSetter, function(self, output){
  17887. output.print("set");
  17888. output.space();
  17889. self.key.print(output);
  17890. self.value._do_print(output, true);
  17891. });
  17892. DEFPRINT(AST_ObjectGetter, function(self, output){
  17893. output.print("get");
  17894. output.space();
  17895. self.key.print(output);
  17896. self.value._do_print(output, true);
  17897. });
  17898. DEFPRINT(AST_Symbol, function(self, output){
  17899. var def = self.definition();
  17900. output.print_name(def ? def.mangled_name || def.name : self.name);
  17901. });
  17902. DEFPRINT(AST_Undefined, function(self, output){
  17903. output.print("void 0");
  17904. });
  17905. DEFPRINT(AST_Hole, noop);
  17906. DEFPRINT(AST_Infinity, function(self, output){
  17907. output.print("1/0");
  17908. });
  17909. DEFPRINT(AST_NaN, function(self, output){
  17910. output.print("0/0");
  17911. });
  17912. DEFPRINT(AST_This, function(self, output){
  17913. output.print("this");
  17914. });
  17915. DEFPRINT(AST_Constant, function(self, output){
  17916. output.print(self.getValue());
  17917. });
  17918. DEFPRINT(AST_String, function(self, output){
  17919. output.print_string(self.getValue());
  17920. });
  17921. DEFPRINT(AST_Number, function(self, output){
  17922. output.print(make_num(self.getValue()));
  17923. });
  17924. function regexp_safe_literal(code) {
  17925. return [
  17926. 0x5c , // \
  17927. 0x2f , // /
  17928. 0x2e , // .
  17929. 0x2b , // +
  17930. 0x2a , // *
  17931. 0x3f , // ?
  17932. 0x28 , // (
  17933. 0x29 , // )
  17934. 0x5b , // [
  17935. 0x5d , // ]
  17936. 0x7b , // {
  17937. 0x7d , // }
  17938. 0x24 , // $
  17939. 0x5e , // ^
  17940. 0x3a , // :
  17941. 0x7c , // |
  17942. 0x21 , // !
  17943. 0x0a , // \n
  17944. 0x0d , // \r
  17945. 0x00 , // \0
  17946. 0xfeff , // Unicode BOM
  17947. 0x2028 , // unicode "line separator"
  17948. 0x2029 , // unicode "paragraph separator"
  17949. ].indexOf(code) < 0;
  17950. };
  17951. DEFPRINT(AST_RegExp, function(self, output){
  17952. var str = self.getValue().toString();
  17953. if (output.option("ascii_only")) {
  17954. str = output.to_ascii(str);
  17955. } else if (output.option("unescape_regexps")) {
  17956. str = str.split("\\\\").map(function(str){
  17957. return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){
  17958. var code = parseInt(s.substr(2), 16);
  17959. return regexp_safe_literal(code) ? String.fromCharCode(code) : s;
  17960. });
  17961. }).join("\\\\");
  17962. }
  17963. output.print(str);
  17964. var p = output.parent();
  17965. if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)
  17966. output.print(" ");
  17967. });
  17968. function force_statement(stat, output) {
  17969. if (output.option("bracketize")) {
  17970. if (!stat || stat instanceof AST_EmptyStatement)
  17971. output.print("{}");
  17972. else if (stat instanceof AST_BlockStatement)
  17973. stat.print(output);
  17974. else output.with_block(function(){
  17975. output.indent();
  17976. stat.print(output);
  17977. output.newline();
  17978. });
  17979. } else {
  17980. if (!stat || stat instanceof AST_EmptyStatement)
  17981. output.force_semicolon();
  17982. else
  17983. stat.print(output);
  17984. }
  17985. };
  17986. // return true if the node at the top of the stack (that means the
  17987. // innermost node in the current output) is lexically the first in
  17988. // a statement.
  17989. function first_in_statement(output) {
  17990. var a = output.stack(), i = a.length, node = a[--i], p = a[--i];
  17991. while (i > 0) {
  17992. if (p instanceof AST_Statement && p.body === node)
  17993. return true;
  17994. if ((p instanceof AST_Seq && p.car === node ) ||
  17995. (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) ||
  17996. (p instanceof AST_Dot && p.expression === node ) ||
  17997. (p instanceof AST_Sub && p.expression === node ) ||
  17998. (p instanceof AST_Conditional && p.condition === node ) ||
  17999. (p instanceof AST_Binary && p.left === node ) ||
  18000. (p instanceof AST_UnaryPostfix && p.expression === node ))
  18001. {
  18002. node = p;
  18003. p = a[--i];
  18004. } else {
  18005. return false;
  18006. }
  18007. }
  18008. };
  18009. // self should be AST_New. decide if we want to show parens or not.
  18010. function no_constructor_parens(self, output) {
  18011. return self.args.length == 0 && !output.option("beautify");
  18012. };
  18013. function best_of(a) {
  18014. var best = a[0], len = best.length;
  18015. for (var i = 1; i < a.length; ++i) {
  18016. if (a[i].length < len) {
  18017. best = a[i];
  18018. len = best.length;
  18019. }
  18020. }
  18021. return best;
  18022. };
  18023. function make_num(num) {
  18024. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  18025. if (Math.floor(num) === num) {
  18026. if (num >= 0) {
  18027. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  18028. "0" + num.toString(8)); // same.
  18029. } else {
  18030. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  18031. "-0" + (-num).toString(8)); // same.
  18032. }
  18033. if ((m = /^(.*?)(0+)$/.exec(num))) {
  18034. a.push(m[1] + "e" + m[2].length);
  18035. }
  18036. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  18037. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  18038. str.substr(str.indexOf(".")));
  18039. }
  18040. return best_of(a);
  18041. };
  18042. function make_block(stmt, output) {
  18043. if (stmt instanceof AST_BlockStatement) {
  18044. stmt.print(output);
  18045. return;
  18046. }
  18047. output.with_block(function(){
  18048. output.indent();
  18049. stmt.print(output);
  18050. output.newline();
  18051. });
  18052. };
  18053. /* -----[ source map generators ]----- */
  18054. function DEFMAP(nodetype, generator) {
  18055. nodetype.DEFMETHOD("add_source_map", function(stream){
  18056. generator(this, stream);
  18057. });
  18058. };
  18059. // We could easily add info for ALL nodes, but it seems to me that
  18060. // would be quite wasteful, hence this noop in the base class.
  18061. DEFMAP(AST_Node, noop);
  18062. function basic_sourcemap_gen(self, output) {
  18063. output.add_mapping(self.start);
  18064. };
  18065. // XXX: I'm not exactly sure if we need it for all of these nodes,
  18066. // or if we should add even more.
  18067. DEFMAP(AST_Directive, basic_sourcemap_gen);
  18068. DEFMAP(AST_Debugger, basic_sourcemap_gen);
  18069. DEFMAP(AST_Symbol, basic_sourcemap_gen);
  18070. DEFMAP(AST_Jump, basic_sourcemap_gen);
  18071. DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);
  18072. DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it
  18073. DEFMAP(AST_Lambda, basic_sourcemap_gen);
  18074. DEFMAP(AST_Switch, basic_sourcemap_gen);
  18075. DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);
  18076. DEFMAP(AST_BlockStatement, basic_sourcemap_gen);
  18077. DEFMAP(AST_Toplevel, noop);
  18078. DEFMAP(AST_New, basic_sourcemap_gen);
  18079. DEFMAP(AST_Try, basic_sourcemap_gen);
  18080. DEFMAP(AST_Catch, basic_sourcemap_gen);
  18081. DEFMAP(AST_Finally, basic_sourcemap_gen);
  18082. DEFMAP(AST_Definitions, basic_sourcemap_gen);
  18083. DEFMAP(AST_Constant, basic_sourcemap_gen);
  18084. DEFMAP(AST_ObjectProperty, function(self, output){
  18085. output.add_mapping(self.start, self.key);
  18086. });
  18087. })();
  18088. /***********************************************************************
  18089. A JavaScript tokenizer / parser / beautifier / compressor.
  18090. https://github.com/mishoo/UglifyJS2
  18091. -------------------------------- (C) ---------------------------------
  18092. Author: Mihai Bazon
  18093. <mihai.bazon@gmail.com>
  18094. http://mihai.bazon.net/blog
  18095. Distributed under the BSD license:
  18096. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  18097. Redistribution and use in source and binary forms, with or without
  18098. modification, are permitted provided that the following conditions
  18099. are met:
  18100. * Redistributions of source code must retain the above
  18101. copyright notice, this list of conditions and the following
  18102. disclaimer.
  18103. * Redistributions in binary form must reproduce the above
  18104. copyright notice, this list of conditions and the following
  18105. disclaimer in the documentation and/or other materials
  18106. provided with the distribution.
  18107. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  18108. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18109. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  18110. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  18111. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  18112. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18113. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  18114. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  18115. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  18116. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  18117. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  18118. SUCH DAMAGE.
  18119. ***********************************************************************/
  18120. "use strict";
  18121. function Compressor(options, false_by_default) {
  18122. if (!(this instanceof Compressor))
  18123. return new Compressor(options, false_by_default);
  18124. TreeTransformer.call(this, this.before, this.after);
  18125. this.options = defaults(options, {
  18126. sequences : !false_by_default,
  18127. properties : !false_by_default,
  18128. dead_code : !false_by_default,
  18129. drop_debugger : !false_by_default,
  18130. unsafe : false,
  18131. unsafe_comps : false,
  18132. conditionals : !false_by_default,
  18133. comparisons : !false_by_default,
  18134. evaluate : !false_by_default,
  18135. booleans : !false_by_default,
  18136. loops : !false_by_default,
  18137. unused : !false_by_default,
  18138. hoist_funs : !false_by_default,
  18139. keep_fargs : false,
  18140. hoist_vars : false,
  18141. if_return : !false_by_default,
  18142. join_vars : !false_by_default,
  18143. cascade : !false_by_default,
  18144. side_effects : !false_by_default,
  18145. pure_getters : false,
  18146. pure_funcs : null,
  18147. negate_iife : !false_by_default,
  18148. screw_ie8 : false,
  18149. drop_console : false,
  18150. angular : false,
  18151. warnings : true,
  18152. global_defs : {}
  18153. }, true);
  18154. };
  18155. Compressor.prototype = new TreeTransformer;
  18156. merge(Compressor.prototype, {
  18157. option: function(key) { return this.options[key] },
  18158. warn: function() {
  18159. if (this.options.warnings)
  18160. AST_Node.warn.apply(AST_Node, arguments);
  18161. },
  18162. before: function(node, descend, in_list) {
  18163. if (node._squeezed) return node;
  18164. var was_scope = false;
  18165. if (node instanceof AST_Scope) {
  18166. node = node.hoist_declarations(this);
  18167. was_scope = true;
  18168. }
  18169. descend(node, this);
  18170. node = node.optimize(this);
  18171. if (was_scope && node instanceof AST_Scope) {
  18172. node.drop_unused(this);
  18173. descend(node, this);
  18174. }
  18175. node._squeezed = true;
  18176. return node;
  18177. }
  18178. });
  18179. (function(){
  18180. function OPT(node, optimizer) {
  18181. node.DEFMETHOD("optimize", function(compressor){
  18182. var self = this;
  18183. if (self._optimized) return self;
  18184. var opt = optimizer(self, compressor);
  18185. opt._optimized = true;
  18186. if (opt === self) return opt;
  18187. return opt.transform(compressor);
  18188. });
  18189. };
  18190. OPT(AST_Node, function(self, compressor){
  18191. return self;
  18192. });
  18193. AST_Node.DEFMETHOD("equivalent_to", function(node){
  18194. // XXX: this is a rather expensive way to test two node's equivalence:
  18195. return this.print_to_string() == node.print_to_string();
  18196. });
  18197. function make_node(ctor, orig, props) {
  18198. if (!props) props = {};
  18199. if (orig) {
  18200. if (!props.start) props.start = orig.start;
  18201. if (!props.end) props.end = orig.end;
  18202. }
  18203. return new ctor(props);
  18204. };
  18205. function make_node_from_constant(compressor, val, orig) {
  18206. // XXX: WIP.
  18207. // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){
  18208. // if (node instanceof AST_SymbolRef) {
  18209. // var scope = compressor.find_parent(AST_Scope);
  18210. // var def = scope.find_variable(node);
  18211. // node.thedef = def;
  18212. // return node;
  18213. // }
  18214. // })).transform(compressor);
  18215. if (val instanceof AST_Node) return val.transform(compressor);
  18216. switch (typeof val) {
  18217. case "string":
  18218. return make_node(AST_String, orig, {
  18219. value: val
  18220. }).optimize(compressor);
  18221. case "number":
  18222. return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, {
  18223. value: val
  18224. }).optimize(compressor);
  18225. case "boolean":
  18226. return make_node(val ? AST_True : AST_False, orig).optimize(compressor);
  18227. case "undefined":
  18228. return make_node(AST_Undefined, orig).optimize(compressor);
  18229. default:
  18230. if (val === null) {
  18231. return make_node(AST_Null, orig).optimize(compressor);
  18232. }
  18233. if (val instanceof RegExp) {
  18234. return make_node(AST_RegExp, orig).optimize(compressor);
  18235. }
  18236. throw new Error(string_template("Can't handle constant of type: {type}", {
  18237. type: typeof val
  18238. }));
  18239. }
  18240. };
  18241. function as_statement_array(thing) {
  18242. if (thing === null) return [];
  18243. if (thing instanceof AST_BlockStatement) return thing.body;
  18244. if (thing instanceof AST_EmptyStatement) return [];
  18245. if (thing instanceof AST_Statement) return [ thing ];
  18246. throw new Error("Can't convert thing to statement array");
  18247. };
  18248. function is_empty(thing) {
  18249. if (thing === null) return true;
  18250. if (thing instanceof AST_EmptyStatement) return true;
  18251. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  18252. return false;
  18253. };
  18254. function loop_body(x) {
  18255. if (x instanceof AST_Switch) return x;
  18256. if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
  18257. return (x.body instanceof AST_BlockStatement ? x.body : x);
  18258. }
  18259. return x;
  18260. };
  18261. function tighten_body(statements, compressor) {
  18262. var CHANGED;
  18263. do {
  18264. CHANGED = false;
  18265. if (compressor.option("angular")) {
  18266. statements = process_for_angular(statements);
  18267. }
  18268. statements = eliminate_spurious_blocks(statements);
  18269. if (compressor.option("dead_code")) {
  18270. statements = eliminate_dead_code(statements, compressor);
  18271. }
  18272. if (compressor.option("if_return")) {
  18273. statements = handle_if_return(statements, compressor);
  18274. }
  18275. if (compressor.option("sequences")) {
  18276. statements = sequencesize(statements, compressor);
  18277. }
  18278. if (compressor.option("join_vars")) {
  18279. statements = join_consecutive_vars(statements, compressor);
  18280. }
  18281. } while (CHANGED);
  18282. if (compressor.option("negate_iife")) {
  18283. negate_iifes(statements, compressor);
  18284. }
  18285. return statements;
  18286. function process_for_angular(statements) {
  18287. function make_injector(func, name) {
  18288. return make_node(AST_SimpleStatement, func, {
  18289. body: make_node(AST_Assign, func, {
  18290. operator: "=",
  18291. left: make_node(AST_Dot, name, {
  18292. expression: make_node(AST_SymbolRef, name, name),
  18293. property: "$inject"
  18294. }),
  18295. right: make_node(AST_Array, func, {
  18296. elements: func.argnames.map(function(sym){
  18297. return make_node(AST_String, sym, { value: sym.name });
  18298. })
  18299. })
  18300. })
  18301. });
  18302. }
  18303. return statements.reduce(function(a, stat){
  18304. a.push(stat);
  18305. var token = stat.start;
  18306. var comments = token.comments_before;
  18307. if (comments && comments.length > 0) {
  18308. var last = comments.pop();
  18309. if (/@ngInject/.test(last.value)) {
  18310. // case 1: defun
  18311. if (stat instanceof AST_Defun) {
  18312. a.push(make_injector(stat, stat.name));
  18313. }
  18314. else if (stat instanceof AST_Definitions) {
  18315. stat.definitions.forEach(function(def){
  18316. if (def.value && def.value instanceof AST_Lambda) {
  18317. a.push(make_injector(def.value, def.name));
  18318. }
  18319. });
  18320. }
  18321. else {
  18322. compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token);
  18323. }
  18324. }
  18325. }
  18326. return a;
  18327. }, []);
  18328. }
  18329. function eliminate_spurious_blocks(statements) {
  18330. var seen_dirs = [];
  18331. return statements.reduce(function(a, stat){
  18332. if (stat instanceof AST_BlockStatement) {
  18333. CHANGED = true;
  18334. a.push.apply(a, eliminate_spurious_blocks(stat.body));
  18335. } else if (stat instanceof AST_EmptyStatement) {
  18336. CHANGED = true;
  18337. } else if (stat instanceof AST_Directive) {
  18338. if (seen_dirs.indexOf(stat.value) < 0) {
  18339. a.push(stat);
  18340. seen_dirs.push(stat.value);
  18341. } else {
  18342. CHANGED = true;
  18343. }
  18344. } else {
  18345. a.push(stat);
  18346. }
  18347. return a;
  18348. }, []);
  18349. };
  18350. function handle_if_return(statements, compressor) {
  18351. var self = compressor.self();
  18352. var in_lambda = self instanceof AST_Lambda;
  18353. var ret = [];
  18354. loop: for (var i = statements.length; --i >= 0;) {
  18355. var stat = statements[i];
  18356. switch (true) {
  18357. case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):
  18358. CHANGED = true;
  18359. // note, ret.length is probably always zero
  18360. // because we drop unreachable code before this
  18361. // step. nevertheless, it's good to check.
  18362. continue loop;
  18363. case stat instanceof AST_If:
  18364. if (stat.body instanceof AST_Return) {
  18365. //---
  18366. // pretty silly case, but:
  18367. // if (foo()) return; return; ==> foo(); return;
  18368. if (((in_lambda && ret.length == 0)
  18369. || (ret[0] instanceof AST_Return && !ret[0].value))
  18370. && !stat.body.value && !stat.alternative) {
  18371. CHANGED = true;
  18372. var cond = make_node(AST_SimpleStatement, stat.condition, {
  18373. body: stat.condition
  18374. });
  18375. ret.unshift(cond);
  18376. continue loop;
  18377. }
  18378. //---
  18379. // if (foo()) return x; return y; ==> return foo() ? x : y;
  18380. if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
  18381. CHANGED = true;
  18382. stat = stat.clone();
  18383. stat.alternative = ret[0];
  18384. ret[0] = stat.transform(compressor);
  18385. continue loop;
  18386. }
  18387. //---
  18388. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  18389. if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) {
  18390. CHANGED = true;
  18391. stat = stat.clone();
  18392. stat.alternative = ret[0] || make_node(AST_Return, stat, {
  18393. value: make_node(AST_Undefined, stat)
  18394. });
  18395. ret[0] = stat.transform(compressor);
  18396. continue loop;
  18397. }
  18398. //---
  18399. // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }
  18400. if (!stat.body.value && in_lambda) {
  18401. CHANGED = true;
  18402. stat = stat.clone();
  18403. stat.condition = stat.condition.negate(compressor);
  18404. stat.body = make_node(AST_BlockStatement, stat, {
  18405. body: as_statement_array(stat.alternative).concat(ret)
  18406. });
  18407. stat.alternative = null;
  18408. ret = [ stat.transform(compressor) ];
  18409. continue loop;
  18410. }
  18411. //---
  18412. if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement
  18413. && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {
  18414. CHANGED = true;
  18415. ret.push(make_node(AST_Return, ret[0], {
  18416. value: make_node(AST_Undefined, ret[0])
  18417. }).transform(compressor));
  18418. ret = as_statement_array(stat.alternative).concat(ret);
  18419. ret.unshift(stat);
  18420. continue loop;
  18421. }
  18422. }
  18423. var ab = aborts(stat.body);
  18424. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  18425. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  18426. || (ab instanceof AST_Continue && self === loop_body(lct))
  18427. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  18428. if (ab.label) {
  18429. remove(ab.label.thedef.references, ab);
  18430. }
  18431. CHANGED = true;
  18432. var body = as_statement_array(stat.body).slice(0, -1);
  18433. stat = stat.clone();
  18434. stat.condition = stat.condition.negate(compressor);
  18435. stat.body = make_node(AST_BlockStatement, stat, {
  18436. body: as_statement_array(stat.alternative).concat(ret)
  18437. });
  18438. stat.alternative = make_node(AST_BlockStatement, stat, {
  18439. body: body
  18440. });
  18441. ret = [ stat.transform(compressor) ];
  18442. continue loop;
  18443. }
  18444. var ab = aborts(stat.alternative);
  18445. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  18446. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  18447. || (ab instanceof AST_Continue && self === loop_body(lct))
  18448. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  18449. if (ab.label) {
  18450. remove(ab.label.thedef.references, ab);
  18451. }
  18452. CHANGED = true;
  18453. stat = stat.clone();
  18454. stat.body = make_node(AST_BlockStatement, stat.body, {
  18455. body: as_statement_array(stat.body).concat(ret)
  18456. });
  18457. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  18458. body: as_statement_array(stat.alternative).slice(0, -1)
  18459. });
  18460. ret = [ stat.transform(compressor) ];
  18461. continue loop;
  18462. }
  18463. ret.unshift(stat);
  18464. break;
  18465. default:
  18466. ret.unshift(stat);
  18467. break;
  18468. }
  18469. }
  18470. return ret;
  18471. };
  18472. function eliminate_dead_code(statements, compressor) {
  18473. var has_quit = false;
  18474. var orig = statements.length;
  18475. var self = compressor.self();
  18476. statements = statements.reduce(function(a, stat){
  18477. if (has_quit) {
  18478. extract_declarations_from_unreachable_code(compressor, stat, a);
  18479. } else {
  18480. if (stat instanceof AST_LoopControl) {
  18481. var lct = compressor.loopcontrol_target(stat.label);
  18482. if ((stat instanceof AST_Break
  18483. && lct instanceof AST_BlockStatement
  18484. && loop_body(lct) === self) || (stat instanceof AST_Continue
  18485. && loop_body(lct) === self)) {
  18486. if (stat.label) {
  18487. remove(stat.label.thedef.references, stat);
  18488. }
  18489. } else {
  18490. a.push(stat);
  18491. }
  18492. } else {
  18493. a.push(stat);
  18494. }
  18495. if (aborts(stat)) has_quit = true;
  18496. }
  18497. return a;
  18498. }, []);
  18499. CHANGED = statements.length != orig;
  18500. return statements;
  18501. };
  18502. function sequencesize(statements, compressor) {
  18503. if (statements.length < 2) return statements;
  18504. var seq = [], ret = [];
  18505. function push_seq() {
  18506. seq = AST_Seq.from_array(seq);
  18507. if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
  18508. body: seq
  18509. }));
  18510. seq = [];
  18511. };
  18512. statements.forEach(function(stat){
  18513. if (stat instanceof AST_SimpleStatement) seq.push(stat.body);
  18514. else push_seq(), ret.push(stat);
  18515. });
  18516. push_seq();
  18517. ret = sequencesize_2(ret, compressor);
  18518. CHANGED = ret.length != statements.length;
  18519. return ret;
  18520. };
  18521. function sequencesize_2(statements, compressor) {
  18522. function cons_seq(right) {
  18523. ret.pop();
  18524. var left = prev.body;
  18525. if (left instanceof AST_Seq) {
  18526. left.add(right);
  18527. } else {
  18528. left = AST_Seq.cons(left, right);
  18529. }
  18530. return left.transform(compressor);
  18531. };
  18532. var ret = [], prev = null;
  18533. statements.forEach(function(stat){
  18534. if (prev) {
  18535. if (stat instanceof AST_For) {
  18536. var opera = {};
  18537. try {
  18538. prev.body.walk(new TreeWalker(function(node){
  18539. if (node instanceof AST_Binary && node.operator == "in")
  18540. throw opera;
  18541. }));
  18542. if (stat.init && !(stat.init instanceof AST_Definitions)) {
  18543. stat.init = cons_seq(stat.init);
  18544. }
  18545. else if (!stat.init) {
  18546. stat.init = prev.body;
  18547. ret.pop();
  18548. }
  18549. } catch(ex) {
  18550. if (ex !== opera) throw ex;
  18551. }
  18552. }
  18553. else if (stat instanceof AST_If) {
  18554. stat.condition = cons_seq(stat.condition);
  18555. }
  18556. else if (stat instanceof AST_With) {
  18557. stat.expression = cons_seq(stat.expression);
  18558. }
  18559. else if (stat instanceof AST_Exit && stat.value) {
  18560. stat.value = cons_seq(stat.value);
  18561. }
  18562. else if (stat instanceof AST_Exit) {
  18563. stat.value = cons_seq(make_node(AST_Undefined, stat));
  18564. }
  18565. else if (stat instanceof AST_Switch) {
  18566. stat.expression = cons_seq(stat.expression);
  18567. }
  18568. }
  18569. ret.push(stat);
  18570. prev = stat instanceof AST_SimpleStatement ? stat : null;
  18571. });
  18572. return ret;
  18573. };
  18574. function join_consecutive_vars(statements, compressor) {
  18575. var prev = null;
  18576. return statements.reduce(function(a, stat){
  18577. if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
  18578. prev.definitions = prev.definitions.concat(stat.definitions);
  18579. CHANGED = true;
  18580. }
  18581. else if (stat instanceof AST_For
  18582. && prev instanceof AST_Definitions
  18583. && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  18584. CHANGED = true;
  18585. a.pop();
  18586. if (stat.init) {
  18587. stat.init.definitions = prev.definitions.concat(stat.init.definitions);
  18588. } else {
  18589. stat.init = prev;
  18590. }
  18591. a.push(stat);
  18592. prev = stat;
  18593. }
  18594. else {
  18595. prev = stat;
  18596. a.push(stat);
  18597. }
  18598. return a;
  18599. }, []);
  18600. };
  18601. function negate_iifes(statements, compressor) {
  18602. statements.forEach(function(stat){
  18603. if (stat instanceof AST_SimpleStatement) {
  18604. stat.body = (function transform(thing) {
  18605. return thing.transform(new TreeTransformer(function(node){
  18606. if (node instanceof AST_Call && node.expression instanceof AST_Function) {
  18607. return make_node(AST_UnaryPrefix, node, {
  18608. operator: "!",
  18609. expression: node
  18610. });
  18611. }
  18612. else if (node instanceof AST_Call) {
  18613. node.expression = transform(node.expression);
  18614. }
  18615. else if (node instanceof AST_Seq) {
  18616. node.car = transform(node.car);
  18617. }
  18618. else if (node instanceof AST_Conditional) {
  18619. var expr = transform(node.condition);
  18620. if (expr !== node.condition) {
  18621. // it has been negated, reverse
  18622. node.condition = expr;
  18623. var tmp = node.consequent;
  18624. node.consequent = node.alternative;
  18625. node.alternative = tmp;
  18626. }
  18627. }
  18628. return node;
  18629. }));
  18630. })(stat.body);
  18631. }
  18632. });
  18633. };
  18634. };
  18635. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  18636. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  18637. stat.walk(new TreeWalker(function(node){
  18638. if (node instanceof AST_Definitions) {
  18639. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  18640. node.remove_initializers();
  18641. target.push(node);
  18642. return true;
  18643. }
  18644. if (node instanceof AST_Defun) {
  18645. target.push(node);
  18646. return true;
  18647. }
  18648. if (node instanceof AST_Scope) {
  18649. return true;
  18650. }
  18651. }));
  18652. };
  18653. /* -----[ boolean/negation helpers ]----- */
  18654. // methods to determine whether an expression has a boolean result type
  18655. (function (def){
  18656. var unary_bool = [ "!", "delete" ];
  18657. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  18658. def(AST_Node, function(){ return false });
  18659. def(AST_UnaryPrefix, function(){
  18660. return member(this.operator, unary_bool);
  18661. });
  18662. def(AST_Binary, function(){
  18663. return member(this.operator, binary_bool) ||
  18664. ( (this.operator == "&&" || this.operator == "||") &&
  18665. this.left.is_boolean() && this.right.is_boolean() );
  18666. });
  18667. def(AST_Conditional, function(){
  18668. return this.consequent.is_boolean() && this.alternative.is_boolean();
  18669. });
  18670. def(AST_Assign, function(){
  18671. return this.operator == "=" && this.right.is_boolean();
  18672. });
  18673. def(AST_Seq, function(){
  18674. return this.cdr.is_boolean();
  18675. });
  18676. def(AST_True, function(){ return true });
  18677. def(AST_False, function(){ return true });
  18678. })(function(node, func){
  18679. node.DEFMETHOD("is_boolean", func);
  18680. });
  18681. // methods to determine if an expression has a string result type
  18682. (function (def){
  18683. def(AST_Node, function(){ return false });
  18684. def(AST_String, function(){ return true });
  18685. def(AST_UnaryPrefix, function(){
  18686. return this.operator == "typeof";
  18687. });
  18688. def(AST_Binary, function(compressor){
  18689. return this.operator == "+" &&
  18690. (this.left.is_string(compressor) || this.right.is_string(compressor));
  18691. });
  18692. def(AST_Assign, function(compressor){
  18693. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  18694. });
  18695. def(AST_Seq, function(compressor){
  18696. return this.cdr.is_string(compressor);
  18697. });
  18698. def(AST_Conditional, function(compressor){
  18699. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  18700. });
  18701. def(AST_Call, function(compressor){
  18702. return compressor.option("unsafe")
  18703. && this.expression instanceof AST_SymbolRef
  18704. && this.expression.name == "String"
  18705. && this.expression.undeclared();
  18706. });
  18707. })(function(node, func){
  18708. node.DEFMETHOD("is_string", func);
  18709. });
  18710. function best_of(ast1, ast2) {
  18711. return ast1.print_to_string().length >
  18712. ast2.print_to_string().length
  18713. ? ast2 : ast1;
  18714. };
  18715. // methods to evaluate a constant expression
  18716. (function (def){
  18717. // The evaluate method returns an array with one or two
  18718. // elements. If the node has been successfully reduced to a
  18719. // constant, then the second element tells us the value;
  18720. // otherwise the second element is missing. The first element
  18721. // of the array is always an AST_Node descendant; if
  18722. // evaluation was successful it's a node that represents the
  18723. // constant; otherwise it's the original or a replacement node.
  18724. AST_Node.DEFMETHOD("evaluate", function(compressor){
  18725. if (!compressor.option("evaluate")) return [ this ];
  18726. try {
  18727. var val = this._eval(compressor);
  18728. return [ best_of(make_node_from_constant(compressor, val, this), this), val ];
  18729. } catch(ex) {
  18730. if (ex !== def) throw ex;
  18731. return [ this ];
  18732. }
  18733. });
  18734. def(AST_Statement, function(){
  18735. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  18736. });
  18737. def(AST_Function, function(){
  18738. // XXX: AST_Function inherits from AST_Scope, which itself
  18739. // inherits from AST_Statement; however, an AST_Function
  18740. // isn't really a statement. This could byte in other
  18741. // places too. :-( Wish JS had multiple inheritance.
  18742. throw def;
  18743. });
  18744. function ev(node, compressor) {
  18745. if (!compressor) throw new Error("Compressor must be passed");
  18746. return node._eval(compressor);
  18747. };
  18748. def(AST_Node, function(){
  18749. throw def; // not constant
  18750. });
  18751. def(AST_Constant, function(){
  18752. return this.getValue();
  18753. });
  18754. def(AST_UnaryPrefix, function(compressor){
  18755. var e = this.expression;
  18756. switch (this.operator) {
  18757. case "!": return !ev(e, compressor);
  18758. case "typeof":
  18759. // Function would be evaluated to an array and so typeof would
  18760. // incorrectly return 'object'. Hence making is a special case.
  18761. if (e instanceof AST_Function) return typeof function(){};
  18762. e = ev(e, compressor);
  18763. // typeof <RegExp> returns "object" or "function" on different platforms
  18764. // so cannot evaluate reliably
  18765. if (e instanceof RegExp) throw def;
  18766. return typeof e;
  18767. case "void": return void ev(e, compressor);
  18768. case "~": return ~ev(e, compressor);
  18769. case "-":
  18770. e = ev(e, compressor);
  18771. if (e === 0) throw def;
  18772. return -e;
  18773. case "+": return +ev(e, compressor);
  18774. }
  18775. throw def;
  18776. });
  18777. def(AST_Binary, function(c){
  18778. var left = this.left, right = this.right;
  18779. switch (this.operator) {
  18780. case "&&" : return ev(left, c) && ev(right, c);
  18781. case "||" : return ev(left, c) || ev(right, c);
  18782. case "|" : return ev(left, c) | ev(right, c);
  18783. case "&" : return ev(left, c) & ev(right, c);
  18784. case "^" : return ev(left, c) ^ ev(right, c);
  18785. case "+" : return ev(left, c) + ev(right, c);
  18786. case "*" : return ev(left, c) * ev(right, c);
  18787. case "/" : return ev(left, c) / ev(right, c);
  18788. case "%" : return ev(left, c) % ev(right, c);
  18789. case "-" : return ev(left, c) - ev(right, c);
  18790. case "<<" : return ev(left, c) << ev(right, c);
  18791. case ">>" : return ev(left, c) >> ev(right, c);
  18792. case ">>>" : return ev(left, c) >>> ev(right, c);
  18793. case "==" : return ev(left, c) == ev(right, c);
  18794. case "===" : return ev(left, c) === ev(right, c);
  18795. case "!=" : return ev(left, c) != ev(right, c);
  18796. case "!==" : return ev(left, c) !== ev(right, c);
  18797. case "<" : return ev(left, c) < ev(right, c);
  18798. case "<=" : return ev(left, c) <= ev(right, c);
  18799. case ">" : return ev(left, c) > ev(right, c);
  18800. case ">=" : return ev(left, c) >= ev(right, c);
  18801. case "in" : return ev(left, c) in ev(right, c);
  18802. case "instanceof" : return ev(left, c) instanceof ev(right, c);
  18803. }
  18804. throw def;
  18805. });
  18806. def(AST_Conditional, function(compressor){
  18807. return ev(this.condition, compressor)
  18808. ? ev(this.consequent, compressor)
  18809. : ev(this.alternative, compressor);
  18810. });
  18811. def(AST_SymbolRef, function(compressor){
  18812. var d = this.definition();
  18813. if (d && d.constant && d.init) return ev(d.init, compressor);
  18814. throw def;
  18815. });
  18816. def(AST_Dot, function(compressor){
  18817. if (compressor.option("unsafe") && this.property == "length") {
  18818. var str = ev(this.expression, compressor);
  18819. if (typeof str == "string")
  18820. return str.length;
  18821. }
  18822. throw def;
  18823. });
  18824. })(function(node, func){
  18825. node.DEFMETHOD("_eval", func);
  18826. });
  18827. // method to negate an expression
  18828. (function(def){
  18829. function basic_negation(exp) {
  18830. return make_node(AST_UnaryPrefix, exp, {
  18831. operator: "!",
  18832. expression: exp
  18833. });
  18834. };
  18835. def(AST_Node, function(){
  18836. return basic_negation(this);
  18837. });
  18838. def(AST_Statement, function(){
  18839. throw new Error("Cannot negate a statement");
  18840. });
  18841. def(AST_Function, function(){
  18842. return basic_negation(this);
  18843. });
  18844. def(AST_UnaryPrefix, function(){
  18845. if (this.operator == "!")
  18846. return this.expression;
  18847. return basic_negation(this);
  18848. });
  18849. def(AST_Seq, function(compressor){
  18850. var self = this.clone();
  18851. self.cdr = self.cdr.negate(compressor);
  18852. return self;
  18853. });
  18854. def(AST_Conditional, function(compressor){
  18855. var self = this.clone();
  18856. self.consequent = self.consequent.negate(compressor);
  18857. self.alternative = self.alternative.negate(compressor);
  18858. return best_of(basic_negation(this), self);
  18859. });
  18860. def(AST_Binary, function(compressor){
  18861. var self = this.clone(), op = this.operator;
  18862. if (compressor.option("unsafe_comps")) {
  18863. switch (op) {
  18864. case "<=" : self.operator = ">" ; return self;
  18865. case "<" : self.operator = ">=" ; return self;
  18866. case ">=" : self.operator = "<" ; return self;
  18867. case ">" : self.operator = "<=" ; return self;
  18868. }
  18869. }
  18870. switch (op) {
  18871. case "==" : self.operator = "!="; return self;
  18872. case "!=" : self.operator = "=="; return self;
  18873. case "===": self.operator = "!=="; return self;
  18874. case "!==": self.operator = "==="; return self;
  18875. case "&&":
  18876. self.operator = "||";
  18877. self.left = self.left.negate(compressor);
  18878. self.right = self.right.negate(compressor);
  18879. return best_of(basic_negation(this), self);
  18880. case "||":
  18881. self.operator = "&&";
  18882. self.left = self.left.negate(compressor);
  18883. self.right = self.right.negate(compressor);
  18884. return best_of(basic_negation(this), self);
  18885. }
  18886. return basic_negation(this);
  18887. });
  18888. })(function(node, func){
  18889. node.DEFMETHOD("negate", function(compressor){
  18890. return func.call(this, compressor);
  18891. });
  18892. });
  18893. // determine if expression has side effects
  18894. (function(def){
  18895. def(AST_Node, function(compressor){ return true });
  18896. def(AST_EmptyStatement, function(compressor){ return false });
  18897. def(AST_Constant, function(compressor){ return false });
  18898. def(AST_This, function(compressor){ return false });
  18899. def(AST_Call, function(compressor){
  18900. var pure = compressor.option("pure_funcs");
  18901. if (!pure) return true;
  18902. return pure.indexOf(this.expression.print_to_string()) < 0;
  18903. });
  18904. def(AST_Block, function(compressor){
  18905. for (var i = this.body.length; --i >= 0;) {
  18906. if (this.body[i].has_side_effects(compressor))
  18907. return true;
  18908. }
  18909. return false;
  18910. });
  18911. def(AST_SimpleStatement, function(compressor){
  18912. return this.body.has_side_effects(compressor);
  18913. });
  18914. def(AST_Defun, function(compressor){ return true });
  18915. def(AST_Function, function(compressor){ return false });
  18916. def(AST_Binary, function(compressor){
  18917. return this.left.has_side_effects(compressor)
  18918. || this.right.has_side_effects(compressor);
  18919. });
  18920. def(AST_Assign, function(compressor){ return true });
  18921. def(AST_Conditional, function(compressor){
  18922. return this.condition.has_side_effects(compressor)
  18923. || this.consequent.has_side_effects(compressor)
  18924. || this.alternative.has_side_effects(compressor);
  18925. });
  18926. def(AST_Unary, function(compressor){
  18927. return this.operator == "delete"
  18928. || this.operator == "++"
  18929. || this.operator == "--"
  18930. || this.expression.has_side_effects(compressor);
  18931. });
  18932. def(AST_SymbolRef, function(compressor){
  18933. return this.global() && this.undeclared();
  18934. });
  18935. def(AST_Object, function(compressor){
  18936. for (var i = this.properties.length; --i >= 0;)
  18937. if (this.properties[i].has_side_effects(compressor))
  18938. return true;
  18939. return false;
  18940. });
  18941. def(AST_ObjectProperty, function(compressor){
  18942. return this.value.has_side_effects(compressor);
  18943. });
  18944. def(AST_Array, function(compressor){
  18945. for (var i = this.elements.length; --i >= 0;)
  18946. if (this.elements[i].has_side_effects(compressor))
  18947. return true;
  18948. return false;
  18949. });
  18950. def(AST_Dot, function(compressor){
  18951. if (!compressor.option("pure_getters")) return true;
  18952. return this.expression.has_side_effects(compressor);
  18953. });
  18954. def(AST_Sub, function(compressor){
  18955. if (!compressor.option("pure_getters")) return true;
  18956. return this.expression.has_side_effects(compressor)
  18957. || this.property.has_side_effects(compressor);
  18958. });
  18959. def(AST_PropAccess, function(compressor){
  18960. return !compressor.option("pure_getters");
  18961. });
  18962. def(AST_Seq, function(compressor){
  18963. return this.car.has_side_effects(compressor)
  18964. || this.cdr.has_side_effects(compressor);
  18965. });
  18966. })(function(node, func){
  18967. node.DEFMETHOD("has_side_effects", func);
  18968. });
  18969. // tell me if a statement aborts
  18970. function aborts(thing) {
  18971. return thing && thing.aborts();
  18972. };
  18973. (function(def){
  18974. def(AST_Statement, function(){ return null });
  18975. def(AST_Jump, function(){ return this });
  18976. function block_aborts(){
  18977. var n = this.body.length;
  18978. return n > 0 && aborts(this.body[n - 1]);
  18979. };
  18980. def(AST_BlockStatement, block_aborts);
  18981. def(AST_SwitchBranch, block_aborts);
  18982. def(AST_If, function(){
  18983. return this.alternative && aborts(this.body) && aborts(this.alternative);
  18984. });
  18985. })(function(node, func){
  18986. node.DEFMETHOD("aborts", func);
  18987. });
  18988. /* -----[ optimizers ]----- */
  18989. OPT(AST_Directive, function(self, compressor){
  18990. if (self.scope.has_directive(self.value) !== self.scope) {
  18991. return make_node(AST_EmptyStatement, self);
  18992. }
  18993. return self;
  18994. });
  18995. OPT(AST_Debugger, function(self, compressor){
  18996. if (compressor.option("drop_debugger"))
  18997. return make_node(AST_EmptyStatement, self);
  18998. return self;
  18999. });
  19000. OPT(AST_LabeledStatement, function(self, compressor){
  19001. if (self.body instanceof AST_Break
  19002. && compressor.loopcontrol_target(self.body.label) === self.body) {
  19003. return make_node(AST_EmptyStatement, self);
  19004. }
  19005. return self.label.references.length == 0 ? self.body : self;
  19006. });
  19007. OPT(AST_Block, function(self, compressor){
  19008. self.body = tighten_body(self.body, compressor);
  19009. return self;
  19010. });
  19011. OPT(AST_BlockStatement, function(self, compressor){
  19012. self.body = tighten_body(self.body, compressor);
  19013. switch (self.body.length) {
  19014. case 1: return self.body[0];
  19015. case 0: return make_node(AST_EmptyStatement, self);
  19016. }
  19017. return self;
  19018. });
  19019. AST_Scope.DEFMETHOD("drop_unused", function(compressor){
  19020. var self = this;
  19021. if (compressor.option("unused")
  19022. && !(self instanceof AST_Toplevel)
  19023. && !self.uses_eval
  19024. ) {
  19025. var in_use = [];
  19026. var initializations = new Dictionary();
  19027. // pass 1: find out which symbols are directly used in
  19028. // this scope (not in nested scopes).
  19029. var scope = this;
  19030. var tw = new TreeWalker(function(node, descend){
  19031. if (node !== self) {
  19032. if (node instanceof AST_Defun) {
  19033. initializations.add(node.name.name, node);
  19034. return true; // don't go in nested scopes
  19035. }
  19036. if (node instanceof AST_Definitions && scope === self) {
  19037. node.definitions.forEach(function(def){
  19038. if (def.value) {
  19039. initializations.add(def.name.name, def.value);
  19040. if (def.value.has_side_effects(compressor)) {
  19041. def.value.walk(tw);
  19042. }
  19043. }
  19044. });
  19045. return true;
  19046. }
  19047. if (node instanceof AST_SymbolRef) {
  19048. push_uniq(in_use, node.definition());
  19049. return true;
  19050. }
  19051. if (node instanceof AST_Scope) {
  19052. var save_scope = scope;
  19053. scope = node;
  19054. descend();
  19055. scope = save_scope;
  19056. return true;
  19057. }
  19058. }
  19059. });
  19060. self.walk(tw);
  19061. // pass 2: for every used symbol we need to walk its
  19062. // initialization code to figure out if it uses other
  19063. // symbols (that may not be in_use).
  19064. for (var i = 0; i < in_use.length; ++i) {
  19065. in_use[i].orig.forEach(function(decl){
  19066. // undeclared globals will be instanceof AST_SymbolRef
  19067. var init = initializations.get(decl.name);
  19068. if (init) init.forEach(function(init){
  19069. var tw = new TreeWalker(function(node){
  19070. if (node instanceof AST_SymbolRef) {
  19071. push_uniq(in_use, node.definition());
  19072. }
  19073. });
  19074. init.walk(tw);
  19075. });
  19076. });
  19077. }
  19078. // pass 3: we should drop declarations not in_use
  19079. var tt = new TreeTransformer(
  19080. function before(node, descend, in_list) {
  19081. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  19082. if (!compressor.option("keep_fargs")) {
  19083. for (var a = node.argnames, i = a.length; --i >= 0;) {
  19084. var sym = a[i];
  19085. if (sym.unreferenced()) {
  19086. a.pop();
  19087. compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", {
  19088. name : sym.name,
  19089. file : sym.start.file,
  19090. line : sym.start.line,
  19091. col : sym.start.col
  19092. });
  19093. }
  19094. else break;
  19095. }
  19096. }
  19097. }
  19098. if (node instanceof AST_Defun && node !== self) {
  19099. if (!member(node.name.definition(), in_use)) {
  19100. compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", {
  19101. name : node.name.name,
  19102. file : node.name.start.file,
  19103. line : node.name.start.line,
  19104. col : node.name.start.col
  19105. });
  19106. return make_node(AST_EmptyStatement, node);
  19107. }
  19108. return node;
  19109. }
  19110. if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {
  19111. var def = node.definitions.filter(function(def){
  19112. if (member(def.name.definition(), in_use)) return true;
  19113. var w = {
  19114. name : def.name.name,
  19115. file : def.name.start.file,
  19116. line : def.name.start.line,
  19117. col : def.name.start.col
  19118. };
  19119. if (def.value && def.value.has_side_effects(compressor)) {
  19120. def._unused_side_effects = true;
  19121. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
  19122. return true;
  19123. }
  19124. compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w);
  19125. return false;
  19126. });
  19127. // place uninitialized names at the start
  19128. def = mergeSort(def, function(a, b){
  19129. if (!a.value && b.value) return -1;
  19130. if (!b.value && a.value) return 1;
  19131. return 0;
  19132. });
  19133. // for unused names whose initialization has
  19134. // side effects, we can cascade the init. code
  19135. // into the next one, or next statement.
  19136. var side_effects = [];
  19137. for (var i = 0; i < def.length;) {
  19138. var x = def[i];
  19139. if (x._unused_side_effects) {
  19140. side_effects.push(x.value);
  19141. def.splice(i, 1);
  19142. } else {
  19143. if (side_effects.length > 0) {
  19144. side_effects.push(x.value);
  19145. x.value = AST_Seq.from_array(side_effects);
  19146. side_effects = [];
  19147. }
  19148. ++i;
  19149. }
  19150. }
  19151. if (side_effects.length > 0) {
  19152. side_effects = make_node(AST_BlockStatement, node, {
  19153. body: [ make_node(AST_SimpleStatement, node, {
  19154. body: AST_Seq.from_array(side_effects)
  19155. }) ]
  19156. });
  19157. } else {
  19158. side_effects = null;
  19159. }
  19160. if (def.length == 0 && !side_effects) {
  19161. return make_node(AST_EmptyStatement, node);
  19162. }
  19163. if (def.length == 0) {
  19164. return side_effects;
  19165. }
  19166. node.definitions = def;
  19167. if (side_effects) {
  19168. side_effects.body.unshift(node);
  19169. node = side_effects;
  19170. }
  19171. return node;
  19172. }
  19173. if (node instanceof AST_For) {
  19174. descend(node, this);
  19175. if (node.init instanceof AST_BlockStatement) {
  19176. // certain combination of unused name + side effect leads to:
  19177. // https://github.com/mishoo/UglifyJS2/issues/44
  19178. // that's an invalid AST.
  19179. // We fix it at this stage by moving the `var` outside the `for`.
  19180. var body = node.init.body.slice(0, -1);
  19181. node.init = node.init.body.slice(-1)[0].body;
  19182. body.push(node);
  19183. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  19184. body: body
  19185. });
  19186. }
  19187. }
  19188. if (node instanceof AST_Scope && node !== self)
  19189. return node;
  19190. }
  19191. );
  19192. self.transform(tt);
  19193. }
  19194. });
  19195. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
  19196. var hoist_funs = compressor.option("hoist_funs");
  19197. var hoist_vars = compressor.option("hoist_vars");
  19198. var self = this;
  19199. if (hoist_funs || hoist_vars) {
  19200. var dirs = [];
  19201. var hoisted = [];
  19202. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  19203. // let's count var_decl first, we seem to waste a lot of
  19204. // space if we hoist `var` when there's only one.
  19205. self.walk(new TreeWalker(function(node){
  19206. if (node instanceof AST_Scope && node !== self)
  19207. return true;
  19208. if (node instanceof AST_Var) {
  19209. ++var_decl;
  19210. return true;
  19211. }
  19212. }));
  19213. hoist_vars = hoist_vars && var_decl > 1;
  19214. var tt = new TreeTransformer(
  19215. function before(node) {
  19216. if (node !== self) {
  19217. if (node instanceof AST_Directive) {
  19218. dirs.push(node);
  19219. return make_node(AST_EmptyStatement, node);
  19220. }
  19221. if (node instanceof AST_Defun && hoist_funs) {
  19222. hoisted.push(node);
  19223. return make_node(AST_EmptyStatement, node);
  19224. }
  19225. if (node instanceof AST_Var && hoist_vars) {
  19226. node.definitions.forEach(function(def){
  19227. vars.set(def.name.name, def);
  19228. ++vars_found;
  19229. });
  19230. var seq = node.to_assignments();
  19231. var p = tt.parent();
  19232. if (p instanceof AST_ForIn && p.init === node) {
  19233. if (seq == null) return node.definitions[0].name;
  19234. return seq;
  19235. }
  19236. if (p instanceof AST_For && p.init === node) {
  19237. return seq;
  19238. }
  19239. if (!seq) return make_node(AST_EmptyStatement, node);
  19240. return make_node(AST_SimpleStatement, node, {
  19241. body: seq
  19242. });
  19243. }
  19244. if (node instanceof AST_Scope)
  19245. return node; // to avoid descending in nested scopes
  19246. }
  19247. }
  19248. );
  19249. self = self.transform(tt);
  19250. if (vars_found > 0) {
  19251. // collect only vars which don't show up in self's arguments list
  19252. var defs = [];
  19253. vars.each(function(def, name){
  19254. if (self instanceof AST_Lambda
  19255. && find_if(function(x){ return x.name == def.name.name },
  19256. self.argnames)) {
  19257. vars.del(name);
  19258. } else {
  19259. def = def.clone();
  19260. def.value = null;
  19261. defs.push(def);
  19262. vars.set(name, def);
  19263. }
  19264. });
  19265. if (defs.length > 0) {
  19266. // try to merge in assignments
  19267. for (var i = 0; i < self.body.length;) {
  19268. if (self.body[i] instanceof AST_SimpleStatement) {
  19269. var expr = self.body[i].body, sym, assign;
  19270. if (expr instanceof AST_Assign
  19271. && expr.operator == "="
  19272. && (sym = expr.left) instanceof AST_Symbol
  19273. && vars.has(sym.name))
  19274. {
  19275. var def = vars.get(sym.name);
  19276. if (def.value) break;
  19277. def.value = expr.right;
  19278. remove(defs, def);
  19279. defs.push(def);
  19280. self.body.splice(i, 1);
  19281. continue;
  19282. }
  19283. if (expr instanceof AST_Seq
  19284. && (assign = expr.car) instanceof AST_Assign
  19285. && assign.operator == "="
  19286. && (sym = assign.left) instanceof AST_Symbol
  19287. && vars.has(sym.name))
  19288. {
  19289. var def = vars.get(sym.name);
  19290. if (def.value) break;
  19291. def.value = assign.right;
  19292. remove(defs, def);
  19293. defs.push(def);
  19294. self.body[i].body = expr.cdr;
  19295. continue;
  19296. }
  19297. }
  19298. if (self.body[i] instanceof AST_EmptyStatement) {
  19299. self.body.splice(i, 1);
  19300. continue;
  19301. }
  19302. if (self.body[i] instanceof AST_BlockStatement) {
  19303. var tmp = [ i, 1 ].concat(self.body[i].body);
  19304. self.body.splice.apply(self.body, tmp);
  19305. continue;
  19306. }
  19307. break;
  19308. }
  19309. defs = make_node(AST_Var, self, {
  19310. definitions: defs
  19311. });
  19312. hoisted.push(defs);
  19313. };
  19314. }
  19315. self.body = dirs.concat(hoisted, self.body);
  19316. }
  19317. return self;
  19318. });
  19319. OPT(AST_SimpleStatement, function(self, compressor){
  19320. if (compressor.option("side_effects")) {
  19321. if (!self.body.has_side_effects(compressor)) {
  19322. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  19323. return make_node(AST_EmptyStatement, self);
  19324. }
  19325. }
  19326. return self;
  19327. });
  19328. OPT(AST_DWLoop, function(self, compressor){
  19329. var cond = self.condition.evaluate(compressor);
  19330. self.condition = cond[0];
  19331. if (!compressor.option("loops")) return self;
  19332. if (cond.length > 1) {
  19333. if (cond[1]) {
  19334. return make_node(AST_For, self, {
  19335. body: self.body
  19336. });
  19337. } else if (self instanceof AST_While) {
  19338. if (compressor.option("dead_code")) {
  19339. var a = [];
  19340. extract_declarations_from_unreachable_code(compressor, self.body, a);
  19341. return make_node(AST_BlockStatement, self, { body: a });
  19342. }
  19343. }
  19344. }
  19345. return self;
  19346. });
  19347. function if_break_in_loop(self, compressor) {
  19348. function drop_it(rest) {
  19349. rest = as_statement_array(rest);
  19350. if (self.body instanceof AST_BlockStatement) {
  19351. self.body = self.body.clone();
  19352. self.body.body = rest.concat(self.body.body.slice(1));
  19353. self.body = self.body.transform(compressor);
  19354. } else {
  19355. self.body = make_node(AST_BlockStatement, self.body, {
  19356. body: rest
  19357. }).transform(compressor);
  19358. }
  19359. if_break_in_loop(self, compressor);
  19360. }
  19361. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  19362. if (first instanceof AST_If) {
  19363. if (first.body instanceof AST_Break
  19364. && compressor.loopcontrol_target(first.body.label) === self) {
  19365. if (self.condition) {
  19366. self.condition = make_node(AST_Binary, self.condition, {
  19367. left: self.condition,
  19368. operator: "&&",
  19369. right: first.condition.negate(compressor),
  19370. });
  19371. } else {
  19372. self.condition = first.condition.negate(compressor);
  19373. }
  19374. drop_it(first.alternative);
  19375. }
  19376. else if (first.alternative instanceof AST_Break
  19377. && compressor.loopcontrol_target(first.alternative.label) === self) {
  19378. if (self.condition) {
  19379. self.condition = make_node(AST_Binary, self.condition, {
  19380. left: self.condition,
  19381. operator: "&&",
  19382. right: first.condition,
  19383. });
  19384. } else {
  19385. self.condition = first.condition;
  19386. }
  19387. drop_it(first.body);
  19388. }
  19389. }
  19390. };
  19391. OPT(AST_While, function(self, compressor) {
  19392. if (!compressor.option("loops")) return self;
  19393. self = AST_DWLoop.prototype.optimize.call(self, compressor);
  19394. if (self instanceof AST_While) {
  19395. if_break_in_loop(self, compressor);
  19396. self = make_node(AST_For, self, self).transform(compressor);
  19397. }
  19398. return self;
  19399. });
  19400. OPT(AST_For, function(self, compressor){
  19401. var cond = self.condition;
  19402. if (cond) {
  19403. cond = cond.evaluate(compressor);
  19404. self.condition = cond[0];
  19405. }
  19406. if (!compressor.option("loops")) return self;
  19407. if (cond) {
  19408. if (cond.length > 1 && !cond[1]) {
  19409. if (compressor.option("dead_code")) {
  19410. var a = [];
  19411. if (self.init instanceof AST_Statement) {
  19412. a.push(self.init);
  19413. }
  19414. else if (self.init) {
  19415. a.push(make_node(AST_SimpleStatement, self.init, {
  19416. body: self.init
  19417. }));
  19418. }
  19419. extract_declarations_from_unreachable_code(compressor, self.body, a);
  19420. return make_node(AST_BlockStatement, self, { body: a });
  19421. }
  19422. }
  19423. }
  19424. if_break_in_loop(self, compressor);
  19425. return self;
  19426. });
  19427. OPT(AST_If, function(self, compressor){
  19428. if (!compressor.option("conditionals")) return self;
  19429. // if condition can be statically determined, warn and drop
  19430. // one of the blocks. note, statically determined implies
  19431. // “has no side effects”; also it doesn't work for cases like
  19432. // `x && true`, though it probably should.
  19433. var cond = self.condition.evaluate(compressor);
  19434. self.condition = cond[0];
  19435. if (cond.length > 1) {
  19436. if (cond[1]) {
  19437. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  19438. if (compressor.option("dead_code")) {
  19439. var a = [];
  19440. if (self.alternative) {
  19441. extract_declarations_from_unreachable_code(compressor, self.alternative, a);
  19442. }
  19443. a.push(self.body);
  19444. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  19445. }
  19446. } else {
  19447. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  19448. if (compressor.option("dead_code")) {
  19449. var a = [];
  19450. extract_declarations_from_unreachable_code(compressor, self.body, a);
  19451. if (self.alternative) a.push(self.alternative);
  19452. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  19453. }
  19454. }
  19455. }
  19456. if (is_empty(self.alternative)) self.alternative = null;
  19457. var negated = self.condition.negate(compressor);
  19458. var negated_is_best = best_of(self.condition, negated) === negated;
  19459. if (self.alternative && negated_is_best) {
  19460. negated_is_best = false; // because we already do the switch here.
  19461. self.condition = negated;
  19462. var tmp = self.body;
  19463. self.body = self.alternative || make_node(AST_EmptyStatement);
  19464. self.alternative = tmp;
  19465. }
  19466. if (is_empty(self.body) && is_empty(self.alternative)) {
  19467. return make_node(AST_SimpleStatement, self.condition, {
  19468. body: self.condition
  19469. }).transform(compressor);
  19470. }
  19471. if (self.body instanceof AST_SimpleStatement
  19472. && self.alternative instanceof AST_SimpleStatement) {
  19473. return make_node(AST_SimpleStatement, self, {
  19474. body: make_node(AST_Conditional, self, {
  19475. condition : self.condition,
  19476. consequent : self.body.body,
  19477. alternative : self.alternative.body
  19478. })
  19479. }).transform(compressor);
  19480. }
  19481. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  19482. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  19483. body: make_node(AST_Binary, self, {
  19484. operator : "||",
  19485. left : negated,
  19486. right : self.body.body
  19487. })
  19488. }).transform(compressor);
  19489. return make_node(AST_SimpleStatement, self, {
  19490. body: make_node(AST_Binary, self, {
  19491. operator : "&&",
  19492. left : self.condition,
  19493. right : self.body.body
  19494. })
  19495. }).transform(compressor);
  19496. }
  19497. if (self.body instanceof AST_EmptyStatement
  19498. && self.alternative
  19499. && self.alternative instanceof AST_SimpleStatement) {
  19500. return make_node(AST_SimpleStatement, self, {
  19501. body: make_node(AST_Binary, self, {
  19502. operator : "||",
  19503. left : self.condition,
  19504. right : self.alternative.body
  19505. })
  19506. }).transform(compressor);
  19507. }
  19508. if (self.body instanceof AST_Exit
  19509. && self.alternative instanceof AST_Exit
  19510. && self.body.TYPE == self.alternative.TYPE) {
  19511. return make_node(self.body.CTOR, self, {
  19512. value: make_node(AST_Conditional, self, {
  19513. condition : self.condition,
  19514. consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),
  19515. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)
  19516. })
  19517. }).transform(compressor);
  19518. }
  19519. if (self.body instanceof AST_If
  19520. && !self.body.alternative
  19521. && !self.alternative) {
  19522. self.condition = make_node(AST_Binary, self.condition, {
  19523. operator: "&&",
  19524. left: self.condition,
  19525. right: self.body.condition
  19526. }).transform(compressor);
  19527. self.body = self.body.body;
  19528. }
  19529. if (aborts(self.body)) {
  19530. if (self.alternative) {
  19531. var alt = self.alternative;
  19532. self.alternative = null;
  19533. return make_node(AST_BlockStatement, self, {
  19534. body: [ self, alt ]
  19535. }).transform(compressor);
  19536. }
  19537. }
  19538. if (aborts(self.alternative)) {
  19539. var body = self.body;
  19540. self.body = self.alternative;
  19541. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  19542. self.alternative = null;
  19543. return make_node(AST_BlockStatement, self, {
  19544. body: [ self, body ]
  19545. }).transform(compressor);
  19546. }
  19547. return self;
  19548. });
  19549. OPT(AST_Switch, function(self, compressor){
  19550. if (self.body.length == 0 && compressor.option("conditionals")) {
  19551. return make_node(AST_SimpleStatement, self, {
  19552. body: self.expression
  19553. }).transform(compressor);
  19554. }
  19555. for(;;) {
  19556. var last_branch = self.body[self.body.length - 1];
  19557. if (last_branch) {
  19558. var stat = last_branch.body[last_branch.body.length - 1]; // last statement
  19559. if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self)
  19560. last_branch.body.pop();
  19561. if (last_branch instanceof AST_Default && last_branch.body.length == 0) {
  19562. self.body.pop();
  19563. continue;
  19564. }
  19565. }
  19566. break;
  19567. }
  19568. var exp = self.expression.evaluate(compressor);
  19569. out: if (exp.length == 2) try {
  19570. // constant expression
  19571. self.expression = exp[0];
  19572. if (!compressor.option("dead_code")) break out;
  19573. var value = exp[1];
  19574. var in_if = false;
  19575. var in_block = false;
  19576. var started = false;
  19577. var stopped = false;
  19578. var ruined = false;
  19579. var tt = new TreeTransformer(function(node, descend, in_list){
  19580. if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {
  19581. // no need to descend these node types
  19582. return node;
  19583. }
  19584. else if (node instanceof AST_Switch && node === self) {
  19585. node = node.clone();
  19586. descend(node, this);
  19587. return ruined ? node : make_node(AST_BlockStatement, node, {
  19588. body: node.body.reduce(function(a, branch){
  19589. return a.concat(branch.body);
  19590. }, [])
  19591. }).transform(compressor);
  19592. }
  19593. else if (node instanceof AST_If || node instanceof AST_Try) {
  19594. var save = in_if;
  19595. in_if = !in_block;
  19596. descend(node, this);
  19597. in_if = save;
  19598. return node;
  19599. }
  19600. else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {
  19601. var save = in_block;
  19602. in_block = true;
  19603. descend(node, this);
  19604. in_block = save;
  19605. return node;
  19606. }
  19607. else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {
  19608. if (in_if) {
  19609. ruined = true;
  19610. return node;
  19611. }
  19612. if (in_block) return node;
  19613. stopped = true;
  19614. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  19615. }
  19616. else if (node instanceof AST_SwitchBranch && this.parent() === self) {
  19617. if (stopped) return MAP.skip;
  19618. if (node instanceof AST_Case) {
  19619. var exp = node.expression.evaluate(compressor);
  19620. if (exp.length < 2) {
  19621. // got a case with non-constant expression, baling out
  19622. throw self;
  19623. }
  19624. if (exp[1] === value || started) {
  19625. started = true;
  19626. if (aborts(node)) stopped = true;
  19627. descend(node, this);
  19628. return node;
  19629. }
  19630. return MAP.skip;
  19631. }
  19632. descend(node, this);
  19633. return node;
  19634. }
  19635. });
  19636. tt.stack = compressor.stack.slice(); // so that's able to see parent nodes
  19637. self = self.transform(tt);
  19638. } catch(ex) {
  19639. if (ex !== self) throw ex;
  19640. }
  19641. return self;
  19642. });
  19643. OPT(AST_Case, function(self, compressor){
  19644. self.body = tighten_body(self.body, compressor);
  19645. return self;
  19646. });
  19647. OPT(AST_Try, function(self, compressor){
  19648. self.body = tighten_body(self.body, compressor);
  19649. return self;
  19650. });
  19651. AST_Definitions.DEFMETHOD("remove_initializers", function(){
  19652. this.definitions.forEach(function(def){ def.value = null });
  19653. });
  19654. AST_Definitions.DEFMETHOD("to_assignments", function(){
  19655. var assignments = this.definitions.reduce(function(a, def){
  19656. if (def.value) {
  19657. var name = make_node(AST_SymbolRef, def.name, def.name);
  19658. a.push(make_node(AST_Assign, def, {
  19659. operator : "=",
  19660. left : name,
  19661. right : def.value
  19662. }));
  19663. }
  19664. return a;
  19665. }, []);
  19666. if (assignments.length == 0) return null;
  19667. return AST_Seq.from_array(assignments);
  19668. });
  19669. OPT(AST_Definitions, function(self, compressor){
  19670. if (self.definitions.length == 0)
  19671. return make_node(AST_EmptyStatement, self);
  19672. return self;
  19673. });
  19674. OPT(AST_Function, function(self, compressor){
  19675. self = AST_Lambda.prototype.optimize.call(self, compressor);
  19676. if (compressor.option("unused")) {
  19677. if (self.name && self.name.unreferenced()) {
  19678. self.name = null;
  19679. }
  19680. }
  19681. return self;
  19682. });
  19683. OPT(AST_Call, function(self, compressor){
  19684. if (compressor.option("unsafe")) {
  19685. var exp = self.expression;
  19686. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  19687. switch (exp.name) {
  19688. case "Array":
  19689. if (self.args.length != 1) {
  19690. return make_node(AST_Array, self, {
  19691. elements: self.args
  19692. }).transform(compressor);
  19693. }
  19694. break;
  19695. case "Object":
  19696. if (self.args.length == 0) {
  19697. return make_node(AST_Object, self, {
  19698. properties: []
  19699. });
  19700. }
  19701. break;
  19702. case "String":
  19703. if (self.args.length == 0) return make_node(AST_String, self, {
  19704. value: ""
  19705. });
  19706. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  19707. left: self.args[0],
  19708. operator: "+",
  19709. right: make_node(AST_String, self, { value: "" })
  19710. }).transform(compressor);
  19711. break;
  19712. case "Number":
  19713. if (self.args.length == 0) return make_node(AST_Number, self, {
  19714. value: 0
  19715. });
  19716. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  19717. expression: self.args[0],
  19718. operator: "+"
  19719. }).transform(compressor);
  19720. case "Boolean":
  19721. if (self.args.length == 0) return make_node(AST_False, self);
  19722. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  19723. expression: make_node(AST_UnaryPrefix, null, {
  19724. expression: self.args[0],
  19725. operator: "!"
  19726. }),
  19727. operator: "!"
  19728. }).transform(compressor);
  19729. break;
  19730. case "Function":
  19731. if (all(self.args, function(x){ return x instanceof AST_String })) {
  19732. // quite a corner-case, but we can handle it:
  19733. // https://github.com/mishoo/UglifyJS2/issues/203
  19734. // if the code argument is a constant, then we can minify it.
  19735. try {
  19736. var code = "(function(" + self.args.slice(0, -1).map(function(arg){
  19737. return arg.value;
  19738. }).join(",") + "){" + self.args[self.args.length - 1].value + "})()";
  19739. var ast = parse(code);
  19740. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  19741. var comp = new Compressor(compressor.options);
  19742. ast = ast.transform(comp);
  19743. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  19744. ast.mangle_names();
  19745. var fun;
  19746. try {
  19747. ast.walk(new TreeWalker(function(node){
  19748. if (node instanceof AST_Lambda) {
  19749. fun = node;
  19750. throw ast;
  19751. }
  19752. }));
  19753. } catch(ex) {
  19754. if (ex !== ast) throw ex;
  19755. };
  19756. if (!fun) return self;
  19757. var args = fun.argnames.map(function(arg, i){
  19758. return make_node(AST_String, self.args[i], {
  19759. value: arg.print_to_string()
  19760. });
  19761. });
  19762. var code = OutputStream();
  19763. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  19764. code = code.toString().replace(/^\{|\}$/g, "");
  19765. args.push(make_node(AST_String, self.args[self.args.length - 1], {
  19766. value: code
  19767. }));
  19768. self.args = args;
  19769. return self;
  19770. } catch(ex) {
  19771. if (ex instanceof JS_Parse_Error) {
  19772. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  19773. compressor.warn(ex.toString());
  19774. } else {
  19775. console.log(ex);
  19776. throw ex;
  19777. }
  19778. }
  19779. }
  19780. break;
  19781. }
  19782. }
  19783. else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
  19784. return make_node(AST_Binary, self, {
  19785. left: make_node(AST_String, self, { value: "" }),
  19786. operator: "+",
  19787. right: exp.expression
  19788. }).transform(compressor);
  19789. }
  19790. else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: {
  19791. var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1];
  19792. if (separator == null) break EXIT; // not a constant
  19793. var elements = exp.expression.elements.reduce(function(a, el){
  19794. el = el.evaluate(compressor);
  19795. if (a.length == 0 || el.length == 1) {
  19796. a.push(el);
  19797. } else {
  19798. var last = a[a.length - 1];
  19799. if (last.length == 2) {
  19800. // it's a constant
  19801. var val = "" + last[1] + separator + el[1];
  19802. a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ];
  19803. } else {
  19804. a.push(el);
  19805. }
  19806. }
  19807. return a;
  19808. }, []);
  19809. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  19810. if (elements.length == 1) return elements[0][0];
  19811. if (separator == "") {
  19812. var first;
  19813. if (elements[0][0] instanceof AST_String
  19814. || elements[1][0] instanceof AST_String) {
  19815. first = elements.shift()[0];
  19816. } else {
  19817. first = make_node(AST_String, self, { value: "" });
  19818. }
  19819. return elements.reduce(function(prev, el){
  19820. return make_node(AST_Binary, el[0], {
  19821. operator : "+",
  19822. left : prev,
  19823. right : el[0],
  19824. });
  19825. }, first).transform(compressor);
  19826. }
  19827. // need this awkward cloning to not affect original element
  19828. // best_of will decide which one to get through.
  19829. var node = self.clone();
  19830. node.expression = node.expression.clone();
  19831. node.expression.expression = node.expression.expression.clone();
  19832. node.expression.expression.elements = elements.map(function(el){
  19833. return el[0];
  19834. });
  19835. return best_of(self, node);
  19836. }
  19837. }
  19838. if (compressor.option("side_effects")) {
  19839. if (self.expression instanceof AST_Function
  19840. && self.args.length == 0
  19841. && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) {
  19842. return make_node(AST_Undefined, self).transform(compressor);
  19843. }
  19844. }
  19845. if (compressor.option("drop_console")) {
  19846. if (self.expression instanceof AST_PropAccess &&
  19847. self.expression.expression instanceof AST_SymbolRef &&
  19848. self.expression.expression.name == "console" &&
  19849. self.expression.expression.undeclared()) {
  19850. return make_node(AST_Undefined, self).transform(compressor);
  19851. }
  19852. }
  19853. return self.evaluate(compressor)[0];
  19854. });
  19855. OPT(AST_New, function(self, compressor){
  19856. if (compressor.option("unsafe")) {
  19857. var exp = self.expression;
  19858. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  19859. switch (exp.name) {
  19860. case "Object":
  19861. case "RegExp":
  19862. case "Function":
  19863. case "Error":
  19864. case "Array":
  19865. return make_node(AST_Call, self, self).transform(compressor);
  19866. }
  19867. }
  19868. }
  19869. return self;
  19870. });
  19871. OPT(AST_Seq, function(self, compressor){
  19872. if (!compressor.option("side_effects"))
  19873. return self;
  19874. if (!self.car.has_side_effects(compressor)) {
  19875. // we shouldn't compress (1,eval)(something) to
  19876. // eval(something) because that changes the meaning of
  19877. // eval (becomes lexical instead of global).
  19878. var p;
  19879. if (!(self.cdr instanceof AST_SymbolRef
  19880. && self.cdr.name == "eval"
  19881. && self.cdr.undeclared()
  19882. && (p = compressor.parent()) instanceof AST_Call
  19883. && p.expression === self)) {
  19884. return self.cdr;
  19885. }
  19886. }
  19887. if (compressor.option("cascade")) {
  19888. if (self.car instanceof AST_Assign
  19889. && !self.car.left.has_side_effects(compressor)) {
  19890. if (self.car.left.equivalent_to(self.cdr)) {
  19891. return self.car;
  19892. }
  19893. if (self.cdr instanceof AST_Call
  19894. && self.cdr.expression.equivalent_to(self.car.left)) {
  19895. self.cdr.expression = self.car;
  19896. return self.cdr;
  19897. }
  19898. }
  19899. if (!self.car.has_side_effects(compressor)
  19900. && !self.cdr.has_side_effects(compressor)
  19901. && self.car.equivalent_to(self.cdr)) {
  19902. return self.car;
  19903. }
  19904. }
  19905. if (self.cdr instanceof AST_UnaryPrefix
  19906. && self.cdr.operator == "void"
  19907. && !self.cdr.expression.has_side_effects(compressor)) {
  19908. self.cdr.operator = self.car;
  19909. return self.cdr;
  19910. }
  19911. if (self.cdr instanceof AST_Undefined) {
  19912. return make_node(AST_UnaryPrefix, self, {
  19913. operator : "void",
  19914. expression : self.car
  19915. });
  19916. }
  19917. return self;
  19918. });
  19919. AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
  19920. if (compressor.option("sequences")) {
  19921. if (this.expression instanceof AST_Seq) {
  19922. var seq = this.expression;
  19923. var x = seq.to_array();
  19924. this.expression = x.pop();
  19925. x.push(this);
  19926. seq = AST_Seq.from_array(x).transform(compressor);
  19927. return seq;
  19928. }
  19929. }
  19930. return this;
  19931. });
  19932. OPT(AST_UnaryPostfix, function(self, compressor){
  19933. return self.lift_sequences(compressor);
  19934. });
  19935. OPT(AST_UnaryPrefix, function(self, compressor){
  19936. self = self.lift_sequences(compressor);
  19937. var e = self.expression;
  19938. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  19939. switch (self.operator) {
  19940. case "!":
  19941. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  19942. // !!foo ==> foo, if we're in boolean context
  19943. return e.expression;
  19944. }
  19945. break;
  19946. case "typeof":
  19947. // typeof always returns a non-empty string, thus it's
  19948. // always true in booleans
  19949. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  19950. return make_node(AST_True, self);
  19951. }
  19952. if (e instanceof AST_Binary && self.operator == "!") {
  19953. self = best_of(self, e.negate(compressor));
  19954. }
  19955. }
  19956. return self.evaluate(compressor)[0];
  19957. });
  19958. function has_side_effects_or_prop_access(node, compressor) {
  19959. var save_pure_getters = compressor.option("pure_getters");
  19960. compressor.options.pure_getters = false;
  19961. var ret = node.has_side_effects(compressor);
  19962. compressor.options.pure_getters = save_pure_getters;
  19963. return ret;
  19964. }
  19965. AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
  19966. if (compressor.option("sequences")) {
  19967. if (this.left instanceof AST_Seq) {
  19968. var seq = this.left;
  19969. var x = seq.to_array();
  19970. this.left = x.pop();
  19971. x.push(this);
  19972. seq = AST_Seq.from_array(x).transform(compressor);
  19973. return seq;
  19974. }
  19975. if (this.right instanceof AST_Seq
  19976. && this instanceof AST_Assign
  19977. && !has_side_effects_or_prop_access(this.left, compressor)) {
  19978. var seq = this.right;
  19979. var x = seq.to_array();
  19980. this.right = x.pop();
  19981. x.push(this);
  19982. seq = AST_Seq.from_array(x).transform(compressor);
  19983. return seq;
  19984. }
  19985. }
  19986. return this;
  19987. });
  19988. var commutativeOperators = makePredicate("== === != !== * & | ^");
  19989. OPT(AST_Binary, function(self, compressor){
  19990. var reverse = compressor.has_directive("use asm") ? noop
  19991. : function(op, force) {
  19992. if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {
  19993. if (op) self.operator = op;
  19994. var tmp = self.left;
  19995. self.left = self.right;
  19996. self.right = tmp;
  19997. }
  19998. };
  19999. if (commutativeOperators(self.operator)) {
  20000. if (self.right instanceof AST_Constant
  20001. && !(self.left instanceof AST_Constant)) {
  20002. // if right is a constant, whatever side effects the
  20003. // left side might have could not influence the
  20004. // result. hence, force switch.
  20005. if (!(self.left instanceof AST_Binary
  20006. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  20007. reverse(null, true);
  20008. }
  20009. }
  20010. if (/^[!=]==?$/.test(self.operator)) {
  20011. if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) {
  20012. if (self.right.consequent instanceof AST_SymbolRef
  20013. && self.right.consequent.definition() === self.left.definition()) {
  20014. if (/^==/.test(self.operator)) return self.right.condition;
  20015. if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor);
  20016. }
  20017. if (self.right.alternative instanceof AST_SymbolRef
  20018. && self.right.alternative.definition() === self.left.definition()) {
  20019. if (/^==/.test(self.operator)) return self.right.condition.negate(compressor);
  20020. if (/^!=/.test(self.operator)) return self.right.condition;
  20021. }
  20022. }
  20023. if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) {
  20024. if (self.left.consequent instanceof AST_SymbolRef
  20025. && self.left.consequent.definition() === self.right.definition()) {
  20026. if (/^==/.test(self.operator)) return self.left.condition;
  20027. if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor);
  20028. }
  20029. if (self.left.alternative instanceof AST_SymbolRef
  20030. && self.left.alternative.definition() === self.right.definition()) {
  20031. if (/^==/.test(self.operator)) return self.left.condition.negate(compressor);
  20032. if (/^!=/.test(self.operator)) return self.left.condition;
  20033. }
  20034. }
  20035. }
  20036. }
  20037. self = self.lift_sequences(compressor);
  20038. if (compressor.option("comparisons")) switch (self.operator) {
  20039. case "===":
  20040. case "!==":
  20041. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  20042. (self.left.is_boolean() && self.right.is_boolean())) {
  20043. self.operator = self.operator.substr(0, 2);
  20044. }
  20045. // XXX: intentionally falling down to the next case
  20046. case "==":
  20047. case "!=":
  20048. if (self.left instanceof AST_String
  20049. && self.left.value == "undefined"
  20050. && self.right instanceof AST_UnaryPrefix
  20051. && self.right.operator == "typeof"
  20052. && compressor.option("unsafe")) {
  20053. if (!(self.right.expression instanceof AST_SymbolRef)
  20054. || !self.right.expression.undeclared()) {
  20055. self.right = self.right.expression;
  20056. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  20057. if (self.operator.length == 2) self.operator += "=";
  20058. }
  20059. }
  20060. break;
  20061. }
  20062. if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
  20063. case "&&":
  20064. var ll = self.left.evaluate(compressor);
  20065. var rr = self.right.evaluate(compressor);
  20066. if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) {
  20067. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  20068. return make_node(AST_False, self);
  20069. }
  20070. if (ll.length > 1 && ll[1]) {
  20071. return rr[0];
  20072. }
  20073. if (rr.length > 1 && rr[1]) {
  20074. return ll[0];
  20075. }
  20076. break;
  20077. case "||":
  20078. var ll = self.left.evaluate(compressor);
  20079. var rr = self.right.evaluate(compressor);
  20080. if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) {
  20081. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  20082. return make_node(AST_True, self);
  20083. }
  20084. if (ll.length > 1 && !ll[1]) {
  20085. return rr[0];
  20086. }
  20087. if (rr.length > 1 && !rr[1]) {
  20088. return ll[0];
  20089. }
  20090. break;
  20091. case "+":
  20092. var ll = self.left.evaluate(compressor);
  20093. var rr = self.right.evaluate(compressor);
  20094. if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) ||
  20095. (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) {
  20096. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  20097. return make_node(AST_True, self);
  20098. }
  20099. break;
  20100. }
  20101. if (compressor.option("comparisons")) {
  20102. if (!(compressor.parent() instanceof AST_Binary)
  20103. || compressor.parent() instanceof AST_Assign) {
  20104. var negated = make_node(AST_UnaryPrefix, self, {
  20105. operator: "!",
  20106. expression: self.negate(compressor)
  20107. });
  20108. self = best_of(self, negated);
  20109. }
  20110. switch (self.operator) {
  20111. case "<": reverse(">"); break;
  20112. case "<=": reverse(">="); break;
  20113. }
  20114. }
  20115. if (self.operator == "+" && self.right instanceof AST_String
  20116. && self.right.getValue() === "" && self.left instanceof AST_Binary
  20117. && self.left.operator == "+" && self.left.is_string(compressor)) {
  20118. return self.left;
  20119. }
  20120. if (compressor.option("evaluate")) {
  20121. if (self.operator == "+") {
  20122. if (self.left instanceof AST_Constant
  20123. && self.right instanceof AST_Binary
  20124. && self.right.operator == "+"
  20125. && self.right.left instanceof AST_Constant
  20126. && self.right.is_string(compressor)) {
  20127. self = make_node(AST_Binary, self, {
  20128. operator: "+",
  20129. left: make_node(AST_String, null, {
  20130. value: "" + self.left.getValue() + self.right.left.getValue(),
  20131. start: self.left.start,
  20132. end: self.right.left.end
  20133. }),
  20134. right: self.right.right
  20135. });
  20136. }
  20137. if (self.right instanceof AST_Constant
  20138. && self.left instanceof AST_Binary
  20139. && self.left.operator == "+"
  20140. && self.left.right instanceof AST_Constant
  20141. && self.left.is_string(compressor)) {
  20142. self = make_node(AST_Binary, self, {
  20143. operator: "+",
  20144. left: self.left.left,
  20145. right: make_node(AST_String, null, {
  20146. value: "" + self.left.right.getValue() + self.right.getValue(),
  20147. start: self.left.right.start,
  20148. end: self.right.end
  20149. })
  20150. });
  20151. }
  20152. if (self.left instanceof AST_Binary
  20153. && self.left.operator == "+"
  20154. && self.left.is_string(compressor)
  20155. && self.left.right instanceof AST_Constant
  20156. && self.right instanceof AST_Binary
  20157. && self.right.operator == "+"
  20158. && self.right.left instanceof AST_Constant
  20159. && self.right.is_string(compressor)) {
  20160. self = make_node(AST_Binary, self, {
  20161. operator: "+",
  20162. left: make_node(AST_Binary, self.left, {
  20163. operator: "+",
  20164. left: self.left.left,
  20165. right: make_node(AST_String, null, {
  20166. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  20167. start: self.left.right.start,
  20168. end: self.right.left.end
  20169. })
  20170. }),
  20171. right: self.right.right
  20172. });
  20173. }
  20174. }
  20175. }
  20176. // x * (y * z) ==> x * y * z
  20177. if (self.right instanceof AST_Binary
  20178. && self.right.operator == self.operator
  20179. && (self.operator == "*" || self.operator == "&&" || self.operator == "||"))
  20180. {
  20181. self.left = make_node(AST_Binary, self.left, {
  20182. operator : self.operator,
  20183. left : self.left,
  20184. right : self.right.left
  20185. });
  20186. self.right = self.right.right;
  20187. return self.transform(compressor);
  20188. }
  20189. return self.evaluate(compressor)[0];
  20190. });
  20191. OPT(AST_SymbolRef, function(self, compressor){
  20192. if (self.undeclared()) {
  20193. var defines = compressor.option("global_defs");
  20194. if (defines && defines.hasOwnProperty(self.name)) {
  20195. return make_node_from_constant(compressor, defines[self.name], self);
  20196. }
  20197. switch (self.name) {
  20198. case "undefined":
  20199. return make_node(AST_Undefined, self);
  20200. case "NaN":
  20201. return make_node(AST_NaN, self);
  20202. case "Infinity":
  20203. return make_node(AST_Infinity, self);
  20204. }
  20205. }
  20206. return self;
  20207. });
  20208. OPT(AST_Undefined, function(self, compressor){
  20209. if (compressor.option("unsafe")) {
  20210. var scope = compressor.find_parent(AST_Scope);
  20211. var undef = scope.find_variable("undefined");
  20212. if (undef) {
  20213. var ref = make_node(AST_SymbolRef, self, {
  20214. name : "undefined",
  20215. scope : scope,
  20216. thedef : undef
  20217. });
  20218. ref.reference();
  20219. return ref;
  20220. }
  20221. }
  20222. return self;
  20223. });
  20224. var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  20225. OPT(AST_Assign, function(self, compressor){
  20226. self = self.lift_sequences(compressor);
  20227. if (self.operator == "="
  20228. && self.left instanceof AST_SymbolRef
  20229. && self.right instanceof AST_Binary
  20230. && self.right.left instanceof AST_SymbolRef
  20231. && self.right.left.name == self.left.name
  20232. && member(self.right.operator, ASSIGN_OPS)) {
  20233. self.operator = self.right.operator + "=";
  20234. self.right = self.right.right;
  20235. }
  20236. return self;
  20237. });
  20238. OPT(AST_Conditional, function(self, compressor){
  20239. if (!compressor.option("conditionals")) return self;
  20240. if (self.condition instanceof AST_Seq) {
  20241. var car = self.condition.car;
  20242. self.condition = self.condition.cdr;
  20243. return AST_Seq.cons(car, self);
  20244. }
  20245. var cond = self.condition.evaluate(compressor);
  20246. if (cond.length > 1) {
  20247. if (cond[1]) {
  20248. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  20249. return self.consequent;
  20250. } else {
  20251. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  20252. return self.alternative;
  20253. }
  20254. }
  20255. var negated = cond[0].negate(compressor);
  20256. if (best_of(cond[0], negated) === negated) {
  20257. self = make_node(AST_Conditional, self, {
  20258. condition: negated,
  20259. consequent: self.alternative,
  20260. alternative: self.consequent
  20261. });
  20262. }
  20263. var consequent = self.consequent;
  20264. var alternative = self.alternative;
  20265. if (consequent instanceof AST_Assign
  20266. && alternative instanceof AST_Assign
  20267. && consequent.operator == alternative.operator
  20268. && consequent.left.equivalent_to(alternative.left)
  20269. ) {
  20270. /*
  20271. * Stuff like this:
  20272. * if (foo) exp = something; else exp = something_else;
  20273. * ==>
  20274. * exp = foo ? something : something_else;
  20275. */
  20276. return make_node(AST_Assign, self, {
  20277. operator: consequent.operator,
  20278. left: consequent.left,
  20279. right: make_node(AST_Conditional, self, {
  20280. condition: self.condition,
  20281. consequent: consequent.right,
  20282. alternative: alternative.right
  20283. })
  20284. });
  20285. }
  20286. if (consequent instanceof AST_Call
  20287. && alternative.TYPE === consequent.TYPE
  20288. && consequent.args.length == alternative.args.length
  20289. && consequent.expression.equivalent_to(alternative.expression)) {
  20290. if (consequent.args.length == 0) {
  20291. return make_node(AST_Seq, self, {
  20292. car: self.condition,
  20293. cdr: consequent
  20294. });
  20295. }
  20296. if (consequent.args.length == 1) {
  20297. consequent.args[0] = make_node(AST_Conditional, self, {
  20298. condition: self.condition,
  20299. consequent: consequent.args[0],
  20300. alternative: alternative.args[0]
  20301. });
  20302. return consequent;
  20303. }
  20304. }
  20305. // x?y?z:a:a --> x&&y?z:a
  20306. if (consequent instanceof AST_Conditional
  20307. && consequent.alternative.equivalent_to(alternative)) {
  20308. return make_node(AST_Conditional, self, {
  20309. condition: make_node(AST_Binary, self, {
  20310. left: self.condition,
  20311. operator: "&&",
  20312. right: consequent.condition
  20313. }),
  20314. consequent: consequent.consequent,
  20315. alternative: alternative
  20316. });
  20317. }
  20318. // x=y?1:1 --> x=1
  20319. if (consequent instanceof AST_Constant
  20320. && alternative instanceof AST_Constant
  20321. && consequent.equivalent_to(alternative)) {
  20322. if (self.condition.has_side_effects(compressor)) {
  20323. return AST_Seq.from_array([self.condition, make_node_from_constant(compressor, consequent.value, self)]);
  20324. } else {
  20325. return make_node_from_constant(compressor, consequent.value, self);
  20326. }
  20327. }
  20328. return self;
  20329. });
  20330. OPT(AST_Boolean, function(self, compressor){
  20331. if (compressor.option("booleans")) {
  20332. var p = compressor.parent();
  20333. if (p instanceof AST_Binary && (p.operator == "=="
  20334. || p.operator == "!=")) {
  20335. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  20336. operator : p.operator,
  20337. value : self.value,
  20338. file : p.start.file,
  20339. line : p.start.line,
  20340. col : p.start.col,
  20341. });
  20342. return make_node(AST_Number, self, {
  20343. value: +self.value
  20344. });
  20345. }
  20346. return make_node(AST_UnaryPrefix, self, {
  20347. operator: "!",
  20348. expression: make_node(AST_Number, self, {
  20349. value: 1 - self.value
  20350. })
  20351. });
  20352. }
  20353. return self;
  20354. });
  20355. OPT(AST_Sub, function(self, compressor){
  20356. var prop = self.property;
  20357. if (prop instanceof AST_String && compressor.option("properties")) {
  20358. prop = prop.getValue();
  20359. if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) {
  20360. return make_node(AST_Dot, self, {
  20361. expression : self.expression,
  20362. property : prop
  20363. }).optimize(compressor);
  20364. }
  20365. var v = parseFloat(prop);
  20366. if (!isNaN(v) && v.toString() == prop) {
  20367. self.property = make_node(AST_Number, self.property, {
  20368. value: v
  20369. });
  20370. }
  20371. }
  20372. return self;
  20373. });
  20374. OPT(AST_Dot, function(self, compressor){
  20375. var prop = self.property;
  20376. if (RESERVED_WORDS(prop) && !compressor.option("screw_ie8")) {
  20377. return make_node(AST_Sub, self, {
  20378. expression : self.expression,
  20379. property : make_node(AST_String, self, {
  20380. value: prop
  20381. })
  20382. }).optimize(compressor);
  20383. }
  20384. return self.evaluate(compressor)[0];
  20385. });
  20386. function literals_in_boolean_context(self, compressor) {
  20387. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  20388. return make_node(AST_True, self);
  20389. }
  20390. return self;
  20391. };
  20392. OPT(AST_Array, literals_in_boolean_context);
  20393. OPT(AST_Object, literals_in_boolean_context);
  20394. OPT(AST_RegExp, literals_in_boolean_context);
  20395. })();
  20396. /***********************************************************************
  20397. A JavaScript tokenizer / parser / beautifier / compressor.
  20398. https://github.com/mishoo/UglifyJS2
  20399. -------------------------------- (C) ---------------------------------
  20400. Author: Mihai Bazon
  20401. <mihai.bazon@gmail.com>
  20402. http://mihai.bazon.net/blog
  20403. Distributed under the BSD license:
  20404. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  20405. Redistribution and use in source and binary forms, with or without
  20406. modification, are permitted provided that the following conditions
  20407. are met:
  20408. * Redistributions of source code must retain the above
  20409. copyright notice, this list of conditions and the following
  20410. disclaimer.
  20411. * Redistributions in binary form must reproduce the above
  20412. copyright notice, this list of conditions and the following
  20413. disclaimer in the documentation and/or other materials
  20414. provided with the distribution.
  20415. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  20416. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20417. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  20418. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  20419. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  20420. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  20421. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  20422. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  20423. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  20424. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  20425. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  20426. SUCH DAMAGE.
  20427. ***********************************************************************/
  20428. "use strict";
  20429. // a small wrapper around fitzgen's source-map library
  20430. function SourceMap(options) {
  20431. options = defaults(options, {
  20432. file : null,
  20433. root : null,
  20434. orig : null,
  20435. orig_line_diff : 0,
  20436. dest_line_diff : 0,
  20437. });
  20438. var generator = new MOZ_SourceMap.SourceMapGenerator({
  20439. file : options.file,
  20440. sourceRoot : options.root
  20441. });
  20442. var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
  20443. function add(source, gen_line, gen_col, orig_line, orig_col, name) {
  20444. if (orig_map) {
  20445. var info = orig_map.originalPositionFor({
  20446. line: orig_line,
  20447. column: orig_col
  20448. });
  20449. if (info.source === null) {
  20450. return;
  20451. }
  20452. source = info.source;
  20453. orig_line = info.line;
  20454. orig_col = info.column;
  20455. name = info.name || name;
  20456. }
  20457. generator.addMapping({
  20458. generated : { line: gen_line + options.dest_line_diff, column: gen_col },
  20459. original : { line: orig_line + options.orig_line_diff, column: orig_col },
  20460. source : source,
  20461. name : name
  20462. });
  20463. };
  20464. return {
  20465. add : add,
  20466. get : function() { return generator },
  20467. toString : function() { return generator.toString() }
  20468. };
  20469. };
  20470. /***********************************************************************
  20471. A JavaScript tokenizer / parser / beautifier / compressor.
  20472. https://github.com/mishoo/UglifyJS2
  20473. -------------------------------- (C) ---------------------------------
  20474. Author: Mihai Bazon
  20475. <mihai.bazon@gmail.com>
  20476. http://mihai.bazon.net/blog
  20477. Distributed under the BSD license:
  20478. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  20479. Redistribution and use in source and binary forms, with or without
  20480. modification, are permitted provided that the following conditions
  20481. are met:
  20482. * Redistributions of source code must retain the above
  20483. copyright notice, this list of conditions and the following
  20484. disclaimer.
  20485. * Redistributions in binary form must reproduce the above
  20486. copyright notice, this list of conditions and the following
  20487. disclaimer in the documentation and/or other materials
  20488. provided with the distribution.
  20489. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  20490. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20491. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  20492. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  20493. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  20494. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  20495. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  20496. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  20497. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  20498. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  20499. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  20500. SUCH DAMAGE.
  20501. ***********************************************************************/
  20502. "use strict";
  20503. (function(){
  20504. var MOZ_TO_ME = {
  20505. ExpressionStatement: function(M) {
  20506. var expr = M.expression;
  20507. if (expr.type === "Literal" && typeof expr.value === "string") {
  20508. return new AST_Directive({
  20509. start: my_start_token(M),
  20510. end: my_end_token(M),
  20511. value: expr.value
  20512. });
  20513. }
  20514. return new AST_SimpleStatement({
  20515. start: my_start_token(M),
  20516. end: my_end_token(M),
  20517. body: from_moz(expr)
  20518. });
  20519. },
  20520. TryStatement: function(M) {
  20521. var handlers = M.handlers || [M.handler];
  20522. if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) {
  20523. throw new Error("Multiple catch clauses are not supported.");
  20524. }
  20525. return new AST_Try({
  20526. start : my_start_token(M),
  20527. end : my_end_token(M),
  20528. body : from_moz(M.block).body,
  20529. bcatch : from_moz(handlers[0]),
  20530. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  20531. });
  20532. },
  20533. Property: function(M) {
  20534. var key = M.key;
  20535. var name = key.type == "Identifier" ? key.name : key.value;
  20536. var args = {
  20537. start : my_start_token(key),
  20538. end : my_end_token(M.value),
  20539. key : name,
  20540. value : from_moz(M.value)
  20541. };
  20542. switch (M.kind) {
  20543. case "init":
  20544. return new AST_ObjectKeyVal(args);
  20545. case "set":
  20546. args.value.name = from_moz(key);
  20547. return new AST_ObjectSetter(args);
  20548. case "get":
  20549. args.value.name = from_moz(key);
  20550. return new AST_ObjectGetter(args);
  20551. }
  20552. },
  20553. ObjectExpression: function(M) {
  20554. return new AST_Object({
  20555. start : my_start_token(M),
  20556. end : my_end_token(M),
  20557. properties : M.properties.map(function(prop){
  20558. prop.type = "Property";
  20559. return from_moz(prop)
  20560. })
  20561. });
  20562. },
  20563. SequenceExpression: function(M) {
  20564. return AST_Seq.from_array(M.expressions.map(from_moz));
  20565. },
  20566. MemberExpression: function(M) {
  20567. return new (M.computed ? AST_Sub : AST_Dot)({
  20568. start : my_start_token(M),
  20569. end : my_end_token(M),
  20570. property : M.computed ? from_moz(M.property) : M.property.name,
  20571. expression : from_moz(M.object)
  20572. });
  20573. },
  20574. SwitchCase: function(M) {
  20575. return new (M.test ? AST_Case : AST_Default)({
  20576. start : my_start_token(M),
  20577. end : my_end_token(M),
  20578. expression : from_moz(M.test),
  20579. body : M.consequent.map(from_moz)
  20580. });
  20581. },
  20582. VariableDeclaration: function(M) {
  20583. return new (M.kind === "const" ? AST_Const : AST_Var)({
  20584. start : my_start_token(M),
  20585. end : my_end_token(M),
  20586. definitions : M.declarations.map(from_moz)
  20587. });
  20588. },
  20589. Literal: function(M) {
  20590. var val = M.value, args = {
  20591. start : my_start_token(M),
  20592. end : my_end_token(M)
  20593. };
  20594. if (val === null) return new AST_Null(args);
  20595. switch (typeof val) {
  20596. case "string":
  20597. args.value = val;
  20598. return new AST_String(args);
  20599. case "number":
  20600. args.value = val;
  20601. return new AST_Number(args);
  20602. case "boolean":
  20603. return new (val ? AST_True : AST_False)(args);
  20604. default:
  20605. args.value = val;
  20606. return new AST_RegExp(args);
  20607. }
  20608. },
  20609. Identifier: function(M) {
  20610. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  20611. return new ( p.type == "LabeledStatement" ? AST_Label
  20612. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
  20613. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  20614. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  20615. : p.type == "CatchClause" ? AST_SymbolCatch
  20616. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  20617. : AST_SymbolRef)({
  20618. start : my_start_token(M),
  20619. end : my_end_token(M),
  20620. name : M.name
  20621. });
  20622. }
  20623. };
  20624. MOZ_TO_ME.UpdateExpression =
  20625. MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) {
  20626. var prefix = "prefix" in M ? M.prefix
  20627. : M.type == "UnaryExpression" ? true : false;
  20628. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  20629. start : my_start_token(M),
  20630. end : my_end_token(M),
  20631. operator : M.operator,
  20632. expression : from_moz(M.argument)
  20633. });
  20634. };
  20635. map("Program", AST_Toplevel, "body@body");
  20636. map("EmptyStatement", AST_EmptyStatement);
  20637. map("BlockStatement", AST_BlockStatement, "body@body");
  20638. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  20639. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  20640. map("BreakStatement", AST_Break, "label>label");
  20641. map("ContinueStatement", AST_Continue, "label>label");
  20642. map("WithStatement", AST_With, "object>expression, body>body");
  20643. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  20644. map("ReturnStatement", AST_Return, "argument>value");
  20645. map("ThrowStatement", AST_Throw, "argument>value");
  20646. map("WhileStatement", AST_While, "test>condition, body>body");
  20647. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  20648. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  20649. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  20650. map("DebuggerStatement", AST_Debugger);
  20651. map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body");
  20652. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  20653. map("CatchClause", AST_Catch, "param>argname, body%body");
  20654. map("ThisExpression", AST_This);
  20655. map("ArrayExpression", AST_Array, "elements@elements");
  20656. map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body");
  20657. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  20658. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  20659. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  20660. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  20661. map("NewExpression", AST_New, "callee>expression, arguments@args");
  20662. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  20663. def_to_moz(AST_Directive, function To_Moz_Directive(M) {
  20664. return {
  20665. type: "ExpressionStatement",
  20666. expression: {
  20667. type: "Literal",
  20668. value: M.value
  20669. }
  20670. };
  20671. });
  20672. def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) {
  20673. return {
  20674. type: "ExpressionStatement",
  20675. expression: to_moz(M.body)
  20676. };
  20677. });
  20678. def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) {
  20679. return {
  20680. type: "SwitchCase",
  20681. test: to_moz(M.expression),
  20682. consequent: M.body.map(to_moz)
  20683. };
  20684. });
  20685. def_to_moz(AST_Try, function To_Moz_TryStatement(M) {
  20686. return {
  20687. type: "TryStatement",
  20688. block: to_moz_block(M),
  20689. handler: to_moz(M.bcatch),
  20690. guardedHandlers: [],
  20691. finalizer: to_moz(M.bfinally)
  20692. };
  20693. });
  20694. def_to_moz(AST_Catch, function To_Moz_CatchClause(M) {
  20695. return {
  20696. type: "CatchClause",
  20697. param: to_moz(M.argname),
  20698. guard: null,
  20699. body: to_moz_block(M)
  20700. };
  20701. });
  20702. def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) {
  20703. return {
  20704. type: "VariableDeclaration",
  20705. kind: M instanceof AST_Const ? "const" : "var",
  20706. declarations: M.definitions.map(to_moz)
  20707. };
  20708. });
  20709. def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) {
  20710. return {
  20711. type: "SequenceExpression",
  20712. expressions: M.to_array().map(to_moz)
  20713. };
  20714. });
  20715. def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) {
  20716. var isComputed = M instanceof AST_Sub;
  20717. return {
  20718. type: "MemberExpression",
  20719. object: to_moz(M.expression),
  20720. computed: isComputed,
  20721. property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}
  20722. };
  20723. });
  20724. def_to_moz(AST_Unary, function To_Moz_Unary(M) {
  20725. return {
  20726. type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression",
  20727. operator: M.operator,
  20728. prefix: M instanceof AST_UnaryPrefix,
  20729. argument: to_moz(M.expression)
  20730. };
  20731. });
  20732. def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) {
  20733. return {
  20734. type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression",
  20735. left: to_moz(M.left),
  20736. operator: M.operator,
  20737. right: to_moz(M.right)
  20738. };
  20739. });
  20740. def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) {
  20741. return {
  20742. type: "ObjectExpression",
  20743. properties: M.properties.map(to_moz)
  20744. };
  20745. });
  20746. def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) {
  20747. var key = (
  20748. is_identifier(M.key)
  20749. ? {type: "Identifier", name: M.key}
  20750. : {type: "Literal", value: M.key}
  20751. );
  20752. var kind;
  20753. if (M instanceof AST_ObjectKeyVal) {
  20754. kind = "init";
  20755. } else
  20756. if (M instanceof AST_ObjectGetter) {
  20757. kind = "get";
  20758. } else
  20759. if (M instanceof AST_ObjectSetter) {
  20760. kind = "set";
  20761. }
  20762. return {
  20763. type: "Property",
  20764. kind: kind,
  20765. key: key,
  20766. value: to_moz(M.value)
  20767. };
  20768. });
  20769. def_to_moz(AST_Symbol, function To_Moz_Identifier(M) {
  20770. var def = M.definition();
  20771. return {
  20772. type: "Identifier",
  20773. name: def ? def.mangled_name || def.name : M.name
  20774. };
  20775. });
  20776. def_to_moz(AST_Constant, function To_Moz_Literal(M) {
  20777. var value = M.value;
  20778. if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) {
  20779. return {
  20780. type: "UnaryExpression",
  20781. operator: "-",
  20782. prefix: true,
  20783. argument: {
  20784. type: "Literal",
  20785. value: -value
  20786. }
  20787. };
  20788. }
  20789. return {
  20790. type: "Literal",
  20791. value: value
  20792. };
  20793. });
  20794. def_to_moz(AST_Atom, function To_Moz_Atom(M) {
  20795. return {
  20796. type: "Identifier",
  20797. name: String(M.value)
  20798. };
  20799. });
  20800. AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  20801. AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  20802. AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null });
  20803. AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast);
  20804. AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast);
  20805. /* -----[ tools ]----- */
  20806. function my_start_token(moznode) {
  20807. var loc = moznode.loc;
  20808. var range = moznode.range;
  20809. return new AST_Token({
  20810. file : loc && loc.source,
  20811. line : loc && loc.start.line,
  20812. col : loc && loc.start.column,
  20813. pos : range ? range[0] : moznode.start,
  20814. endpos : range ? range[0] : moznode.start
  20815. });
  20816. };
  20817. function my_end_token(moznode) {
  20818. var loc = moznode.loc;
  20819. var range = moznode.range;
  20820. return new AST_Token({
  20821. file : loc && loc.source,
  20822. line : loc && loc.end.line,
  20823. col : loc && loc.end.column,
  20824. pos : range ? range[1] : moznode.end,
  20825. endpos : range ? range[1] : moznode.end
  20826. });
  20827. };
  20828. function map(moztype, mytype, propmap) {
  20829. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  20830. moz_to_me += "return new " + mytype.name + "({\n" +
  20831. "start: my_start_token(M),\n" +
  20832. "end: my_end_token(M)";
  20833. var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
  20834. me_to_moz += "return {\n" +
  20835. "type: " + JSON.stringify(moztype);
  20836. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
  20837. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  20838. if (!m) throw new Error("Can't understand property map: " + prop);
  20839. var moz = m[1], how = m[2], my = m[3];
  20840. moz_to_me += ",\n" + my + ": ";
  20841. me_to_moz += ",\n" + moz + ": ";
  20842. switch (how) {
  20843. case "@":
  20844. moz_to_me += "M." + moz + ".map(from_moz)";
  20845. me_to_moz += "M." + my + ".map(to_moz)";
  20846. break;
  20847. case ">":
  20848. moz_to_me += "from_moz(M." + moz + ")";
  20849. me_to_moz += "to_moz(M." + my + ")";
  20850. break;
  20851. case "=":
  20852. moz_to_me += "M." + moz;
  20853. me_to_moz += "M." + my;
  20854. break;
  20855. case "%":
  20856. moz_to_me += "from_moz(M." + moz + ").body";
  20857. me_to_moz += "to_moz_block(M)";
  20858. break;
  20859. default:
  20860. throw new Error("Can't understand operator in propmap: " + prop);
  20861. }
  20862. });
  20863. moz_to_me += "\n})\n}";
  20864. me_to_moz += "\n}\n}";
  20865. //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  20866. //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
  20867. //console.log(moz_to_me);
  20868. moz_to_me = new Function("my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  20869. my_start_token, my_end_token, from_moz
  20870. );
  20871. me_to_moz = new Function("to_moz", "to_moz_block", "return(" + me_to_moz + ")")(
  20872. to_moz, to_moz_block
  20873. );
  20874. MOZ_TO_ME[moztype] = moz_to_me;
  20875. def_to_moz(mytype, me_to_moz);
  20876. };
  20877. var FROM_MOZ_STACK = null;
  20878. function from_moz(node) {
  20879. FROM_MOZ_STACK.push(node);
  20880. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  20881. FROM_MOZ_STACK.pop();
  20882. return ret;
  20883. };
  20884. AST_Node.from_mozilla_ast = function(node){
  20885. var save_stack = FROM_MOZ_STACK;
  20886. FROM_MOZ_STACK = [];
  20887. var ast = from_moz(node);
  20888. FROM_MOZ_STACK = save_stack;
  20889. return ast;
  20890. };
  20891. function moz_sub_loc(token) {
  20892. return token.line ? {
  20893. line: token.line,
  20894. column: token.col
  20895. } : null;
  20896. };
  20897. function set_moz_loc(mynode, moznode) {
  20898. var start = mynode.start;
  20899. var end = mynode.end;
  20900. if (start.pos != null && end.pos != null) {
  20901. moznode.range = [start.pos, end.pos];
  20902. }
  20903. if (start.line) {
  20904. moznode.loc = {
  20905. start: moz_sub_loc(start),
  20906. end: moz_sub_loc(end)
  20907. };
  20908. if (start.file) {
  20909. moznode.loc.source = start.file;
  20910. }
  20911. }
  20912. return moznode;
  20913. };
  20914. function def_to_moz(mytype, handler) {
  20915. mytype.DEFMETHOD("to_mozilla_ast", function() {
  20916. return set_moz_loc(this, handler(this));
  20917. });
  20918. };
  20919. function to_moz(node) {
  20920. return node != null ? node.to_mozilla_ast() : null;
  20921. };
  20922. function to_moz_block(node) {
  20923. return {
  20924. type: "BlockStatement",
  20925. body: node.body.map(to_moz)
  20926. };
  20927. };
  20928. })();
  20929. AST_Node.warn_function = function(txt) { logger.error("uglifyjs2 WARN: " + txt); };
  20930. exports.minify = function(files, options, name) {
  20931. options = defaults(options, {
  20932. spidermonkey : false,
  20933. outSourceMap : null,
  20934. sourceRoot : null,
  20935. inSourceMap : null,
  20936. fromString : false,
  20937. warnings : false,
  20938. mangle : {},
  20939. output : null,
  20940. compress : {}
  20941. });
  20942. base54.reset();
  20943. // 1. parse
  20944. var toplevel = null,
  20945. sourcesContent = {};
  20946. if (options.spidermonkey) {
  20947. toplevel = AST_Node.from_mozilla_ast(files);
  20948. } else {
  20949. if (typeof files == "string")
  20950. files = [ files ];
  20951. files.forEach(function(file){
  20952. var code = options.fromString
  20953. ? file
  20954. : rjsFile.readFile(file, "utf8");
  20955. sourcesContent[file] = code;
  20956. toplevel = parse(code, {
  20957. filename: options.fromString ? name : file,
  20958. toplevel: toplevel
  20959. });
  20960. });
  20961. }
  20962. // 2. compress
  20963. if (options.compress) {
  20964. var compress = { warnings: options.warnings };
  20965. merge(compress, options.compress);
  20966. toplevel.figure_out_scope();
  20967. var sq = Compressor(compress);
  20968. toplevel = toplevel.transform(sq);
  20969. }
  20970. // 3. mangle
  20971. if (options.mangle) {
  20972. toplevel.figure_out_scope();
  20973. toplevel.compute_char_frequency();
  20974. toplevel.mangle_names(options.mangle);
  20975. }
  20976. // 4. output
  20977. var inMap = options.inSourceMap;
  20978. var output = {};
  20979. if (typeof options.inSourceMap == "string") {
  20980. inMap = rjsFile.readFile(options.inSourceMap, "utf8");
  20981. }
  20982. if (options.outSourceMap) {
  20983. output.source_map = SourceMap({
  20984. file: options.outSourceMap,
  20985. orig: inMap,
  20986. root: options.sourceRoot
  20987. });
  20988. if (options.sourceMapIncludeSources) {
  20989. for (var file in sourcesContent) {
  20990. if (sourcesContent.hasOwnProperty(file)) {
  20991. output.source_map.get().setSourceContent(file, sourcesContent[file]);
  20992. }
  20993. }
  20994. }
  20995. }
  20996. if (options.output) {
  20997. merge(output, options.output);
  20998. }
  20999. var stream = OutputStream(output);
  21000. toplevel.print(stream);
  21001. if(options.outSourceMap){
  21002. stream += "\n//# sourceMappingURL=" + options.outSourceMap;
  21003. }
  21004. return {
  21005. code : stream + "",
  21006. map : output.source_map + ""
  21007. };
  21008. };
  21009. // exports.describe_ast = function() {
  21010. // function doitem(ctor) {
  21011. // var sub = {};
  21012. // ctor.SUBCLASSES.forEach(function(ctor){
  21013. // sub[ctor.TYPE] = doitem(ctor);
  21014. // });
  21015. // var ret = {};
  21016. // if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS;
  21017. // if (ctor.SUBCLASSES.length > 0) ret.sub = sub;
  21018. // return ret;
  21019. // }
  21020. // return doitem(AST_Node).sub;
  21021. // }
  21022. exports.describe_ast = function() {
  21023. var out = OutputStream({ beautify: true });
  21024. function doitem(ctor) {
  21025. out.print("AST_" + ctor.TYPE);
  21026. var props = ctor.SELF_PROPS.filter(function(prop){
  21027. return !/^\$/.test(prop);
  21028. });
  21029. if (props.length > 0) {
  21030. out.space();
  21031. out.with_parens(function(){
  21032. props.forEach(function(prop, i){
  21033. if (i) out.space();
  21034. out.print(prop);
  21035. });
  21036. });
  21037. }
  21038. if (ctor.documentation) {
  21039. out.space();
  21040. out.print_string(ctor.documentation);
  21041. }
  21042. if (ctor.SUBCLASSES.length > 0) {
  21043. out.space();
  21044. out.with_block(function(){
  21045. ctor.SUBCLASSES.forEach(function(ctor, i){
  21046. out.indent();
  21047. doitem(ctor);
  21048. out.newline();
  21049. });
  21050. });
  21051. }
  21052. };
  21053. doitem(AST_Node);
  21054. return out + "";
  21055. };
  21056. });
  21057. /**
  21058. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  21059. * Available via the MIT or new BSD license.
  21060. * see: http://github.com/jrburke/requirejs for details
  21061. */
  21062. /*jslint plusplus: true */
  21063. /*global define: false */
  21064. define('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) {
  21065. 'use strict';
  21066. function arrayToString(ary) {
  21067. var output = '[';
  21068. if (ary) {
  21069. ary.forEach(function (item, i) {
  21070. output += (i > 0 ? ',' : '') + '"' + lang.jsEscape(item) + '"';
  21071. });
  21072. }
  21073. output += ']';
  21074. return output;
  21075. }
  21076. //This string is saved off because JSLint complains
  21077. //about obj.arguments use, as 'reserved word'
  21078. var argPropName = 'arguments',
  21079. //Default object to use for "scope" checking for UMD identifiers.
  21080. emptyScope = {},
  21081. mixin = lang.mixin,
  21082. hasProp = lang.hasProp;
  21083. //From an esprima example for traversing its ast.
  21084. function traverse(object, visitor) {
  21085. var key, child;
  21086. if (!object) {
  21087. return;
  21088. }
  21089. if (visitor.call(null, object) === false) {
  21090. return false;
  21091. }
  21092. for (key in object) {
  21093. if (object.hasOwnProperty(key)) {
  21094. child = object[key];
  21095. if (typeof child === 'object' && child !== null) {
  21096. if (traverse(child, visitor) === false) {
  21097. return false;
  21098. }
  21099. }
  21100. }
  21101. }
  21102. }
  21103. //Like traverse, but visitor returning false just
  21104. //stops that subtree analysis, not the rest of tree
  21105. //visiting.
  21106. function traverseBroad(object, visitor) {
  21107. var key, child;
  21108. if (!object) {
  21109. return;
  21110. }
  21111. if (visitor.call(null, object) === false) {
  21112. return false;
  21113. }
  21114. for (key in object) {
  21115. if (object.hasOwnProperty(key)) {
  21116. child = object[key];
  21117. if (typeof child === 'object' && child !== null) {
  21118. traverseBroad(child, visitor);
  21119. }
  21120. }
  21121. }
  21122. }
  21123. /**
  21124. * Pulls out dependencies from an array literal with just string members.
  21125. * If string literals, will just return those string values in an array,
  21126. * skipping other items in the array.
  21127. *
  21128. * @param {Node} node an AST node.
  21129. *
  21130. * @returns {Array} an array of strings.
  21131. * If null is returned, then it means the input node was not a valid
  21132. * dependency.
  21133. */
  21134. function getValidDeps(node) {
  21135. if (!node || node.type !== 'ArrayExpression' || !node.elements) {
  21136. return;
  21137. }
  21138. var deps = [];
  21139. node.elements.some(function (elem) {
  21140. if (elem.type === 'Literal') {
  21141. deps.push(elem.value);
  21142. }
  21143. });
  21144. return deps.length ? deps : undefined;
  21145. }
  21146. // Detects regular or arrow function expressions as the desired expression
  21147. // type.
  21148. function isFnExpression(node) {
  21149. return (node && (node.type === 'FunctionExpression' ||
  21150. node.type === 'ArrowFunctionExpression'));
  21151. }
  21152. /**
  21153. * Main parse function. Returns a string of any valid require or
  21154. * define/require.def calls as part of one JavaScript source string.
  21155. * @param {String} moduleName the module name that represents this file.
  21156. * It is used to create a default define if there is not one already for the
  21157. * file. This allows properly tracing dependencies for builds. Otherwise, if
  21158. * the file just has a require() call, the file dependencies will not be
  21159. * properly reflected: the file will come before its dependencies.
  21160. * @param {String} moduleName
  21161. * @param {String} fileName
  21162. * @param {String} fileContents
  21163. * @param {Object} options optional options. insertNeedsDefine: true will
  21164. * add calls to require.needsDefine() if appropriate.
  21165. * @returns {String} JS source string or null, if no require or
  21166. * define/require.def calls are found.
  21167. */
  21168. function parse(moduleName, fileName, fileContents, options) {
  21169. options = options || {};
  21170. //Set up source input
  21171. var i, moduleCall, depString,
  21172. moduleDeps = [],
  21173. result = '',
  21174. moduleList = [],
  21175. needsDefine = true,
  21176. astRoot = esprima.parse(fileContents);
  21177. parse.recurse(astRoot, function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) {
  21178. if (!deps) {
  21179. deps = [];
  21180. }
  21181. if (callName === 'define' && (!name || name === moduleName)) {
  21182. needsDefine = false;
  21183. }
  21184. if (!name) {
  21185. //If there is no module name, the dependencies are for
  21186. //this file/default module name.
  21187. moduleDeps = moduleDeps.concat(deps);
  21188. } else {
  21189. moduleList.push({
  21190. name: name,
  21191. deps: deps
  21192. });
  21193. }
  21194. if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) {
  21195. return factoryIdentifier;
  21196. }
  21197. //If define was found, no need to dive deeper, unless
  21198. //the config explicitly wants to dig deeper.
  21199. return !!options.findNestedDependencies;
  21200. }, options);
  21201. if (options.insertNeedsDefine && needsDefine) {
  21202. result += 'require.needsDefine("' + moduleName + '");';
  21203. }
  21204. if (moduleDeps.length || moduleList.length) {
  21205. for (i = 0; i < moduleList.length; i++) {
  21206. moduleCall = moduleList[i];
  21207. if (result) {
  21208. result += '\n';
  21209. }
  21210. //If this is the main module for this file, combine any
  21211. //"anonymous" dependencies (could come from a nested require
  21212. //call) with this module.
  21213. if (moduleCall.name === moduleName) {
  21214. moduleCall.deps = moduleCall.deps.concat(moduleDeps);
  21215. moduleDeps = [];
  21216. }
  21217. depString = arrayToString(moduleCall.deps);
  21218. result += 'define("' + moduleCall.name + '",' +
  21219. depString + ');';
  21220. }
  21221. if (moduleDeps.length) {
  21222. if (result) {
  21223. result += '\n';
  21224. }
  21225. depString = arrayToString(moduleDeps);
  21226. result += 'define("' + moduleName + '",' + depString + ');';
  21227. }
  21228. }
  21229. return result || null;
  21230. }
  21231. parse.traverse = traverse;
  21232. parse.traverseBroad = traverseBroad;
  21233. parse.isFnExpression = isFnExpression;
  21234. /**
  21235. * Handles parsing a file recursively for require calls.
  21236. * @param {Array} parentNode the AST node to start with.
  21237. * @param {Function} onMatch function to call on a parse match.
  21238. * @param {Object} [options] This is normally the build config options if
  21239. * it is passed.
  21240. * @param {Object} [fnExpScope] holds list of function expresssion
  21241. * argument identifiers, set up internally, not passed in
  21242. */
  21243. parse.recurse = function (object, onMatch, options, fnExpScope) {
  21244. //Like traverse, but skips if branches that would not be processed
  21245. //after has application that results in tests of true or false boolean
  21246. //literal values.
  21247. var key, child, result, i, params, param, tempObject,
  21248. hasHas = options && options.has;
  21249. fnExpScope = fnExpScope || emptyScope;
  21250. if (!object) {
  21251. return;
  21252. }
  21253. //If has replacement has resulted in if(true){} or if(false){}, take
  21254. //the appropriate branch and skip the other one.
  21255. if (hasHas && object.type === 'IfStatement' && object.test.type &&
  21256. object.test.type === 'Literal') {
  21257. if (object.test.value) {
  21258. //Take the if branch
  21259. this.recurse(object.consequent, onMatch, options, fnExpScope);
  21260. } else {
  21261. //Take the else branch
  21262. this.recurse(object.alternate, onMatch, options, fnExpScope);
  21263. }
  21264. } else {
  21265. result = this.parseNode(object, onMatch, fnExpScope);
  21266. if (result === false) {
  21267. return;
  21268. } else if (typeof result === 'string') {
  21269. return result;
  21270. }
  21271. //Build up a "scope" object that informs nested recurse calls if
  21272. //the define call references an identifier that is likely a UMD
  21273. //wrapped function expression argument.
  21274. //Catch (function(a) {... wrappers
  21275. if (object.type === 'ExpressionStatement' && object.expression &&
  21276. object.expression.type === 'CallExpression' && object.expression.callee &&
  21277. isFnExpression(object.expression.callee)) {
  21278. tempObject = object.expression.callee;
  21279. }
  21280. // Catch !function(a) {... wrappers
  21281. if (object.type === 'UnaryExpression' && object.argument &&
  21282. object.argument.type === 'CallExpression' && object.argument.callee &&
  21283. isFnExpression(object.argument.callee)) {
  21284. tempObject = object.argument.callee;
  21285. }
  21286. if (tempObject && tempObject.params && tempObject.params.length) {
  21287. params = tempObject.params;
  21288. fnExpScope = mixin({}, fnExpScope, true);
  21289. for (i = 0; i < params.length; i++) {
  21290. param = params[i];
  21291. if (param.type === 'Identifier') {
  21292. fnExpScope[param.name] = true;
  21293. }
  21294. }
  21295. }
  21296. for (key in object) {
  21297. if (object.hasOwnProperty(key)) {
  21298. child = object[key];
  21299. if (typeof child === 'object' && child !== null) {
  21300. result = this.recurse(child, onMatch, options, fnExpScope);
  21301. if (typeof result === 'string') {
  21302. break;
  21303. }
  21304. }
  21305. }
  21306. }
  21307. //Check for an identifier for a factory function identifier being
  21308. //passed in as a function expression, indicating a UMD-type of
  21309. //wrapping.
  21310. if (typeof result === 'string') {
  21311. if (hasProp(fnExpScope, result)) {
  21312. //result still in scope, keep jumping out indicating the
  21313. //identifier still in use.
  21314. return result;
  21315. }
  21316. return;
  21317. }
  21318. }
  21319. };
  21320. /**
  21321. * Determines if the file defines the require/define module API.
  21322. * Specifically, it looks for the `define.amd = ` expression.
  21323. * @param {String} fileName
  21324. * @param {String} fileContents
  21325. * @returns {Boolean}
  21326. */
  21327. parse.definesRequire = function (fileName, fileContents) {
  21328. var found = false;
  21329. traverse(esprima.parse(fileContents), function (node) {
  21330. if (parse.hasDefineAmd(node)) {
  21331. found = true;
  21332. //Stop traversal
  21333. return false;
  21334. }
  21335. });
  21336. return found;
  21337. };
  21338. /**
  21339. * Finds require("") calls inside a CommonJS anonymous module wrapped in a
  21340. * define(function(require, exports, module){}) wrapper. These dependencies
  21341. * will be added to a modified define() call that lists the dependencies
  21342. * on the outside of the function.
  21343. * @param {String} fileName
  21344. * @param {String|Object} fileContents: a string of contents, or an already
  21345. * parsed AST tree.
  21346. * @returns {Array} an array of module names that are dependencies. Always
  21347. * returns an array, but could be of length zero.
  21348. */
  21349. parse.getAnonDeps = function (fileName, fileContents) {
  21350. var astRoot = typeof fileContents === 'string' ?
  21351. esprima.parse(fileContents) : fileContents,
  21352. defFunc = this.findAnonDefineFactory(astRoot);
  21353. return parse.getAnonDepsFromNode(defFunc);
  21354. };
  21355. /**
  21356. * Finds require("") calls inside a CommonJS anonymous module wrapped
  21357. * in a define function, given an AST node for the definition function.
  21358. * @param {Node} node the AST node for the definition function.
  21359. * @returns {Array} and array of dependency names. Can be of zero length.
  21360. */
  21361. parse.getAnonDepsFromNode = function (node) {
  21362. var deps = [],
  21363. funcArgLength;
  21364. if (node) {
  21365. this.findRequireDepNames(node, deps);
  21366. //If no deps, still add the standard CommonJS require, exports,
  21367. //module, in that order, to the deps, but only if specified as
  21368. //function args. In particular, if exports is used, it is favored
  21369. //over the return value of the function, so only add it if asked.
  21370. funcArgLength = node.params && node.params.length;
  21371. if (funcArgLength) {
  21372. deps = (funcArgLength > 1 ? ["require", "exports", "module"] :
  21373. ["require"]).concat(deps);
  21374. }
  21375. }
  21376. return deps;
  21377. };
  21378. parse.isDefineNodeWithArgs = function (node) {
  21379. return node && node.type === 'CallExpression' &&
  21380. node.callee && node.callee.type === 'Identifier' &&
  21381. node.callee.name === 'define' && node[argPropName];
  21382. };
  21383. /**
  21384. * Finds the function in define(function (require, exports, module){});
  21385. * @param {Array} node
  21386. * @returns {Boolean}
  21387. */
  21388. parse.findAnonDefineFactory = function (node) {
  21389. var match;
  21390. traverse(node, function (node) {
  21391. var arg0, arg1;
  21392. if (parse.isDefineNodeWithArgs(node)) {
  21393. //Just the factory function passed to define
  21394. arg0 = node[argPropName][0];
  21395. if (isFnExpression(arg0)) {
  21396. match = arg0;
  21397. return false;
  21398. }
  21399. //A string literal module ID followed by the factory function.
  21400. arg1 = node[argPropName][1];
  21401. if (arg0.type === 'Literal' && isFnExpression(arg1)) {
  21402. match = arg1;
  21403. return false;
  21404. }
  21405. }
  21406. });
  21407. return match;
  21408. };
  21409. /**
  21410. * Finds any config that is passed to requirejs. That includes calls to
  21411. * require/requirejs.config(), as well as require({}, ...) and
  21412. * requirejs({}, ...)
  21413. * @param {String} fileContents
  21414. *
  21415. * @returns {Object} a config details object with the following properties:
  21416. * - config: {Object} the config object found. Can be undefined if no
  21417. * config found.
  21418. * - range: {Array} the start index and end index in the contents where
  21419. * the config was found. Can be undefined if no config found.
  21420. * Can throw an error if the config in the file cannot be evaluated in
  21421. * a build context to valid JavaScript.
  21422. */
  21423. parse.findConfig = function (fileContents) {
  21424. /*jslint evil: true */
  21425. var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch,
  21426. quoteRegExp = /(:\s|\[\s*)(['"])/,
  21427. astRoot = esprima.parse(fileContents, {
  21428. loc: true
  21429. });
  21430. traverse(astRoot, function (node) {
  21431. var arg,
  21432. requireType = parse.hasRequire(node);
  21433. if (requireType && (requireType === 'require' ||
  21434. requireType === 'requirejs' ||
  21435. requireType === 'requireConfig' ||
  21436. requireType === 'requirejsConfig')) {
  21437. arg = node[argPropName] && node[argPropName][0];
  21438. if (arg && arg.type === 'ObjectExpression') {
  21439. stringData = parse.nodeToString(fileContents, arg);
  21440. jsConfig = stringData.value;
  21441. foundRange = stringData.range;
  21442. return false;
  21443. }
  21444. } else {
  21445. arg = parse.getRequireObjectLiteral(node);
  21446. if (arg) {
  21447. stringData = parse.nodeToString(fileContents, arg);
  21448. jsConfig = stringData.value;
  21449. foundRange = stringData.range;
  21450. return false;
  21451. }
  21452. }
  21453. });
  21454. if (jsConfig) {
  21455. // Eval the config
  21456. quoteMatch = quoteRegExp.exec(jsConfig);
  21457. quote = (quoteMatch && quoteMatch[2]) || '"';
  21458. foundConfig = eval('(' + jsConfig + ')');
  21459. }
  21460. return {
  21461. config: foundConfig,
  21462. range: foundRange,
  21463. quote: quote
  21464. };
  21465. };
  21466. /** Returns the node for the object literal assigned to require/requirejs,
  21467. * for holding a declarative config.
  21468. */
  21469. parse.getRequireObjectLiteral = function (node) {
  21470. if (node.id && node.id.type === 'Identifier' &&
  21471. (node.id.name === 'require' || node.id.name === 'requirejs') &&
  21472. node.init && node.init.type === 'ObjectExpression') {
  21473. return node.init;
  21474. }
  21475. };
  21476. /**
  21477. * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define
  21478. * Does *not* do .config calls though. See pragma.namespace for the complete
  21479. * set of namespace transforms. This function is used because require calls
  21480. * inside a define() call should not be renamed, so a simple regexp is not
  21481. * good enough.
  21482. * @param {String} fileContents the contents to transform.
  21483. * @param {String} ns the namespace, *not* including trailing dot.
  21484. * @return {String} the fileContents with the namespace applied
  21485. */
  21486. parse.renameNamespace = function (fileContents, ns) {
  21487. var lines,
  21488. locs = [],
  21489. astRoot = esprima.parse(fileContents, {
  21490. loc: true
  21491. });
  21492. parse.recurse(astRoot, function (callName, config, name, deps, node) {
  21493. locs.push(node.loc);
  21494. //Do not recurse into define functions, they should be using
  21495. //local defines.
  21496. return callName !== 'define';
  21497. }, {});
  21498. if (locs.length) {
  21499. lines = fileContents.split('\n');
  21500. //Go backwards through the found locs, adding in the namespace name
  21501. //in front.
  21502. locs.reverse();
  21503. locs.forEach(function (loc) {
  21504. var startIndex = loc.start.column,
  21505. //start.line is 1-based, not 0 based.
  21506. lineIndex = loc.start.line - 1,
  21507. line = lines[lineIndex];
  21508. lines[lineIndex] = line.substring(0, startIndex) +
  21509. ns + '.' +
  21510. line.substring(startIndex,
  21511. line.length);
  21512. });
  21513. fileContents = lines.join('\n');
  21514. }
  21515. return fileContents;
  21516. };
  21517. /**
  21518. * Finds all dependencies specified in dependency arrays and inside
  21519. * simplified commonjs wrappers.
  21520. * @param {String} fileName
  21521. * @param {String} fileContents
  21522. *
  21523. * @returns {Array} an array of dependency strings. The dependencies
  21524. * have not been normalized, they may be relative IDs.
  21525. */
  21526. parse.findDependencies = function (fileName, fileContents, options) {
  21527. var dependencies = [],
  21528. astRoot = esprima.parse(fileContents);
  21529. parse.recurse(astRoot, function (callName, config, name, deps) {
  21530. if (deps) {
  21531. dependencies = dependencies.concat(deps);
  21532. }
  21533. }, options);
  21534. return dependencies;
  21535. };
  21536. /**
  21537. * Finds only CJS dependencies, ones that are the form
  21538. * require('stringLiteral')
  21539. */
  21540. parse.findCjsDependencies = function (fileName, fileContents) {
  21541. var dependencies = [];
  21542. traverse(esprima.parse(fileContents), function (node) {
  21543. var arg;
  21544. if (node && node.type === 'CallExpression' && node.callee &&
  21545. node.callee.type === 'Identifier' &&
  21546. node.callee.name === 'require' && node[argPropName] &&
  21547. node[argPropName].length === 1) {
  21548. arg = node[argPropName][0];
  21549. if (arg.type === 'Literal') {
  21550. dependencies.push(arg.value);
  21551. }
  21552. }
  21553. });
  21554. return dependencies;
  21555. };
  21556. //function define() {}
  21557. parse.hasDefDefine = function (node) {
  21558. return node.type === 'FunctionDeclaration' && node.id &&
  21559. node.id.type === 'Identifier' && node.id.name === 'define';
  21560. };
  21561. //define.amd = ...
  21562. parse.hasDefineAmd = function (node) {
  21563. return node && node.type === 'AssignmentExpression' &&
  21564. node.left && node.left.type === 'MemberExpression' &&
  21565. node.left.object && node.left.object.name === 'define' &&
  21566. node.left.property && node.left.property.name === 'amd';
  21567. };
  21568. //define.amd reference, as in: if (define.amd)
  21569. parse.refsDefineAmd = function (node) {
  21570. return node && node.type === 'MemberExpression' &&
  21571. node.object && node.object.name === 'define' &&
  21572. node.object.type === 'Identifier' &&
  21573. node.property && node.property.name === 'amd' &&
  21574. node.property.type === 'Identifier';
  21575. };
  21576. //require(), requirejs(), require.config() and requirejs.config()
  21577. parse.hasRequire = function (node) {
  21578. var callName,
  21579. c = node && node.callee;
  21580. if (node && node.type === 'CallExpression' && c) {
  21581. if (c.type === 'Identifier' &&
  21582. (c.name === 'require' ||
  21583. c.name === 'requirejs')) {
  21584. //A require/requirejs({}, ...) call
  21585. callName = c.name;
  21586. } else if (c.type === 'MemberExpression' &&
  21587. c.object &&
  21588. c.object.type === 'Identifier' &&
  21589. (c.object.name === 'require' ||
  21590. c.object.name === 'requirejs') &&
  21591. c.property && c.property.name === 'config') {
  21592. // require/requirejs.config({}) call
  21593. callName = c.object.name + 'Config';
  21594. }
  21595. }
  21596. return callName;
  21597. };
  21598. //define()
  21599. parse.hasDefine = function (node) {
  21600. return node && node.type === 'CallExpression' && node.callee &&
  21601. node.callee.type === 'Identifier' &&
  21602. node.callee.name === 'define';
  21603. };
  21604. /**
  21605. * If there is a named define in the file, returns the name. Does not
  21606. * scan for mulitple names, just the first one.
  21607. */
  21608. parse.getNamedDefine = function (fileContents) {
  21609. var name;
  21610. traverse(esprima.parse(fileContents), function (node) {
  21611. if (node && node.type === 'CallExpression' && node.callee &&
  21612. node.callee.type === 'Identifier' &&
  21613. node.callee.name === 'define' &&
  21614. node[argPropName] && node[argPropName][0] &&
  21615. node[argPropName][0].type === 'Literal') {
  21616. name = node[argPropName][0].value;
  21617. return false;
  21618. }
  21619. });
  21620. return name;
  21621. };
  21622. /**
  21623. * Determines if define(), require({}|[]) or requirejs was called in the
  21624. * file. Also finds out if define() is declared and if define.amd is called.
  21625. */
  21626. parse.usesAmdOrRequireJs = function (fileName, fileContents) {
  21627. var uses;
  21628. traverse(esprima.parse(fileContents), function (node) {
  21629. var type, callName, arg;
  21630. if (parse.hasDefDefine(node)) {
  21631. //function define() {}
  21632. type = 'declaresDefine';
  21633. } else if (parse.hasDefineAmd(node)) {
  21634. type = 'defineAmd';
  21635. } else {
  21636. callName = parse.hasRequire(node);
  21637. if (callName) {
  21638. arg = node[argPropName] && node[argPropName][0];
  21639. if (arg && (arg.type === 'ObjectExpression' ||
  21640. arg.type === 'ArrayExpression')) {
  21641. type = callName;
  21642. }
  21643. } else if (parse.hasDefine(node)) {
  21644. type = 'define';
  21645. }
  21646. }
  21647. if (type) {
  21648. if (!uses) {
  21649. uses = {};
  21650. }
  21651. uses[type] = true;
  21652. }
  21653. });
  21654. return uses;
  21655. };
  21656. /**
  21657. * Determines if require(''), exports.x =, module.exports =,
  21658. * __dirname, __filename are used. So, not strictly traditional CommonJS,
  21659. * also checks for Node variants.
  21660. */
  21661. parse.usesCommonJs = function (fileName, fileContents) {
  21662. var uses = null,
  21663. assignsExports = false;
  21664. traverse(esprima.parse(fileContents), function (node) {
  21665. var type,
  21666. exp = node.expression || node.init;
  21667. if (node.type === 'Identifier' &&
  21668. (node.name === '__dirname' || node.name === '__filename')) {
  21669. type = node.name.substring(2);
  21670. } else if (node.type === 'VariableDeclarator' && node.id &&
  21671. node.id.type === 'Identifier' &&
  21672. node.id.name === 'exports') {
  21673. //Hmm, a variable assignment for exports, so does not use cjs
  21674. //exports.
  21675. type = 'varExports';
  21676. } else if (exp && exp.type === 'AssignmentExpression' && exp.left &&
  21677. exp.left.type === 'MemberExpression' && exp.left.object) {
  21678. if (exp.left.object.name === 'module' && exp.left.property &&
  21679. exp.left.property.name === 'exports') {
  21680. type = 'moduleExports';
  21681. } else if (exp.left.object.name === 'exports' &&
  21682. exp.left.property) {
  21683. type = 'exports';
  21684. }
  21685. } else if (node && node.type === 'CallExpression' && node.callee &&
  21686. node.callee.type === 'Identifier' &&
  21687. node.callee.name === 'require' && node[argPropName] &&
  21688. node[argPropName].length === 1 &&
  21689. node[argPropName][0].type === 'Literal') {
  21690. type = 'require';
  21691. }
  21692. if (type) {
  21693. if (type === 'varExports') {
  21694. assignsExports = true;
  21695. } else if (type !== 'exports' || !assignsExports) {
  21696. if (!uses) {
  21697. uses = {};
  21698. }
  21699. uses[type] = true;
  21700. }
  21701. }
  21702. });
  21703. return uses;
  21704. };
  21705. parse.findRequireDepNames = function (node, deps) {
  21706. traverse(node, function (node) {
  21707. var arg;
  21708. if (node && node.type === 'CallExpression' && node.callee &&
  21709. node.callee.type === 'Identifier' &&
  21710. node.callee.name === 'require' &&
  21711. node[argPropName] && node[argPropName].length === 1) {
  21712. arg = node[argPropName][0];
  21713. if (arg.type === 'Literal') {
  21714. deps.push(arg.value);
  21715. }
  21716. }
  21717. });
  21718. };
  21719. /**
  21720. * Determines if a specific node is a valid require or define/require.def
  21721. * call.
  21722. * @param {Array} node
  21723. * @param {Function} onMatch a function to call when a match is found.
  21724. * It is passed the match name, and the config, name, deps possible args.
  21725. * The config, name and deps args are not normalized.
  21726. * @param {Object} fnExpScope an object whose keys are all function
  21727. * expression identifiers that should be in scope. Useful for UMD wrapper
  21728. * detection to avoid parsing more into the wrapped UMD code.
  21729. *
  21730. * @returns {String} a JS source string with the valid require/define call.
  21731. * Otherwise null.
  21732. */
  21733. parse.parseNode = function (node, onMatch, fnExpScope) {
  21734. var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode,
  21735. args = node && node[argPropName],
  21736. callName = parse.hasRequire(node);
  21737. if (callName === 'require' || callName === 'requirejs') {
  21738. //A plain require/requirejs call
  21739. arg = node[argPropName] && node[argPropName][0];
  21740. if (arg && arg.type !== 'ArrayExpression') {
  21741. if (arg.type === 'ObjectExpression') {
  21742. //A config call, try the second arg.
  21743. arg = node[argPropName][1];
  21744. }
  21745. }
  21746. deps = getValidDeps(arg);
  21747. if (!deps) {
  21748. return;
  21749. }
  21750. return onMatch("require", null, null, deps, node);
  21751. } else if (parse.hasDefine(node) && args && args.length) {
  21752. name = args[0];
  21753. deps = args[1];
  21754. factory = args[2];
  21755. if (name.type === 'ArrayExpression') {
  21756. //No name, adjust args
  21757. factory = deps;
  21758. deps = name;
  21759. name = null;
  21760. } else if (isFnExpression(name)) {
  21761. //Just the factory, no name or deps
  21762. factory = name;
  21763. name = deps = null;
  21764. } else if (name.type !== 'Literal') {
  21765. //An object literal, just null out
  21766. name = deps = factory = null;
  21767. }
  21768. if (name && name.type === 'Literal' && deps) {
  21769. if (isFnExpression(deps)) {
  21770. //deps is the factory
  21771. factory = deps;
  21772. deps = null;
  21773. } else if (deps.type === 'ObjectExpression') {
  21774. //deps is object literal, null out
  21775. deps = factory = null;
  21776. } else if (deps.type === 'Identifier' && args.length === 2) {
  21777. // define('id', factory)
  21778. deps = factory = null;
  21779. }
  21780. }
  21781. if (deps && deps.type === 'ArrayExpression') {
  21782. deps = getValidDeps(deps);
  21783. } else if (isFnExpression(factory)) {
  21784. //If no deps and a factory function, could be a commonjs sugar
  21785. //wrapper, scan the function for dependencies.
  21786. cjsDeps = parse.getAnonDepsFromNode(factory);
  21787. if (cjsDeps.length) {
  21788. deps = cjsDeps;
  21789. }
  21790. } else if (deps || factory) {
  21791. //Does not match the shape of an AMD call.
  21792. return;
  21793. }
  21794. //Just save off the name as a string instead of an AST object.
  21795. if (name && name.type === 'Literal') {
  21796. name = name.value;
  21797. }
  21798. return onMatch("define", null, name, deps, node,
  21799. (factory && factory.type === 'Identifier' ? factory.name : undefined),
  21800. fnExpScope);
  21801. } else if (node.type === 'CallExpression' && node.callee &&
  21802. isFnExpression(node.callee) &&
  21803. node.callee.body && node.callee.body.body &&
  21804. node.callee.body.body.length === 1 &&
  21805. node.callee.body.body[0].type === 'IfStatement') {
  21806. bodyNode = node.callee.body.body[0];
  21807. //Look for a define(Identifier) case, but only if inside an
  21808. //if that has a define.amd test
  21809. if (bodyNode.consequent && bodyNode.consequent.body) {
  21810. exp = bodyNode.consequent.body[0];
  21811. if (exp.type === 'ExpressionStatement' && exp.expression &&
  21812. parse.hasDefine(exp.expression) &&
  21813. exp.expression.arguments &&
  21814. exp.expression.arguments.length === 1 &&
  21815. exp.expression.arguments[0].type === 'Identifier') {
  21816. //Calls define(Identifier) as first statement in body.
  21817. //Confirm the if test references define.amd
  21818. traverse(bodyNode.test, function (node) {
  21819. if (parse.refsDefineAmd(node)) {
  21820. refsDefine = true;
  21821. return false;
  21822. }
  21823. });
  21824. if (refsDefine) {
  21825. return onMatch("define", null, null, null, exp.expression,
  21826. exp.expression.arguments[0].name, fnExpScope);
  21827. }
  21828. }
  21829. }
  21830. }
  21831. };
  21832. /**
  21833. * Converts an AST node into a JS source string by extracting
  21834. * the node's location from the given contents string. Assumes
  21835. * esprima.parse() with loc was done.
  21836. * @param {String} contents
  21837. * @param {Object} node
  21838. * @returns {String} a JS source string.
  21839. */
  21840. parse.nodeToString = function (contents, node) {
  21841. var extracted,
  21842. loc = node.loc,
  21843. lines = contents.split('\n'),
  21844. firstLine = loc.start.line > 1 ?
  21845. lines.slice(0, loc.start.line - 1).join('\n') + '\n' :
  21846. '',
  21847. preamble = firstLine +
  21848. lines[loc.start.line - 1].substring(0, loc.start.column);
  21849. if (loc.start.line === loc.end.line) {
  21850. extracted = lines[loc.start.line - 1].substring(loc.start.column,
  21851. loc.end.column);
  21852. } else {
  21853. extracted = lines[loc.start.line - 1].substring(loc.start.column) +
  21854. '\n' +
  21855. lines.slice(loc.start.line, loc.end.line - 1).join('\n') +
  21856. '\n' +
  21857. lines[loc.end.line - 1].substring(0, loc.end.column);
  21858. }
  21859. return {
  21860. value: extracted,
  21861. range: [
  21862. preamble.length,
  21863. preamble.length + extracted.length
  21864. ]
  21865. };
  21866. };
  21867. /**
  21868. * Extracts license comments from JS text.
  21869. * @param {String} fileName
  21870. * @param {String} contents
  21871. * @returns {String} a string of license comments.
  21872. */
  21873. parse.getLicenseComments = function (fileName, contents) {
  21874. var commentNode, refNode, subNode, value, i, j,
  21875. //xpconnect's Reflect does not support comment or range, but
  21876. //prefer continued operation vs strict parity of operation,
  21877. //as license comments can be expressed in other ways, like
  21878. //via wrap args, or linked via sourcemaps.
  21879. ast = esprima.parse(contents, {
  21880. comment: true,
  21881. range: true
  21882. }),
  21883. result = '',
  21884. existsMap = {},
  21885. lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n';
  21886. if (ast.comments) {
  21887. for (i = 0; i < ast.comments.length; i++) {
  21888. commentNode = ast.comments[i];
  21889. if (commentNode.type === 'Line') {
  21890. value = '//' + commentNode.value + lineEnd;
  21891. refNode = commentNode;
  21892. if (i + 1 >= ast.comments.length) {
  21893. value += lineEnd;
  21894. } else {
  21895. //Look for immediately adjacent single line comments
  21896. //since it could from a multiple line comment made out
  21897. //of single line comments. Like this comment.
  21898. for (j = i + 1; j < ast.comments.length; j++) {
  21899. subNode = ast.comments[j];
  21900. if (subNode.type === 'Line' &&
  21901. subNode.range[0] === refNode.range[1] + 1) {
  21902. //Adjacent single line comment. Collect it.
  21903. value += '//' + subNode.value + lineEnd;
  21904. refNode = subNode;
  21905. } else {
  21906. //No more single line comment blocks. Break out
  21907. //and continue outer looping.
  21908. break;
  21909. }
  21910. }
  21911. value += lineEnd;
  21912. i = j - 1;
  21913. }
  21914. } else {
  21915. value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd;
  21916. }
  21917. if (!existsMap[value] && (value.indexOf('license') !== -1 ||
  21918. (commentNode.type === 'Block' &&
  21919. value.indexOf('/*!') === 0) ||
  21920. value.indexOf('opyright') !== -1 ||
  21921. value.indexOf('(c)') !== -1)) {
  21922. result += value;
  21923. existsMap[value] = true;
  21924. }
  21925. }
  21926. }
  21927. return result;
  21928. };
  21929. return parse;
  21930. });
  21931. /**
  21932. * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  21933. * Available via the MIT or new BSD license.
  21934. * see: http://github.com/jrburke/requirejs for details
  21935. */
  21936. /*global define */
  21937. define('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'],
  21938. function (esprima, parse, logger, lang) {
  21939. 'use strict';
  21940. var transform,
  21941. baseIndentRegExp = /^([ \t]+)/,
  21942. indentRegExp = /\{[\r\n]+([ \t]+)/,
  21943. keyRegExp = /^[_A-Za-z]([A-Za-z\d_]*)$/,
  21944. bulkIndentRegExps = {
  21945. '\n': /\n/g,
  21946. '\r\n': /\r\n/g
  21947. };
  21948. function applyIndent(str, indent, lineReturn) {
  21949. var regExp = bulkIndentRegExps[lineReturn];
  21950. return str.replace(regExp, '$&' + indent);
  21951. }
  21952. transform = {
  21953. toTransport: function (namespace, moduleName, path, contents, onFound, options) {
  21954. options = options || {};
  21955. var astRoot, contentLines, modLine,
  21956. foundAnon,
  21957. scanCount = 0,
  21958. scanReset = false,
  21959. defineInfos = [],
  21960. applySourceUrl = function (contents) {
  21961. if (options.useSourceUrl) {
  21962. contents = 'eval("' + lang.jsEscape(contents) +
  21963. '\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') +
  21964. path +
  21965. '");\n';
  21966. }
  21967. return contents;
  21968. };
  21969. try {
  21970. astRoot = esprima.parse(contents, {
  21971. loc: true
  21972. });
  21973. } catch (e) {
  21974. logger.trace('toTransport skipping ' + path + ': ' +
  21975. e.toString());
  21976. return contents;
  21977. }
  21978. //Find the define calls and their position in the files.
  21979. parse.traverse(astRoot, function (node) {
  21980. var args, firstArg, firstArgLoc, factoryNode,
  21981. needsId, depAction, foundId, init,
  21982. sourceUrlData, range,
  21983. namespaceExists = false;
  21984. // If a bundle script with a define declaration, do not
  21985. // parse any further at this level. Likely a built layer
  21986. // by some other tool.
  21987. if (node.type === 'VariableDeclarator' &&
  21988. node.id && node.id.name === 'define' &&
  21989. node.id.type === 'Identifier') {
  21990. init = node.init;
  21991. if (init && init.callee &&
  21992. init.callee.type === 'CallExpression' &&
  21993. init.callee.callee &&
  21994. init.callee.callee.type === 'Identifier' &&
  21995. init.callee.callee.name === 'require' &&
  21996. init.callee.arguments && init.callee.arguments.length === 1 &&
  21997. init.callee.arguments[0].type === 'Literal' &&
  21998. init.callee.arguments[0].value &&
  21999. init.callee.arguments[0].value.indexOf('amdefine') !== -1) {
  22000. // the var define = require('amdefine')(module) case,
  22001. // keep going in that case.
  22002. } else {
  22003. return false;
  22004. }
  22005. }
  22006. namespaceExists = namespace &&
  22007. node.type === 'CallExpression' &&
  22008. node.callee && node.callee.object &&
  22009. node.callee.object.type === 'Identifier' &&
  22010. node.callee.object.name === namespace &&
  22011. node.callee.property.type === 'Identifier' &&
  22012. node.callee.property.name === 'define';
  22013. if (namespaceExists || parse.isDefineNodeWithArgs(node)) {
  22014. //The arguments are where its at.
  22015. args = node.arguments;
  22016. if (!args || !args.length) {
  22017. return;
  22018. }
  22019. firstArg = args[0];
  22020. firstArgLoc = firstArg.loc;
  22021. if (args.length === 1) {
  22022. if (firstArg.type === 'Identifier') {
  22023. //The define(factory) case, but
  22024. //only allow it if one Identifier arg,
  22025. //to limit impact of false positives.
  22026. needsId = true;
  22027. depAction = 'empty';
  22028. } else if (parse.isFnExpression(firstArg)) {
  22029. //define(function(){})
  22030. factoryNode = firstArg;
  22031. needsId = true;
  22032. depAction = 'scan';
  22033. } else if (firstArg.type === 'ObjectExpression') {
  22034. //define({});
  22035. needsId = true;
  22036. depAction = 'skip';
  22037. } else if (firstArg.type === 'Literal' &&
  22038. typeof firstArg.value === 'number') {
  22039. //define('12345');
  22040. needsId = true;
  22041. depAction = 'skip';
  22042. } else if (firstArg.type === 'UnaryExpression' &&
  22043. firstArg.operator === '-' &&
  22044. firstArg.argument &&
  22045. firstArg.argument.type === 'Literal' &&
  22046. typeof firstArg.argument.value === 'number') {
  22047. //define('-12345');
  22048. needsId = true;
  22049. depAction = 'skip';
  22050. } else if (firstArg.type === 'MemberExpression' &&
  22051. firstArg.object &&
  22052. firstArg.property &&
  22053. firstArg.property.type === 'Identifier') {
  22054. //define(this.key);
  22055. needsId = true;
  22056. depAction = 'empty';
  22057. }
  22058. } else if (firstArg.type === 'ArrayExpression') {
  22059. //define([], ...);
  22060. needsId = true;
  22061. depAction = 'skip';
  22062. } else if (firstArg.type === 'Literal' &&
  22063. typeof firstArg.value === 'string') {
  22064. //define('string', ....)
  22065. //Already has an ID.
  22066. needsId = false;
  22067. if (args.length === 2 &&
  22068. parse.isFnExpression(args[1])) {
  22069. //Needs dependency scanning.
  22070. factoryNode = args[1];
  22071. depAction = 'scan';
  22072. } else {
  22073. depAction = 'skip';
  22074. }
  22075. } else {
  22076. //Unknown define entity, keep looking, even
  22077. //in the subtree for this node.
  22078. return;
  22079. }
  22080. range = {
  22081. foundId: foundId,
  22082. needsId: needsId,
  22083. depAction: depAction,
  22084. namespaceExists: namespaceExists,
  22085. node: node,
  22086. defineLoc: node.loc,
  22087. firstArgLoc: firstArgLoc,
  22088. factoryNode: factoryNode,
  22089. sourceUrlData: sourceUrlData
  22090. };
  22091. //Only transform ones that do not have IDs. If it has an
  22092. //ID but no dependency array, assume it is something like
  22093. //a phonegap implementation, that has its own internal
  22094. //define that cannot handle dependency array constructs,
  22095. //and if it is a named module, then it means it has been
  22096. //set for transport form.
  22097. if (range.needsId) {
  22098. if (foundAnon) {
  22099. logger.trace(path + ' has more than one anonymous ' +
  22100. 'define. May be a built file from another ' +
  22101. 'build system like, Ender. Skipping normalization.');
  22102. defineInfos = [];
  22103. return false;
  22104. } else {
  22105. foundAnon = range;
  22106. defineInfos.push(range);
  22107. }
  22108. } else if (depAction === 'scan') {
  22109. scanCount += 1;
  22110. if (scanCount > 1) {
  22111. //Just go back to an array that just has the
  22112. //anon one, since this is an already optimized
  22113. //file like the phonegap one.
  22114. if (!scanReset) {
  22115. defineInfos = foundAnon ? [foundAnon] : [];
  22116. scanReset = true;
  22117. }
  22118. } else {
  22119. defineInfos.push(range);
  22120. }
  22121. }
  22122. }
  22123. });
  22124. if (!defineInfos.length) {
  22125. return applySourceUrl(contents);
  22126. }
  22127. //Reverse the matches, need to start from the bottom of
  22128. //the file to modify it, so that the ranges are still true
  22129. //further up.
  22130. defineInfos.reverse();
  22131. contentLines = contents.split('\n');
  22132. modLine = function (loc, contentInsertion) {
  22133. var startIndex = loc.start.column,
  22134. //start.line is 1-based, not 0 based.
  22135. lineIndex = loc.start.line - 1,
  22136. line = contentLines[lineIndex];
  22137. contentLines[lineIndex] = line.substring(0, startIndex) +
  22138. contentInsertion +
  22139. line.substring(startIndex,
  22140. line.length);
  22141. };
  22142. defineInfos.forEach(function (info) {
  22143. var deps,
  22144. contentInsertion = '',
  22145. depString = '';
  22146. //Do the modifications "backwards", in other words, start with the
  22147. //one that is farthest down and work up, so that the ranges in the
  22148. //defineInfos still apply. So that means deps, id, then namespace.
  22149. if (info.needsId && moduleName) {
  22150. contentInsertion += "'" + moduleName + "',";
  22151. }
  22152. if (info.depAction === 'scan') {
  22153. deps = parse.getAnonDepsFromNode(info.factoryNode);
  22154. if (deps.length) {
  22155. depString = '[' + deps.map(function (dep) {
  22156. return "'" + dep + "'";
  22157. }) + ']';
  22158. } else {
  22159. depString = '[]';
  22160. }
  22161. depString += ',';
  22162. if (info.factoryNode) {
  22163. //Already have a named module, need to insert the
  22164. //dependencies after the name.
  22165. modLine(info.factoryNode.loc, depString);
  22166. } else {
  22167. contentInsertion += depString;
  22168. }
  22169. }
  22170. if (contentInsertion) {
  22171. modLine(info.firstArgLoc, contentInsertion);
  22172. }
  22173. //Do namespace last so that ui does not mess upthe parenRange
  22174. //used above.
  22175. if (namespace && !info.namespaceExists) {
  22176. modLine(info.defineLoc, namespace + '.');
  22177. }
  22178. //Notify any listener for the found info
  22179. if (onFound) {
  22180. onFound(info);
  22181. }
  22182. });
  22183. contents = contentLines.join('\n');
  22184. return applySourceUrl(contents);
  22185. },
  22186. /**
  22187. * Modify the contents of a require.config/requirejs.config call. This
  22188. * call will LOSE any existing comments that are in the config string.
  22189. *
  22190. * @param {String} fileContents String that may contain a config call
  22191. * @param {Function} onConfig Function called when the first config
  22192. * call is found. It will be passed an Object which is the current
  22193. * config, and the onConfig function should return an Object to use
  22194. * as the config.
  22195. * @return {String} the fileContents with the config changes applied.
  22196. */
  22197. modifyConfig: function (fileContents, onConfig) {
  22198. var details = parse.findConfig(fileContents),
  22199. config = details.config;
  22200. if (config) {
  22201. config = onConfig(config);
  22202. if (config) {
  22203. return transform.serializeConfig(config,
  22204. fileContents,
  22205. details.range[0],
  22206. details.range[1],
  22207. {
  22208. quote: details.quote
  22209. });
  22210. }
  22211. }
  22212. return fileContents;
  22213. },
  22214. serializeConfig: function (config, fileContents, start, end, options) {
  22215. //Calculate base level of indent
  22216. var indent, match, configString, outDentRegExp,
  22217. baseIndent = '',
  22218. startString = fileContents.substring(0, start),
  22219. existingConfigString = fileContents.substring(start, end),
  22220. lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n',
  22221. lastReturnIndex = startString.lastIndexOf('\n');
  22222. //Get the basic amount of indent for the require config call.
  22223. if (lastReturnIndex === -1) {
  22224. lastReturnIndex = 0;
  22225. }
  22226. match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start));
  22227. if (match && match[1]) {
  22228. baseIndent = match[1];
  22229. }
  22230. //Calculate internal indentation for config
  22231. match = indentRegExp.exec(existingConfigString);
  22232. if (match && match[1]) {
  22233. indent = match[1];
  22234. }
  22235. if (!indent || indent.length < baseIndent) {
  22236. indent = ' ';
  22237. } else {
  22238. indent = indent.substring(baseIndent.length);
  22239. }
  22240. outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g');
  22241. configString = transform.objectToString(config, {
  22242. indent: indent,
  22243. lineReturn: lineReturn,
  22244. outDentRegExp: outDentRegExp,
  22245. quote: options && options.quote
  22246. });
  22247. //Add in the base indenting level.
  22248. configString = applyIndent(configString, baseIndent, lineReturn);
  22249. return startString + configString + fileContents.substring(end);
  22250. },
  22251. /**
  22252. * Tries converting a JS object to a string. This will likely suck, and
  22253. * is tailored to the type of config expected in a loader config call.
  22254. * So, hasOwnProperty fields, strings, numbers, arrays and functions,
  22255. * no weird recursively referenced stuff.
  22256. * @param {Object} obj the object to convert
  22257. * @param {Object} options options object with the following values:
  22258. * {String} indent the indentation to use for each level
  22259. * {String} lineReturn the type of line return to use
  22260. * {outDentRegExp} outDentRegExp the regexp to use to outdent functions
  22261. * {String} quote the quote type to use, ' or ". Optional. Default is "
  22262. * @param {String} totalIndent the total indent to print for this level
  22263. * @return {String} a string representation of the object.
  22264. */
  22265. objectToString: function (obj, options, totalIndent) {
  22266. var startBrace, endBrace, nextIndent,
  22267. first = true,
  22268. value = '',
  22269. lineReturn = options.lineReturn,
  22270. indent = options.indent,
  22271. outDentRegExp = options.outDentRegExp,
  22272. quote = options.quote || '"';
  22273. totalIndent = totalIndent || '';
  22274. nextIndent = totalIndent + indent;
  22275. if (obj === null) {
  22276. value = 'null';
  22277. } else if (obj === undefined) {
  22278. value = 'undefined';
  22279. } else if (typeof obj === 'number' || typeof obj === 'boolean') {
  22280. value = obj;
  22281. } else if (typeof obj === 'string') {
  22282. //Use double quotes in case the config may also work as JSON.
  22283. value = quote + lang.jsEscape(obj) + quote;
  22284. } else if (lang.isArray(obj)) {
  22285. lang.each(obj, function (item, i) {
  22286. value += (i !== 0 ? ',' + lineReturn : '' ) +
  22287. nextIndent +
  22288. transform.objectToString(item,
  22289. options,
  22290. nextIndent);
  22291. });
  22292. startBrace = '[';
  22293. endBrace = ']';
  22294. } else if (lang.isFunction(obj) || lang.isRegExp(obj)) {
  22295. //The outdent regexp just helps pretty up the conversion
  22296. //just in node. Rhino strips comments and does a different
  22297. //indent scheme for Function toString, so not really helpful
  22298. //there.
  22299. value = obj.toString().replace(outDentRegExp, '$1');
  22300. } else {
  22301. //An object
  22302. lang.eachProp(obj, function (v, prop) {
  22303. value += (first ? '': ',' + lineReturn) +
  22304. nextIndent +
  22305. (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+
  22306. ': ' +
  22307. transform.objectToString(v,
  22308. options,
  22309. nextIndent);
  22310. first = false;
  22311. });
  22312. startBrace = '{';
  22313. endBrace = '}';
  22314. }
  22315. if (startBrace) {
  22316. value = startBrace +
  22317. lineReturn +
  22318. value +
  22319. lineReturn + totalIndent +
  22320. endBrace;
  22321. }
  22322. return value;
  22323. }
  22324. };
  22325. return transform;
  22326. });
  22327. /**
  22328. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  22329. * Available via the MIT or new BSD license.
  22330. * see: http://github.com/jrburke/requirejs for details
  22331. */
  22332. /*jslint regexp: true, plusplus: true */
  22333. /*global define: false */
  22334. define('pragma', ['parse', 'logger'], function (parse, logger) {
  22335. 'use strict';
  22336. function Temp() {}
  22337. function create(obj, mixin) {
  22338. Temp.prototype = obj;
  22339. var temp = new Temp(), prop;
  22340. //Avoid any extra memory hanging around
  22341. Temp.prototype = null;
  22342. if (mixin) {
  22343. for (prop in mixin) {
  22344. if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) {
  22345. temp[prop] = mixin[prop];
  22346. }
  22347. }
  22348. }
  22349. return temp; // Object
  22350. }
  22351. var pragma = {
  22352. conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/,
  22353. useStrictRegExp: /(^|[^{]\r?\n)['"]use strict['"];/g,
  22354. hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
  22355. configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g,
  22356. nsWrapRegExp: /\/\*requirejs namespace: true \*\//,
  22357. apiDefRegExp: /var requirejs,\s*require,\s*define;/,
  22358. defineCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd/g,
  22359. defineStringCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g,
  22360. defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g,
  22361. defineJQueryRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g,
  22362. defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g,
  22363. defineTernaryRegExp: /typeof\s+define\s*===?\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/,
  22364. amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*'function'\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g,
  22365. removeStrict: function (contents, config) {
  22366. return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '$1');
  22367. },
  22368. namespace: function (fileContents, ns, onLifecycleName) {
  22369. if (ns) {
  22370. //Namespace require/define calls
  22371. fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3(');
  22372. fileContents = parse.renameNamespace(fileContents, ns);
  22373. //Namespace define ternary use:
  22374. fileContents = fileContents.replace(pragma.defineTernaryRegExp,
  22375. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define");
  22376. //Namespace define jquery use:
  22377. fileContents = fileContents.replace(pragma.defineJQueryRegExp,
  22378. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery");
  22379. //Namespace has.js define use:
  22380. fileContents = fileContents.replace(pragma.defineHasRegExp,
  22381. "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd");
  22382. //Namespace define checks.
  22383. //Do these ones last, since they are a subset of the more specific
  22384. //checks above.
  22385. fileContents = fileContents.replace(pragma.defineCheckRegExp,
  22386. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd");
  22387. fileContents = fileContents.replace(pragma.defineStringCheckRegExp,
  22388. "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']");
  22389. fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp,
  22390. "'function' === typeof " + ns + ".define && " + ns + ".define.amd");
  22391. //Check for require.js with the require/define definitions
  22392. if (pragma.apiDefRegExp.test(fileContents) &&
  22393. fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) {
  22394. //Wrap the file contents in a typeof check, and a function
  22395. //to contain the API globals.
  22396. fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" +
  22397. "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' +
  22398. fileContents +
  22399. "\n" +
  22400. ns + ".requirejs = requirejs;" +
  22401. ns + ".require = require;" +
  22402. ns + ".define = define;\n" +
  22403. "}\n}());";
  22404. }
  22405. //Finally, if the file wants a special wrapper because it ties
  22406. //in to the requirejs internals in a way that would not fit
  22407. //the above matches, do that. Look for /*requirejs namespace: true*/
  22408. if (pragma.nsWrapRegExp.test(fileContents)) {
  22409. //Remove the pragma.
  22410. fileContents = fileContents.replace(pragma.nsWrapRegExp, '');
  22411. //Alter the contents.
  22412. fileContents = '(function () {\n' +
  22413. 'var require = ' + ns + '.require,' +
  22414. 'requirejs = ' + ns + '.requirejs,' +
  22415. 'define = ' + ns + '.define;\n' +
  22416. fileContents +
  22417. '\n}());';
  22418. }
  22419. }
  22420. return fileContents;
  22421. },
  22422. /**
  22423. * processes the fileContents for some //>> conditional statements
  22424. */
  22425. process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) {
  22426. /*jslint evil: true */
  22427. var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,
  22428. matches, type, marker, condition, isTrue, endRegExp, endMatches,
  22429. endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,
  22430. i, dep, moduleName, collectorMod,
  22431. lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,
  22432. //Legacy arg defined to help in dojo conversion script. Remove later
  22433. //when dojo no longer needs conversion:
  22434. kwArgs = pragmas;
  22435. //Mix in a specific lifecycle scoped object, to allow targeting
  22436. //some pragmas/has tests to only when files are saved, or at different
  22437. //lifecycle events. Do not bother with kwArgs in this section, since
  22438. //the old dojo kwArgs were for all points in the build lifecycle.
  22439. if (onLifecycleName) {
  22440. lifecyclePragmas = config['pragmas' + onLifecycleName];
  22441. lifecycleHas = config['has' + onLifecycleName];
  22442. if (lifecyclePragmas) {
  22443. pragmas = create(pragmas || {}, lifecyclePragmas);
  22444. }
  22445. if (lifecycleHas) {
  22446. hasConfig = create(hasConfig || {}, lifecycleHas);
  22447. }
  22448. }
  22449. //Replace has references if desired
  22450. if (hasConfig) {
  22451. fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {
  22452. if (hasConfig.hasOwnProperty(test)) {
  22453. return !!hasConfig[test];
  22454. }
  22455. return match;
  22456. });
  22457. }
  22458. if (!config.skipPragmas) {
  22459. while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) {
  22460. //Found a conditional. Get the conditional line.
  22461. lineEndIndex = fileContents.indexOf("\n", foundIndex);
  22462. if (lineEndIndex === -1) {
  22463. lineEndIndex = fileContents.length - 1;
  22464. }
  22465. //Increment startIndex past the line so the next conditional search can be done.
  22466. startIndex = lineEndIndex + 1;
  22467. //Break apart the conditional.
  22468. conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);
  22469. matches = conditionLine.match(pragma.conditionalRegExp);
  22470. if (matches) {
  22471. type = matches[1];
  22472. marker = matches[2];
  22473. condition = matches[3];
  22474. isTrue = false;
  22475. //See if the condition is true.
  22476. try {
  22477. isTrue = !!eval("(" + condition + ")");
  22478. } catch (e) {
  22479. throw "Error in file: " +
  22480. fileName +
  22481. ". Conditional comment: " +
  22482. conditionLine +
  22483. " failed with this error: " + e;
  22484. }
  22485. //Find the endpoint marker.
  22486. endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g");
  22487. endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));
  22488. if (endMatches) {
  22489. endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;
  22490. //Find the next line return based on the match position.
  22491. lineEndIndex = fileContents.indexOf("\n", endMarkerIndex);
  22492. if (lineEndIndex === -1) {
  22493. lineEndIndex = fileContents.length - 1;
  22494. }
  22495. //Should we include the segment?
  22496. shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue));
  22497. //Remove the conditional comments, and optionally remove the content inside
  22498. //the conditional comments.
  22499. startLength = startIndex - foundIndex;
  22500. fileContents = fileContents.substring(0, foundIndex) +
  22501. (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") +
  22502. fileContents.substring(lineEndIndex + 1, fileContents.length);
  22503. //Move startIndex to foundIndex, since that is the new position in the file
  22504. //where we need to look for more conditionals in the next while loop pass.
  22505. startIndex = foundIndex;
  22506. } else {
  22507. throw "Error in file: " +
  22508. fileName +
  22509. ". Cannot find end marker for conditional comment: " +
  22510. conditionLine;
  22511. }
  22512. }
  22513. }
  22514. }
  22515. //If need to find all plugin resources to optimize, do that now,
  22516. //before namespacing, since the namespacing will change the API
  22517. //names.
  22518. //If there is a plugin collector, scan the file for plugin resources.
  22519. if (config.optimizeAllPluginResources && pluginCollector) {
  22520. try {
  22521. deps = parse.findDependencies(fileName, fileContents);
  22522. if (deps.length) {
  22523. for (i = 0; i < deps.length; i++) {
  22524. dep = deps[i];
  22525. if (dep.indexOf('!') !== -1) {
  22526. moduleName = dep.split('!')[0];
  22527. collectorMod = pluginCollector[moduleName];
  22528. if (!collectorMod) {
  22529. collectorMod = pluginCollector[moduleName] = [];
  22530. }
  22531. collectorMod.push(dep);
  22532. }
  22533. }
  22534. }
  22535. } catch (eDep) {
  22536. logger.error('Parse error looking for plugin resources in ' +
  22537. fileName + ', skipping.');
  22538. }
  22539. }
  22540. //Strip amdefine use for node-shared modules.
  22541. if (!config.keepAmdefine) {
  22542. fileContents = fileContents.replace(pragma.amdefineRegExp, '');
  22543. }
  22544. //Do namespacing
  22545. if (onLifecycleName === 'OnSave' && config.namespace) {
  22546. fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);
  22547. }
  22548. return pragma.removeStrict(fileContents, config);
  22549. }
  22550. };
  22551. return pragma;
  22552. });
  22553. if(env === 'browser') {
  22554. /**
  22555. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  22556. * Available via the MIT or new BSD license.
  22557. * see: http://github.com/jrburke/requirejs for details
  22558. */
  22559. /*jslint strict: false */
  22560. /*global define: false */
  22561. define('browser/optimize', {});
  22562. }
  22563. if(env === 'node') {
  22564. /**
  22565. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  22566. * Available via the MIT or new BSD license.
  22567. * see: http://github.com/jrburke/requirejs for details
  22568. */
  22569. /*jslint strict: false */
  22570. /*global define: false */
  22571. define('node/optimize', {});
  22572. }
  22573. if(env === 'rhino') {
  22574. /**
  22575. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  22576. * Available via the MIT or new BSD license.
  22577. * see: http://github.com/jrburke/requirejs for details
  22578. */
  22579. /*jslint sloppy: true, plusplus: true */
  22580. /*global define, java, Packages, com */
  22581. define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) {
  22582. //Add .reduce to Rhino so UglifyJS can run in Rhino,
  22583. //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
  22584. //but rewritten for brevity, and to be good enough for use by UglifyJS.
  22585. if (!Array.prototype.reduce) {
  22586. Array.prototype.reduce = function (fn /*, initialValue */) {
  22587. var i = 0,
  22588. length = this.length,
  22589. accumulator;
  22590. if (arguments.length >= 2) {
  22591. accumulator = arguments[1];
  22592. } else {
  22593. if (length) {
  22594. while (!(i in this)) {
  22595. i++;
  22596. }
  22597. accumulator = this[i++];
  22598. }
  22599. }
  22600. for (; i < length; i++) {
  22601. if (i in this) {
  22602. accumulator = fn.call(undefined, accumulator, this[i], i, this);
  22603. }
  22604. }
  22605. return accumulator;
  22606. };
  22607. }
  22608. var JSSourceFilefromCode, optimize,
  22609. mapRegExp = /"file":"[^"]+"/;
  22610. //Bind to Closure compiler, but if it is not available, do not sweat it.
  22611. try {
  22612. // Try older closure compiler that worked on Java 6
  22613. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  22614. } catch (e) {
  22615. try {
  22616. // Try for newer closure compiler that needs Java 7+
  22617. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.SourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  22618. } catch (e) {}
  22619. }
  22620. //Helper for closure compiler, because of weird Java-JavaScript interactions.
  22621. function closurefromCode(filename, content) {
  22622. return JSSourceFilefromCode.invoke(null, [filename, content]);
  22623. }
  22624. function getFileWriter(fileName, encoding) {
  22625. var outFile = new java.io.File(fileName), outWriter, parentDir;
  22626. parentDir = outFile.getAbsoluteFile().getParentFile();
  22627. if (!parentDir.exists()) {
  22628. if (!parentDir.mkdirs()) {
  22629. throw "Could not create directory: " + parentDir.getAbsolutePath();
  22630. }
  22631. }
  22632. if (encoding) {
  22633. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  22634. } else {
  22635. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  22636. }
  22637. return new java.io.BufferedWriter(outWriter);
  22638. }
  22639. optimize = {
  22640. closure: function (fileName, fileContents, outFileName, keepLines, config) {
  22641. config = config || {};
  22642. var result, mappings, optimized, compressed, baseName, writer,
  22643. outBaseName, outFileNameMap, outFileNameMapContent,
  22644. srcOutFileName, concatNameMap,
  22645. jscomp = Packages.com.google.javascript.jscomp,
  22646. flags = Packages.com.google.common.flags,
  22647. //Set up source input
  22648. jsSourceFile = closurefromCode(String(fileName), String(fileContents)),
  22649. sourceListArray = new java.util.ArrayList(),
  22650. options, option, FLAG_compilation_level, compiler,
  22651. Compiler = Packages.com.google.javascript.jscomp.Compiler,
  22652. CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner;
  22653. logger.trace("Minifying file: " + fileName);
  22654. baseName = (new java.io.File(fileName)).getName();
  22655. //Set up options
  22656. options = new jscomp.CompilerOptions();
  22657. for (option in config.CompilerOptions) {
  22658. // options are false by default and jslint wanted an if statement in this for loop
  22659. if (config.CompilerOptions[option]) {
  22660. options[option] = config.CompilerOptions[option];
  22661. }
  22662. }
  22663. options.prettyPrint = keepLines || options.prettyPrint;
  22664. FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];
  22665. FLAG_compilation_level.setOptionsForCompilationLevel(options);
  22666. if (config.generateSourceMaps) {
  22667. mappings = new java.util.ArrayList();
  22668. mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js"));
  22669. options.setSourceMapLocationMappings(mappings);
  22670. options.setSourceMapOutputPath(fileName + ".map");
  22671. }
  22672. //Trigger the compiler
  22673. Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);
  22674. compiler = new Compiler();
  22675. //fill the sourceArrrayList; we need the ArrayList because the only overload of compile
  22676. //accepting the getDefaultExterns return value (a List) also wants the sources as a List
  22677. sourceListArray.add(jsSourceFile);
  22678. result = compiler.compile(CommandLineRunner.getDefaultExterns(), sourceListArray, options);
  22679. if (result.success) {
  22680. optimized = String(compiler.toSource());
  22681. if (config.generateSourceMaps && result.sourceMap && outFileName) {
  22682. outBaseName = (new java.io.File(outFileName)).getName();
  22683. srcOutFileName = outFileName + ".src.js";
  22684. outFileNameMap = outFileName + ".map";
  22685. //If previous .map file exists, move it to the ".src.js"
  22686. //location. Need to update the sourceMappingURL part in the
  22687. //src.js file too.
  22688. if (file.exists(outFileNameMap)) {
  22689. concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map');
  22690. file.saveFile(concatNameMap, file.readFile(outFileNameMap));
  22691. file.saveFile(srcOutFileName,
  22692. fileContents.replace(/\/\# sourceMappingURL=(.+).map/,
  22693. '/# sourceMappingURL=$1.src.js.map'));
  22694. } else {
  22695. file.saveUtf8File(srcOutFileName, fileContents);
  22696. }
  22697. writer = getFileWriter(outFileNameMap, "utf-8");
  22698. result.sourceMap.appendTo(writer, outFileName);
  22699. writer.close();
  22700. //Not sure how better to do this, but right now the .map file
  22701. //leaks the full OS path in the "file" property. Manually
  22702. //modify it to not do that.
  22703. file.saveFile(outFileNameMap,
  22704. file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"'));
  22705. fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map";
  22706. } else {
  22707. fileContents = optimized;
  22708. }
  22709. return fileContents;
  22710. } else {
  22711. throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');
  22712. }
  22713. return fileContents;
  22714. }
  22715. };
  22716. return optimize;
  22717. });
  22718. }
  22719. if(env === 'xpconnect') {
  22720. define('xpconnect/optimize', {});
  22721. }
  22722. /**
  22723. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  22724. * Available via the MIT or new BSD license.
  22725. * see: http://github.com/jrburke/requirejs for details
  22726. */
  22727. /*jslint plusplus: true, nomen: true, regexp: true */
  22728. /*global define: false */
  22729. define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',
  22730. 'pragma', 'uglifyjs/index', 'uglifyjs2',
  22731. 'source-map'],
  22732. function (lang, logger, envOptimize, file, parse,
  22733. pragma, uglify, uglify2,
  22734. sourceMap) {
  22735. 'use strict';
  22736. var optimize,
  22737. cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig,
  22738. cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g,
  22739. cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g,
  22740. protocolRegExp = /^\w+:/,
  22741. SourceMapGenerator = sourceMap.SourceMapGenerator,
  22742. SourceMapConsumer =sourceMap.SourceMapConsumer;
  22743. /**
  22744. * If an URL from a CSS url value contains start/end quotes, remove them.
  22745. * This is not done in the regexp, since my regexp fu is not that strong,
  22746. * and the CSS spec allows for ' and " in the URL if they are backslash escaped.
  22747. * @param {String} url
  22748. */
  22749. function cleanCssUrlQuotes(url) {
  22750. //Make sure we are not ending in whitespace.
  22751. //Not very confident of the css regexps above that there will not be ending
  22752. //whitespace.
  22753. url = url.replace(/\s+$/, "");
  22754. if (url.charAt(0) === "'" || url.charAt(0) === "\"") {
  22755. url = url.substring(1, url.length - 1);
  22756. }
  22757. return url;
  22758. }
  22759. function fixCssUrlPaths(fileName, path, contents, cssPrefix) {
  22760. return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {
  22761. var firstChar, hasProtocol, parts, i,
  22762. fixedUrlMatch = cleanCssUrlQuotes(urlMatch);
  22763. fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");
  22764. //Only do the work for relative URLs. Skip things that start with / or #, or have
  22765. //a protocol.
  22766. firstChar = fixedUrlMatch.charAt(0);
  22767. hasProtocol = protocolRegExp.test(fixedUrlMatch);
  22768. if (firstChar !== "/" && firstChar !== "#" && !hasProtocol) {
  22769. //It is a relative URL, tack on the cssPrefix and path prefix
  22770. urlMatch = cssPrefix + path + fixedUrlMatch;
  22771. } else if (!hasProtocol) {
  22772. logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch);
  22773. }
  22774. //Collapse .. and .
  22775. parts = urlMatch.split("/");
  22776. for (i = parts.length - 1; i > 0; i--) {
  22777. if (parts[i] === ".") {
  22778. parts.splice(i, 1);
  22779. } else if (parts[i] === "..") {
  22780. if (i !== 0 && parts[i - 1] !== "..") {
  22781. parts.splice(i - 1, 2);
  22782. i -= 1;
  22783. }
  22784. }
  22785. }
  22786. return "url(" + parts.join("/") + ")";
  22787. });
  22788. }
  22789. /**
  22790. * Inlines nested stylesheets that have @import calls in them.
  22791. * @param {String} fileName the file name
  22792. * @param {String} fileContents the file contents
  22793. * @param {String} cssImportIgnore comma delimited string of files to ignore
  22794. * @param {String} cssPrefix string to be prefixed before relative URLs
  22795. * @param {Object} included an object used to track the files already imported
  22796. */
  22797. function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) {
  22798. //Find the last slash in the name.
  22799. fileName = fileName.replace(lang.backSlashRegExp, "/");
  22800. var endIndex = fileName.lastIndexOf("/"),
  22801. //Make a file path based on the last slash.
  22802. //If no slash, so must be just a file name. Use empty string then.
  22803. filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "",
  22804. //store a list of merged files
  22805. importList = [],
  22806. skippedList = [];
  22807. //First make a pass by removing any commented out @import calls.
  22808. fileContents = fileContents.replace(cssCommentImportRegExp, '');
  22809. //Make sure we have a delimited ignore list to make matching faster
  22810. if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {
  22811. cssImportIgnore += ",";
  22812. }
  22813. fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {
  22814. //Only process media type "all" or empty media type rules.
  22815. if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {
  22816. skippedList.push(fileName);
  22817. return fullMatch;
  22818. }
  22819. importFileName = cleanCssUrlQuotes(importFileName);
  22820. //Ignore the file import if it is part of an ignore list.
  22821. if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {
  22822. return fullMatch;
  22823. }
  22824. //Make sure we have a unix path for the rest of the operation.
  22825. importFileName = importFileName.replace(lang.backSlashRegExp, "/");
  22826. try {
  22827. //if a relative path, then tack on the filePath.
  22828. //If it is not a relative path, then the readFile below will fail,
  22829. //and we will just skip that import.
  22830. var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,
  22831. importContents = file.readFile(fullImportFileName),
  22832. importEndIndex, importPath, flat;
  22833. //Skip the file if it has already been included.
  22834. if (included[fullImportFileName]) {
  22835. return '';
  22836. }
  22837. included[fullImportFileName] = true;
  22838. //Make sure to flatten any nested imports.
  22839. flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);
  22840. importContents = flat.fileContents;
  22841. if (flat.importList.length) {
  22842. importList.push.apply(importList, flat.importList);
  22843. }
  22844. if (flat.skippedList.length) {
  22845. skippedList.push.apply(skippedList, flat.skippedList);
  22846. }
  22847. //Make the full import path
  22848. importEndIndex = importFileName.lastIndexOf("/");
  22849. //Make a file path based on the last slash.
  22850. //If no slash, so must be just a file name. Use empty string then.
  22851. importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";
  22852. //fix url() on relative import (#5)
  22853. importPath = importPath.replace(/^\.\//, '');
  22854. //Modify URL paths to match the path represented by this file.
  22855. importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix);
  22856. importList.push(fullImportFileName);
  22857. return importContents;
  22858. } catch (e) {
  22859. logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName);
  22860. return fullMatch;
  22861. }
  22862. });
  22863. if (cssPrefix && topLevel) {
  22864. //Modify URL paths to match the path represented by this file.
  22865. fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix);
  22866. }
  22867. return {
  22868. importList : importList,
  22869. skippedList: skippedList,
  22870. fileContents : fileContents
  22871. };
  22872. }
  22873. optimize = {
  22874. /**
  22875. * Optimizes a file that contains JavaScript content. Optionally collects
  22876. * plugin resources mentioned in a file, and then passes the content
  22877. * through an minifier if one is specified via config.optimize.
  22878. *
  22879. * @param {String} fileName the name of the file to optimize
  22880. * @param {String} fileContents the contents to optimize. If this is
  22881. * a null value, then fileName will be used to read the fileContents.
  22882. * @param {String} outFileName the name of the file to use for the
  22883. * saved optimized content.
  22884. * @param {Object} config the build config object.
  22885. * @param {Array} [pluginCollector] storage for any plugin resources
  22886. * found.
  22887. */
  22888. jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {
  22889. if (!fileContents) {
  22890. fileContents = file.readFile(fileName);
  22891. }
  22892. fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);
  22893. file.saveUtf8File(outFileName, fileContents);
  22894. },
  22895. /**
  22896. * Optimizes a file that contains JavaScript content. Optionally collects
  22897. * plugin resources mentioned in a file, and then passes the content
  22898. * through an minifier if one is specified via config.optimize.
  22899. *
  22900. * @param {String} fileName the name of the file that matches the
  22901. * fileContents.
  22902. * @param {String} fileContents the string of JS to optimize.
  22903. * @param {Object} [config] the build config object.
  22904. * @param {Array} [pluginCollector] storage for any plugin resources
  22905. * found.
  22906. */
  22907. js: function (fileName, fileContents, outFileName, config, pluginCollector) {
  22908. var optFunc, optConfig,
  22909. parts = (String(config.optimize)).split('.'),
  22910. optimizerName = parts[0],
  22911. keepLines = parts[1] === 'keepLines',
  22912. licenseContents = '';
  22913. config = config || {};
  22914. //Apply pragmas/namespace renaming
  22915. fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);
  22916. //Optimize the JS files if asked.
  22917. if (optimizerName && optimizerName !== 'none') {
  22918. optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];
  22919. if (!optFunc) {
  22920. throw new Error('optimizer with name of "' +
  22921. optimizerName +
  22922. '" not found for this environment');
  22923. }
  22924. optConfig = config[optimizerName] || {};
  22925. if (config.generateSourceMaps) {
  22926. optConfig.generateSourceMaps = !!config.generateSourceMaps;
  22927. optConfig._buildSourceMap = config._buildSourceMap;
  22928. }
  22929. try {
  22930. if (config.preserveLicenseComments) {
  22931. //Pull out any license comments for prepending after optimization.
  22932. try {
  22933. licenseContents = parse.getLicenseComments(fileName, fileContents);
  22934. } catch (e) {
  22935. throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString());
  22936. }
  22937. }
  22938. fileContents = licenseContents + optFunc(fileName,
  22939. fileContents,
  22940. outFileName,
  22941. keepLines,
  22942. optConfig);
  22943. if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) {
  22944. config._buildSourceMap = optConfig._buildSourceMap;
  22945. }
  22946. } catch (e) {
  22947. if (config.throwWhen && config.throwWhen.optimize) {
  22948. throw e;
  22949. } else {
  22950. logger.error(e);
  22951. }
  22952. }
  22953. } else {
  22954. if (config._buildSourceMap) {
  22955. config._buildSourceMap = null;
  22956. }
  22957. }
  22958. return fileContents;
  22959. },
  22960. /**
  22961. * Optimizes one CSS file, inlining @import calls, stripping comments, and
  22962. * optionally removes line returns.
  22963. * @param {String} fileName the path to the CSS file to optimize
  22964. * @param {String} outFileName the path to save the optimized file.
  22965. * @param {Object} config the config object with the optimizeCss and
  22966. * cssImportIgnore options.
  22967. */
  22968. cssFile: function (fileName, outFileName, config) {
  22969. //Read in the file. Make sure we have a JS string.
  22970. var originalFileContents = file.readFile(fileName),
  22971. flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true),
  22972. //Do not use the flattened CSS if there was one that was skipped.
  22973. fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,
  22974. startIndex, endIndex, buildText, comment;
  22975. if (flat.skippedList.length) {
  22976. logger.warn('Cannot inline @imports for ' + fileName +
  22977. ',\nthe following files had media queries in them:\n' +
  22978. flat.skippedList.join('\n'));
  22979. }
  22980. //Do comment removal.
  22981. try {
  22982. if (config.optimizeCss.indexOf(".keepComments") === -1) {
  22983. startIndex = 0;
  22984. //Get rid of comments.
  22985. while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) {
  22986. endIndex = fileContents.indexOf("*/", startIndex + 2);
  22987. if (endIndex === -1) {
  22988. throw "Improper comment in CSS file: " + fileName;
  22989. }
  22990. comment = fileContents.substring(startIndex, endIndex);
  22991. if (config.preserveLicenseComments &&
  22992. (comment.indexOf('license') !== -1 ||
  22993. comment.indexOf('opyright') !== -1 ||
  22994. comment.indexOf('(c)') !== -1)) {
  22995. //Keep the comment, just increment the startIndex
  22996. startIndex = endIndex;
  22997. } else {
  22998. fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);
  22999. startIndex = 0;
  23000. }
  23001. }
  23002. }
  23003. //Get rid of newlines.
  23004. if (config.optimizeCss.indexOf(".keepLines") === -1) {
  23005. fileContents = fileContents.replace(/[\r\n]/g, " ");
  23006. fileContents = fileContents.replace(/\s+/g, " ");
  23007. fileContents = fileContents.replace(/\{\s/g, "{");
  23008. fileContents = fileContents.replace(/\s\}/g, "}");
  23009. } else {
  23010. //Remove multiple empty lines.
  23011. fileContents = fileContents.replace(/(\r\n)+/g, "\r\n");
  23012. fileContents = fileContents.replace(/(\n)+/g, "\n");
  23013. }
  23014. //Remove unnecessary whitespace
  23015. if (config.optimizeCss.indexOf(".keepWhitespace") === -1) {
  23016. //Remove leading and trailing whitespace from lines
  23017. fileContents = fileContents.replace(/^[ \t]+/gm, "");
  23018. fileContents = fileContents.replace(/[ \t]+$/gm, "");
  23019. //Remove whitespace after semicolon, colon, curly brackets and commas
  23020. fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1");
  23021. //Remove whitespace before opening curly brackets
  23022. fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1");
  23023. //Truncate double whitespace
  23024. fileContents = fileContents.replace(/([ \t])+/g, "$1");
  23025. //Remove empty lines
  23026. fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,'');
  23027. }
  23028. } catch (e) {
  23029. fileContents = originalFileContents;
  23030. logger.error("Could not optimized CSS file: " + fileName + ", error: " + e);
  23031. }
  23032. file.saveUtf8File(outFileName, fileContents);
  23033. //text output to stdout and/or written to build.txt file
  23034. buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n";
  23035. flat.importList.push(fileName);
  23036. buildText += flat.importList.map(function(path){
  23037. return path.replace(config.dir, "");
  23038. }).join("\n");
  23039. return {
  23040. importList: flat.importList,
  23041. buildText: buildText +"\n"
  23042. };
  23043. },
  23044. /**
  23045. * Optimizes CSS files, inlining @import calls, stripping comments, and
  23046. * optionally removes line returns.
  23047. * @param {String} startDir the path to the top level directory
  23048. * @param {Object} config the config object with the optimizeCss and
  23049. * cssImportIgnore options.
  23050. */
  23051. css: function (startDir, config) {
  23052. var buildText = "",
  23053. importList = [],
  23054. shouldRemove = config.dir && config.removeCombined,
  23055. i, fileName, result, fileList;
  23056. if (config.optimizeCss.indexOf("standard") !== -1) {
  23057. fileList = file.getFilteredFileList(startDir, /\.css$/, true);
  23058. if (fileList) {
  23059. for (i = 0; i < fileList.length; i++) {
  23060. fileName = fileList[i];
  23061. logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName);
  23062. result = optimize.cssFile(fileName, fileName, config);
  23063. buildText += result.buildText;
  23064. if (shouldRemove) {
  23065. result.importList.pop();
  23066. importList = importList.concat(result.importList);
  23067. }
  23068. }
  23069. }
  23070. if (shouldRemove) {
  23071. importList.forEach(function (path) {
  23072. if (file.exists(path)) {
  23073. file.deleteFile(path);
  23074. }
  23075. });
  23076. }
  23077. }
  23078. return buildText;
  23079. },
  23080. optimizers: {
  23081. uglify: function (fileName, fileContents, outFileName, keepLines, config) {
  23082. var parser = uglify.parser,
  23083. processor = uglify.uglify,
  23084. ast, errMessage, errMatch;
  23085. config = config || {};
  23086. logger.trace("Uglifying file: " + fileName);
  23087. try {
  23088. ast = parser.parse(fileContents, config.strict_semicolons);
  23089. if (config.no_mangle !== true) {
  23090. ast = processor.ast_mangle(ast, config);
  23091. }
  23092. ast = processor.ast_squeeze(ast, config);
  23093. fileContents = processor.gen_code(ast, config);
  23094. if (config.max_line_length) {
  23095. fileContents = processor.split_lines(fileContents, config.max_line_length);
  23096. }
  23097. //Add trailing semicolon to match uglifyjs command line version
  23098. fileContents += ';';
  23099. } catch (e) {
  23100. errMessage = e.toString();
  23101. errMatch = /\nError(\r)?\n/.exec(errMessage);
  23102. if (errMatch) {
  23103. errMessage = errMessage.substring(0, errMatch.index);
  23104. }
  23105. throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + errMessage);
  23106. }
  23107. return fileContents;
  23108. },
  23109. uglify2: function (fileName, fileContents, outFileName, keepLines, config) {
  23110. var result, existingMap, resultMap, finalMap, sourceIndex,
  23111. uconfig = {},
  23112. existingMapPath = outFileName + '.map',
  23113. baseName = fileName && fileName.split('/').pop();
  23114. config = config || {};
  23115. lang.mixin(uconfig, config, true);
  23116. uconfig.fromString = true;
  23117. if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) {
  23118. uconfig.outSourceMap = baseName;
  23119. if (config._buildSourceMap) {
  23120. existingMap = JSON.parse(config._buildSourceMap);
  23121. uconfig.inSourceMap = existingMap;
  23122. } else if (file.exists(existingMapPath)) {
  23123. uconfig.inSourceMap = existingMapPath;
  23124. existingMap = JSON.parse(file.readFile(existingMapPath));
  23125. }
  23126. }
  23127. logger.trace("Uglify2 file: " + fileName);
  23128. try {
  23129. //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, '');
  23130. result = uglify2.minify(fileContents, uconfig, baseName + '.src.js');
  23131. if (uconfig.outSourceMap && result.map) {
  23132. resultMap = result.map;
  23133. if (existingMap) {
  23134. resultMap = JSON.parse(resultMap);
  23135. finalMap = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(resultMap));
  23136. finalMap.applySourceMap(new SourceMapConsumer(existingMap));
  23137. resultMap = finalMap.toString();
  23138. } else if (!config._buildSourceMap) {
  23139. file.saveFile(outFileName + '.src.js', fileContents);
  23140. }
  23141. fileContents = result.code;
  23142. if (config._buildSourceMap) {
  23143. config._buildSourceMap = resultMap;
  23144. } else {
  23145. file.saveFile(outFileName + '.map', resultMap);
  23146. fileContents += "\n//# sourceMappingURL=" + baseName + ".map";
  23147. }
  23148. } else {
  23149. fileContents = result.code;
  23150. }
  23151. } catch (e) {
  23152. throw new Error('Cannot uglify2 file: ' + fileName + '. Skipping it. Error is:\n' + e.toString());
  23153. }
  23154. return fileContents;
  23155. }
  23156. }
  23157. };
  23158. return optimize;
  23159. });
  23160. /**
  23161. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  23162. * Available via the MIT or new BSD license.
  23163. * see: http://github.com/jrburke/requirejs for details
  23164. */
  23165. /*
  23166. * This file patches require.js to communicate with the build system.
  23167. */
  23168. //Using sloppy since this uses eval for some code like plugins,
  23169. //which may not be strict mode compliant. So if use strict is used
  23170. //below they will have strict rules applied and may cause an error.
  23171. /*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */
  23172. /*global require, define: true */
  23173. //NOT asking for require as a dependency since the goal is to modify the
  23174. //global require below
  23175. define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function (
  23176. file,
  23177. pragma,
  23178. parse,
  23179. lang,
  23180. logger,
  23181. commonJs,
  23182. prim
  23183. ) {
  23184. var allowRun = true,
  23185. hasProp = lang.hasProp,
  23186. falseProp = lang.falseProp,
  23187. getOwn = lang.getOwn,
  23188. // Used to strip out use strict from toString()'d functions for the
  23189. // shim config since they will explicitly want to not be bound by strict,
  23190. // but some envs, explicitly xpcshell, adds a use strict.
  23191. useStrictRegExp = /['"]use strict['"];/g;
  23192. //Turn off throwing on resolution conflict, that was just an older prim
  23193. //idea about finding errors early, but does not comply with how promises
  23194. //should operate.
  23195. prim.hideResolutionConflict = true;
  23196. //This method should be called when the patches to require should take hold.
  23197. return function () {
  23198. if (!allowRun) {
  23199. return;
  23200. }
  23201. allowRun = false;
  23202. var layer,
  23203. pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/,
  23204. oldNewContext = require.s.newContext,
  23205. oldDef,
  23206. //create local undefined values for module and exports,
  23207. //so that when files are evaled in this function they do not
  23208. //see the node values used for r.js
  23209. exports,
  23210. module;
  23211. /**
  23212. * Reset "global" build caches that are kept around between
  23213. * build layer builds. Useful to do when there are multiple
  23214. * top level requirejs.optimize() calls.
  23215. */
  23216. require._cacheReset = function () {
  23217. //Stored raw text caches, used by browser use.
  23218. require._cachedRawText = {};
  23219. //Stored cached file contents for reuse in other layers.
  23220. require._cachedFileContents = {};
  23221. //Store which cached files contain a require definition.
  23222. require._cachedDefinesRequireUrls = {};
  23223. };
  23224. require._cacheReset();
  23225. /**
  23226. * Makes sure the URL is something that can be supported by the
  23227. * optimization tool.
  23228. * @param {String} url
  23229. * @returns {Boolean}
  23230. */
  23231. require._isSupportedBuildUrl = function (url) {
  23232. //Ignore URLs with protocols, hosts or question marks, means either network
  23233. //access is needed to fetch it or it is too dynamic. Note that
  23234. //on Windows, full paths are used for some urls, which include
  23235. //the drive, like c:/something, so need to test for something other
  23236. //than just a colon.
  23237. if (url.indexOf("://") === -1 && url.indexOf("?") === -1 &&
  23238. url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) {
  23239. return true;
  23240. } else {
  23241. if (!layer.ignoredUrls[url]) {
  23242. if (url.indexOf('empty:') === -1) {
  23243. logger.info('Cannot optimize network URL, skipping: ' + url);
  23244. }
  23245. layer.ignoredUrls[url] = true;
  23246. }
  23247. return false;
  23248. }
  23249. };
  23250. function normalizeUrlWithBase(context, moduleName, url) {
  23251. //Adjust the URL if it was not transformed to use baseUrl.
  23252. if (require.jsExtRegExp.test(moduleName)) {
  23253. url = (context.config.dir || context.config.dirBaseUrl) + url;
  23254. }
  23255. return url;
  23256. }
  23257. //Overrides the new context call to add existing tracking features.
  23258. require.s.newContext = function (name) {
  23259. var context = oldNewContext(name),
  23260. oldEnable = context.enable,
  23261. moduleProto = context.Module.prototype,
  23262. oldInit = moduleProto.init,
  23263. oldCallPlugin = moduleProto.callPlugin;
  23264. //Only do this for the context used for building.
  23265. if (name === '_') {
  23266. //For build contexts, do everything sync
  23267. context.nextTick = function (fn) {
  23268. fn();
  23269. };
  23270. context.needFullExec = {};
  23271. context.fullExec = {};
  23272. context.plugins = {};
  23273. context.buildShimExports = {};
  23274. //Override the shim exports function generator to just
  23275. //spit out strings that can be used in the stringified
  23276. //build output.
  23277. context.makeShimExports = function (value) {
  23278. var fn;
  23279. if (context.config.wrapShim) {
  23280. fn = function () {
  23281. var str = 'return ';
  23282. // If specifies an export that is just a global
  23283. // name, no dot for a `this.` and such, then also
  23284. // attach to the global, for `var a = {}` files
  23285. // where the function closure would hide that from
  23286. // the global object.
  23287. if (value.exports && value.exports.indexOf('.') === -1) {
  23288. str += 'root.' + value.exports + ' = ';
  23289. }
  23290. if (value.init) {
  23291. str += '(' + value.init.toString()
  23292. .replace(useStrictRegExp, '') + '.apply(this, arguments))';
  23293. }
  23294. if (value.init && value.exports) {
  23295. str += ' || ';
  23296. }
  23297. if (value.exports) {
  23298. str += value.exports;
  23299. }
  23300. str += ';';
  23301. return str;
  23302. };
  23303. } else {
  23304. fn = function () {
  23305. return '(function (global) {\n' +
  23306. ' return function () {\n' +
  23307. ' var ret, fn;\n' +
  23308. (value.init ?
  23309. (' fn = ' + value.init.toString()
  23310. .replace(useStrictRegExp, '') + ';\n' +
  23311. ' ret = fn.apply(global, arguments);\n') : '') +
  23312. (value.exports ?
  23313. ' return ret || global.' + value.exports + ';\n' :
  23314. ' return ret;\n') +
  23315. ' };\n' +
  23316. '}(this))';
  23317. };
  23318. }
  23319. return fn;
  23320. };
  23321. context.enable = function (depMap, parent) {
  23322. var id = depMap.id,
  23323. parentId = parent && parent.map.id,
  23324. needFullExec = context.needFullExec,
  23325. fullExec = context.fullExec,
  23326. mod = getOwn(context.registry, id);
  23327. if (mod && !mod.defined) {
  23328. if (parentId && getOwn(needFullExec, parentId)) {
  23329. needFullExec[id] = depMap;
  23330. }
  23331. } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) ||
  23332. (parentId && getOwn(needFullExec, parentId) &&
  23333. falseProp(fullExec, id))) {
  23334. context.require.undef(id);
  23335. }
  23336. return oldEnable.apply(context, arguments);
  23337. };
  23338. //Override load so that the file paths can be collected.
  23339. context.load = function (moduleName, url) {
  23340. /*jslint evil: true */
  23341. var contents, pluginBuilderMatch, builderName,
  23342. shim, shimExports;
  23343. //Do not mark the url as fetched if it is
  23344. //not an empty: URL, used by the optimizer.
  23345. //In that case we need to be sure to call
  23346. //load() for each module that is mapped to
  23347. //empty: so that dependencies are satisfied
  23348. //correctly.
  23349. if (url.indexOf('empty:') === 0) {
  23350. delete context.urlFetched[url];
  23351. }
  23352. //Only handle urls that can be inlined, so that means avoiding some
  23353. //URLs like ones that require network access or may be too dynamic,
  23354. //like JSONP
  23355. if (require._isSupportedBuildUrl(url)) {
  23356. //Adjust the URL if it was not transformed to use baseUrl.
  23357. url = normalizeUrlWithBase(context, moduleName, url);
  23358. //Save the module name to path and path to module name mappings.
  23359. layer.buildPathMap[moduleName] = url;
  23360. layer.buildFileToModule[url] = moduleName;
  23361. if (hasProp(context.plugins, moduleName)) {
  23362. //plugins need to have their source evaled as-is.
  23363. context.needFullExec[moduleName] = true;
  23364. }
  23365. prim().start(function () {
  23366. if (hasProp(require._cachedFileContents, url) &&
  23367. (falseProp(context.needFullExec, moduleName) ||
  23368. getOwn(context.fullExec, moduleName))) {
  23369. contents = require._cachedFileContents[url];
  23370. //If it defines require, mark it so it can be hoisted.
  23371. //Done here and in the else below, before the
  23372. //else block removes code from the contents.
  23373. //Related to #263
  23374. if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) {
  23375. layer.existingRequireUrl = url;
  23376. }
  23377. } else {
  23378. //Load the file contents, process for conditionals, then
  23379. //evaluate it.
  23380. return require._cacheReadAsync(url).then(function (text) {
  23381. contents = text;
  23382. if (context.config.cjsTranslate &&
  23383. (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) {
  23384. contents = commonJs.convert(url, contents);
  23385. }
  23386. //If there is a read filter, run it now.
  23387. if (context.config.onBuildRead) {
  23388. contents = context.config.onBuildRead(moduleName, url, contents);
  23389. }
  23390. contents = pragma.process(url, contents, context.config, 'OnExecute');
  23391. //Find out if the file contains a require() definition. Need to know
  23392. //this so we can inject plugins right after it, but before they are needed,
  23393. //and to make sure this file is first, so that define calls work.
  23394. try {
  23395. if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) {
  23396. layer.existingRequireUrl = url;
  23397. require._cachedDefinesRequireUrls[url] = true;
  23398. }
  23399. } catch (e1) {
  23400. throw new Error('Parse error using esprima ' +
  23401. 'for file: ' + url + '\n' + e1);
  23402. }
  23403. }).then(function () {
  23404. if (hasProp(context.plugins, moduleName)) {
  23405. //This is a loader plugin, check to see if it has a build extension,
  23406. //otherwise the plugin will act as the plugin builder too.
  23407. pluginBuilderMatch = pluginBuilderRegExp.exec(contents);
  23408. if (pluginBuilderMatch) {
  23409. //Load the plugin builder for the plugin contents.
  23410. builderName = context.makeModuleMap(pluginBuilderMatch[3],
  23411. context.makeModuleMap(moduleName),
  23412. null,
  23413. true).id;
  23414. return require._cacheReadAsync(context.nameToUrl(builderName));
  23415. }
  23416. }
  23417. return contents;
  23418. }).then(function (text) {
  23419. contents = text;
  23420. //Parse out the require and define calls.
  23421. //Do this even for plugins in case they have their own
  23422. //dependencies that may be separate to how the pluginBuilder works.
  23423. try {
  23424. if (falseProp(context.needFullExec, moduleName)) {
  23425. contents = parse(moduleName, url, contents, {
  23426. insertNeedsDefine: true,
  23427. has: context.config.has,
  23428. findNestedDependencies: context.config.findNestedDependencies
  23429. });
  23430. }
  23431. } catch (e2) {
  23432. throw new Error('Parse error using esprima ' +
  23433. 'for file: ' + url + '\n' + e2);
  23434. }
  23435. require._cachedFileContents[url] = contents;
  23436. });
  23437. }
  23438. }).then(function () {
  23439. if (contents) {
  23440. eval(contents);
  23441. }
  23442. try {
  23443. //If have a string shim config, and this is
  23444. //a fully executed module, try to see if
  23445. //it created a variable in this eval scope
  23446. if (getOwn(context.needFullExec, moduleName)) {
  23447. shim = getOwn(context.config.shim, moduleName);
  23448. if (shim && shim.exports) {
  23449. shimExports = eval(shim.exports);
  23450. if (typeof shimExports !== 'undefined') {
  23451. context.buildShimExports[moduleName] = shimExports;
  23452. }
  23453. }
  23454. }
  23455. //Need to close out completion of this module
  23456. //so that listeners will get notified that it is available.
  23457. context.completeLoad(moduleName);
  23458. } catch (e) {
  23459. //Track which module could not complete loading.
  23460. if (!e.moduleTree) {
  23461. e.moduleTree = [];
  23462. }
  23463. e.moduleTree.push(moduleName);
  23464. throw e;
  23465. }
  23466. }).then(null, function (eOuter) {
  23467. if (!eOuter.fileName) {
  23468. eOuter.fileName = url;
  23469. }
  23470. throw eOuter;
  23471. }).end();
  23472. } else {
  23473. //With unsupported URLs still need to call completeLoad to
  23474. //finish loading.
  23475. context.completeLoad(moduleName);
  23476. }
  23477. };
  23478. //Marks module has having a name, and optionally executes the
  23479. //callback, but only if it meets certain criteria.
  23480. context.execCb = function (name, cb, args, exports) {
  23481. var buildShimExports = getOwn(layer.context.buildShimExports, name);
  23482. if (buildShimExports) {
  23483. return buildShimExports;
  23484. } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) {
  23485. return cb.apply(exports, args);
  23486. }
  23487. return undefined;
  23488. };
  23489. moduleProto.init = function (depMaps) {
  23490. if (context.needFullExec[this.map.id]) {
  23491. lang.each(depMaps, lang.bind(this, function (depMap) {
  23492. if (typeof depMap === 'string') {
  23493. depMap = context.makeModuleMap(depMap,
  23494. (this.map.isDefine ? this.map : this.map.parentMap));
  23495. }
  23496. if (!context.fullExec[depMap.id]) {
  23497. context.require.undef(depMap.id);
  23498. }
  23499. }));
  23500. }
  23501. return oldInit.apply(this, arguments);
  23502. };
  23503. moduleProto.callPlugin = function () {
  23504. var map = this.map,
  23505. pluginMap = context.makeModuleMap(map.prefix),
  23506. pluginId = pluginMap.id,
  23507. pluginMod = getOwn(context.registry, pluginId);
  23508. context.plugins[pluginId] = true;
  23509. context.needFullExec[pluginId] = map;
  23510. //If the module is not waiting to finish being defined,
  23511. //undef it and start over, to get full execution.
  23512. if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) {
  23513. context.require.undef(pluginMap.id);
  23514. }
  23515. return oldCallPlugin.apply(this, arguments);
  23516. };
  23517. }
  23518. return context;
  23519. };
  23520. //Clear up the existing context so that the newContext modifications
  23521. //above will be active.
  23522. delete require.s.contexts._;
  23523. /** Reset state for each build layer pass. */
  23524. require._buildReset = function () {
  23525. var oldContext = require.s.contexts._;
  23526. //Clear up the existing context.
  23527. delete require.s.contexts._;
  23528. //Set up new context, so the layer object can hold onto it.
  23529. require({});
  23530. layer = require._layer = {
  23531. buildPathMap: {},
  23532. buildFileToModule: {},
  23533. buildFilePaths: [],
  23534. pathAdded: {},
  23535. modulesWithNames: {},
  23536. needsDefine: {},
  23537. existingRequireUrl: "",
  23538. ignoredUrls: {},
  23539. context: require.s.contexts._
  23540. };
  23541. //Return the previous context in case it is needed, like for
  23542. //the basic config object.
  23543. return oldContext;
  23544. };
  23545. require._buildReset();
  23546. //Override define() to catch modules that just define an object, so that
  23547. //a dummy define call is not put in the build file for them. They do
  23548. //not end up getting defined via context.execCb, so we need to catch them
  23549. //at the define call.
  23550. oldDef = define;
  23551. //This function signature does not have to be exact, just match what we
  23552. //are looking for.
  23553. define = function (name) {
  23554. if (typeof name === "string" && falseProp(layer.needsDefine, name)) {
  23555. layer.modulesWithNames[name] = true;
  23556. }
  23557. return oldDef.apply(require, arguments);
  23558. };
  23559. define.amd = oldDef.amd;
  23560. //Add some utilities for plugins
  23561. require._readFile = file.readFile;
  23562. require._fileExists = function (path) {
  23563. return file.exists(path);
  23564. };
  23565. //Called when execManager runs for a dependency. Used to figure out
  23566. //what order of execution.
  23567. require.onResourceLoad = function (context, map) {
  23568. var id = map.id,
  23569. url;
  23570. // Fix up any maps that need to be normalized as part of the fullExec
  23571. // plumbing for plugins to participate in the build.
  23572. if (context.plugins && lang.hasProp(context.plugins, id)) {
  23573. lang.eachProp(context.needFullExec, function(value, prop) {
  23574. // For plugin entries themselves, they do not have a map
  23575. // value in needFullExec, just a "true" entry.
  23576. if (value !== true && value.prefix === id && value.unnormalized) {
  23577. var map = context.makeModuleMap(value.originalName, value.parentMap);
  23578. context.needFullExec[map.id] = map;
  23579. }
  23580. });
  23581. }
  23582. //If build needed a full execution, indicate it
  23583. //has been done now. But only do it if the context is tracking
  23584. //that. Only valid for the context used in a build, not for
  23585. //other contexts being run, like for useLib, plain requirejs
  23586. //use in node/rhino.
  23587. if (context.needFullExec && getOwn(context.needFullExec, id)) {
  23588. context.fullExec[id] = map;
  23589. }
  23590. //A plugin.
  23591. if (map.prefix) {
  23592. if (falseProp(layer.pathAdded, id)) {
  23593. layer.buildFilePaths.push(id);
  23594. //For plugins the real path is not knowable, use the name
  23595. //for both module to file and file to module mappings.
  23596. layer.buildPathMap[id] = id;
  23597. layer.buildFileToModule[id] = id;
  23598. layer.modulesWithNames[id] = true;
  23599. layer.pathAdded[id] = true;
  23600. }
  23601. } else if (map.url && require._isSupportedBuildUrl(map.url)) {
  23602. //If the url has not been added to the layer yet, and it
  23603. //is from an actual file that was loaded, add it now.
  23604. url = normalizeUrlWithBase(context, id, map.url);
  23605. if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) {
  23606. //Remember the list of dependencies for this layer.
  23607. layer.buildFilePaths.push(url);
  23608. layer.pathAdded[url] = true;
  23609. }
  23610. }
  23611. };
  23612. //Called by output of the parse() function, when a file does not
  23613. //explicitly call define, probably just require, but the parse()
  23614. //function normalizes on define() for dependency mapping and file
  23615. //ordering works correctly.
  23616. require.needsDefine = function (moduleName) {
  23617. layer.needsDefine[moduleName] = true;
  23618. };
  23619. };
  23620. });
  23621. /**
  23622. * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  23623. * Available via the MIT or new BSD license.
  23624. * see: http://github.com/jrburke/requirejs for details
  23625. */
  23626. /*jslint */
  23627. /*global define: false, console: false */
  23628. define('commonJs', ['env!env/file', 'parse'], function (file, parse) {
  23629. 'use strict';
  23630. var commonJs = {
  23631. //Set to false if you do not want this file to log. Useful in environments
  23632. //like node where you want the work to happen without noise.
  23633. useLog: true,
  23634. convertDir: function (commonJsPath, savePath) {
  23635. var fileList, i,
  23636. jsFileRegExp = /\.js$/,
  23637. fileName, convertedFileName, fileContents;
  23638. //Get list of files to convert.
  23639. fileList = file.getFilteredFileList(commonJsPath, /\w/, true);
  23640. //Normalize on front slashes and make sure the paths do not end in a slash.
  23641. commonJsPath = commonJsPath.replace(/\\/g, "/");
  23642. savePath = savePath.replace(/\\/g, "/");
  23643. if (commonJsPath.charAt(commonJsPath.length - 1) === "/") {
  23644. commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1);
  23645. }
  23646. if (savePath.charAt(savePath.length - 1) === "/") {
  23647. savePath = savePath.substring(0, savePath.length - 1);
  23648. }
  23649. //Cycle through all the JS files and convert them.
  23650. if (!fileList || !fileList.length) {
  23651. if (commonJs.useLog) {
  23652. if (commonJsPath === "convert") {
  23653. //A request just to convert one file.
  23654. console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath)));
  23655. } else {
  23656. console.log("No files to convert in directory: " + commonJsPath);
  23657. }
  23658. }
  23659. } else {
  23660. for (i = 0; i < fileList.length; i++) {
  23661. fileName = fileList[i];
  23662. convertedFileName = fileName.replace(commonJsPath, savePath);
  23663. //Handle JS files.
  23664. if (jsFileRegExp.test(fileName)) {
  23665. fileContents = file.readFile(fileName);
  23666. fileContents = commonJs.convert(fileName, fileContents);
  23667. file.saveUtf8File(convertedFileName, fileContents);
  23668. } else {
  23669. //Just copy the file over.
  23670. file.copyFile(fileName, convertedFileName, true);
  23671. }
  23672. }
  23673. }
  23674. },
  23675. /**
  23676. * Does the actual file conversion.
  23677. *
  23678. * @param {String} fileName the name of the file.
  23679. *
  23680. * @param {String} fileContents the contents of a file :)
  23681. *
  23682. * @returns {String} the converted contents
  23683. */
  23684. convert: function (fileName, fileContents) {
  23685. //Strip out comments.
  23686. try {
  23687. var preamble = '',
  23688. commonJsProps = parse.usesCommonJs(fileName, fileContents);
  23689. //First see if the module is not already RequireJS-formatted.
  23690. if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) {
  23691. return fileContents;
  23692. }
  23693. if (commonJsProps.dirname || commonJsProps.filename) {
  23694. preamble = 'var __filename = module.uri || "", ' +
  23695. '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); ';
  23696. }
  23697. //Construct the wrapper boilerplate.
  23698. fileContents = 'define(function (require, exports, module) {' +
  23699. preamble +
  23700. fileContents +
  23701. '\n});\n';
  23702. } catch (e) {
  23703. console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e);
  23704. return fileContents;
  23705. }
  23706. return fileContents;
  23707. }
  23708. };
  23709. return commonJs;
  23710. });
  23711. /**
  23712. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  23713. * Available via the MIT or new BSD license.
  23714. * see: http://github.com/jrburke/requirejs for details
  23715. */
  23716. /*jslint plusplus: true, nomen: true, regexp: true */
  23717. /*global define, requirejs, java, process, console */
  23718. define('build', function (require) {
  23719. 'use strict';
  23720. var build,
  23721. lang = require('lang'),
  23722. prim = require('prim'),
  23723. logger = require('logger'),
  23724. file = require('env!env/file'),
  23725. parse = require('parse'),
  23726. optimize = require('optimize'),
  23727. pragma = require('pragma'),
  23728. transform = require('transform'),
  23729. requirePatch = require('requirePatch'),
  23730. env = require('env'),
  23731. commonJs = require('commonJs'),
  23732. SourceMapGenerator = require('source-map/source-map-generator'),
  23733. hasProp = lang.hasProp,
  23734. getOwn = lang.getOwn,
  23735. falseProp = lang.falseProp,
  23736. endsWithSemiColonRegExp = /;\s*$/,
  23737. endsWithSlashRegExp = /[\/\\]$/,
  23738. resourceIsModuleIdRegExp = /^[\w\/\\\.]+$/;
  23739. prim.nextTick = function (fn) {
  23740. fn();
  23741. };
  23742. //Now map require to the outermost requirejs, now that we have
  23743. //local dependencies for this module. The rest of the require use is
  23744. //manipulating the requirejs loader.
  23745. require = requirejs;
  23746. //Caching function for performance. Attached to
  23747. //require so it can be reused in requirePatch.js. _cachedRawText
  23748. //set up by requirePatch.js
  23749. require._cacheReadAsync = function (path, encoding) {
  23750. var d;
  23751. if (lang.hasProp(require._cachedRawText, path)) {
  23752. d = prim();
  23753. d.resolve(require._cachedRawText[path]);
  23754. return d.promise;
  23755. } else {
  23756. return file.readFileAsync(path, encoding).then(function (text) {
  23757. require._cachedRawText[path] = text;
  23758. return text;
  23759. });
  23760. }
  23761. };
  23762. function makeBuildBaseConfig() {
  23763. return {
  23764. appDir: "",
  23765. pragmas: {},
  23766. paths: {},
  23767. optimize: "uglify",
  23768. optimizeCss: "standard.keepLines.keepWhitespace",
  23769. inlineText: true,
  23770. isBuild: true,
  23771. optimizeAllPluginResources: false,
  23772. findNestedDependencies: false,
  23773. preserveLicenseComments: true,
  23774. //By default, all files/directories are copied, unless
  23775. //they match this regexp, by default just excludes .folders
  23776. dirExclusionRegExp: file.dirExclusionRegExp,
  23777. _buildPathToModuleIndex: {}
  23778. };
  23779. }
  23780. /**
  23781. * Some JS may not be valid if concatenated with other JS, in particular
  23782. * the style of omitting semicolons and rely on ASI. Add a semicolon in
  23783. * those cases.
  23784. */
  23785. function addSemiColon(text, config) {
  23786. if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) {
  23787. return text;
  23788. } else {
  23789. return text + ";";
  23790. }
  23791. }
  23792. function endsWithSlash(dirName) {
  23793. if (dirName.charAt(dirName.length - 1) !== "/") {
  23794. dirName += "/";
  23795. }
  23796. return dirName;
  23797. }
  23798. //Method used by plugin writeFile calls, defined up here to avoid
  23799. //jslint warning about "making a function in a loop".
  23800. function makeWriteFile(namespace, layer) {
  23801. function writeFile(name, contents) {
  23802. logger.trace('Saving plugin-optimized file: ' + name);
  23803. file.saveUtf8File(name, contents);
  23804. }
  23805. writeFile.asModule = function (moduleName, fileName, contents) {
  23806. writeFile(fileName,
  23807. build.toTransport(namespace, moduleName, fileName, contents, layer));
  23808. };
  23809. return writeFile;
  23810. }
  23811. /**
  23812. * Main API entry point into the build. The args argument can either be
  23813. * an array of arguments (like the onese passed on a command-line),
  23814. * or it can be a JavaScript object that has the format of a build profile
  23815. * file.
  23816. *
  23817. * If it is an object, then in addition to the normal properties allowed in
  23818. * a build profile file, the object should contain one other property:
  23819. *
  23820. * The object could also contain a "buildFile" property, which is a string
  23821. * that is the file path to a build profile that contains the rest
  23822. * of the build profile directives.
  23823. *
  23824. * This function does not return a status, it should throw an error if
  23825. * there is a problem completing the build.
  23826. */
  23827. build = function (args) {
  23828. var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree,
  23829. i, j, errorMod,
  23830. stackRegExp = /( {4}at[^\n]+)\n/,
  23831. standardIndent = ' ';
  23832. return prim().start(function () {
  23833. if (!args || lang.isArray(args)) {
  23834. if (!args || args.length < 1) {
  23835. logger.error("build.js buildProfile.js\n" +
  23836. "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file).");
  23837. return undefined;
  23838. }
  23839. //Next args can include a build file path as well as other build args.
  23840. //build file path comes first. If it does not contain an = then it is
  23841. //a build file path. Otherwise, just all build args.
  23842. if (args[0].indexOf("=") === -1) {
  23843. buildFile = args[0];
  23844. args.splice(0, 1);
  23845. }
  23846. //Remaining args are options to the build
  23847. cmdConfig = build.convertArrayToObject(args);
  23848. cmdConfig.buildFile = buildFile;
  23849. } else {
  23850. cmdConfig = args;
  23851. }
  23852. return build._run(cmdConfig);
  23853. }).then(null, function (e) {
  23854. var err;
  23855. errorMsg = e.toString();
  23856. errorTree = e.moduleTree;
  23857. stackMatch = stackRegExp.exec(errorMsg);
  23858. if (stackMatch) {
  23859. errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1);
  23860. }
  23861. //If a module tree that shows what module triggered the error,
  23862. //print it out.
  23863. if (errorTree && errorTree.length > 0) {
  23864. errorMsg += '\nIn module tree:\n';
  23865. for (i = errorTree.length - 1; i > -1; i--) {
  23866. errorMod = errorTree[i];
  23867. if (errorMod) {
  23868. for (j = errorTree.length - i; j > -1; j--) {
  23869. errorMsg += standardIndent;
  23870. }
  23871. errorMsg += errorMod + '\n';
  23872. }
  23873. }
  23874. logger.error(errorMsg);
  23875. }
  23876. errorStack = e.stack;
  23877. if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) {
  23878. errorMsg += '\n' + errorStack;
  23879. } else {
  23880. if (!stackMatch && errorStack) {
  23881. //Just trim out the first "at" in the stack.
  23882. stackMatch = stackRegExp.exec(errorStack);
  23883. if (stackMatch) {
  23884. errorMsg += '\n' + stackMatch[0] || '';
  23885. }
  23886. }
  23887. }
  23888. err = new Error(errorMsg);
  23889. err.originalError = e;
  23890. throw err;
  23891. });
  23892. };
  23893. build._run = function (cmdConfig) {
  23894. var buildPaths, fileName, fileNames,
  23895. paths, i,
  23896. baseConfig, config,
  23897. modules, srcPath, buildContext,
  23898. destPath, moduleMap, parentModuleMap, context,
  23899. resources, resource, plugin, fileContents,
  23900. pluginProcessed = {},
  23901. buildFileContents = "",
  23902. pluginCollector = {};
  23903. return prim().start(function () {
  23904. var prop;
  23905. //Can now run the patches to require.js to allow it to be used for
  23906. //build generation. Do it here instead of at the top of the module
  23907. //because we want normal require behavior to load the build tool
  23908. //then want to switch to build mode.
  23909. requirePatch();
  23910. config = build.createConfig(cmdConfig);
  23911. paths = config.paths;
  23912. //Remove the previous build dir, in case it contains source transforms,
  23913. //like the ones done with onBuildRead and onBuildWrite.
  23914. if (config.dir && !config.keepBuildDir && file.exists(config.dir)) {
  23915. file.deleteFile(config.dir);
  23916. }
  23917. if (!config.out && !config.cssIn) {
  23918. //This is not just a one-off file build but a full build profile, with
  23919. //lots of files to process.
  23920. //First copy all the baseUrl content
  23921. file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true);
  23922. //Adjust baseUrl if config.appDir is in play, and set up build output paths.
  23923. buildPaths = {};
  23924. if (config.appDir) {
  23925. //All the paths should be inside the appDir, so just adjust
  23926. //the paths to use the dirBaseUrl
  23927. for (prop in paths) {
  23928. if (hasProp(paths, prop)) {
  23929. buildPaths[prop] = paths[prop].replace(config.appDir, config.dir);
  23930. }
  23931. }
  23932. } else {
  23933. //If no appDir, then make sure to copy the other paths to this directory.
  23934. for (prop in paths) {
  23935. if (hasProp(paths, prop)) {
  23936. //Set up build path for each path prefix, but only do so
  23937. //if the path falls out of the current baseUrl
  23938. if (paths[prop].indexOf(config.baseUrl) === 0) {
  23939. buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl);
  23940. } else {
  23941. buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop;
  23942. //Make sure source path is fully formed with baseUrl,
  23943. //if it is a relative URL.
  23944. srcPath = paths[prop];
  23945. if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) {
  23946. srcPath = config.baseUrl + srcPath;
  23947. }
  23948. destPath = config.dirBaseUrl + buildPaths[prop];
  23949. //Skip empty: paths
  23950. if (srcPath !== 'empty:') {
  23951. //If the srcPath is a directory, copy the whole directory.
  23952. if (file.exists(srcPath) && file.isDirectory(srcPath)) {
  23953. //Copy files to build area. Copy all files (the /\w/ regexp)
  23954. file.copyDir(srcPath, destPath, /\w/, true);
  23955. } else {
  23956. //Try a .js extension
  23957. srcPath += '.js';
  23958. destPath += '.js';
  23959. file.copyFile(srcPath, destPath);
  23960. }
  23961. }
  23962. }
  23963. }
  23964. }
  23965. }
  23966. }
  23967. //Figure out source file location for each module layer. Do this by seeding require
  23968. //with source area configuration. This is needed so that later the module layers
  23969. //can be manually copied over to the source area, since the build may be
  23970. //require multiple times and the above copyDir call only copies newer files.
  23971. require({
  23972. baseUrl: config.baseUrl,
  23973. paths: paths,
  23974. packagePaths: config.packagePaths,
  23975. packages: config.packages
  23976. });
  23977. buildContext = require.s.contexts._;
  23978. modules = config.modules;
  23979. if (modules) {
  23980. modules.forEach(function (module) {
  23981. if (module.name) {
  23982. module._sourcePath = buildContext.nameToUrl(module.name);
  23983. //If the module does not exist, and this is not a "new" module layer,
  23984. //as indicated by a true "create" property on the module, and
  23985. //it is not a plugin-loaded resource, and there is no
  23986. //'rawText' containing the module's source then throw an error.
  23987. if (!file.exists(module._sourcePath) && !module.create &&
  23988. module.name.indexOf('!') === -1 &&
  23989. (!config.rawText || !lang.hasProp(config.rawText, module.name))) {
  23990. throw new Error("ERROR: module path does not exist: " +
  23991. module._sourcePath + " for module named: " + module.name +
  23992. ". Path is relative to: " + file.absPath('.'));
  23993. }
  23994. }
  23995. });
  23996. }
  23997. if (config.out) {
  23998. //Just set up the _buildPath for the module layer.
  23999. require(config);
  24000. if (!config.cssIn) {
  24001. config.modules[0]._buildPath = typeof config.out === 'function' ?
  24002. 'FUNCTION' : config.out;
  24003. }
  24004. } else if (!config.cssIn) {
  24005. //Now set up the config for require to use the build area, and calculate the
  24006. //build file locations. Pass along any config info too.
  24007. baseConfig = {
  24008. baseUrl: config.dirBaseUrl,
  24009. paths: buildPaths
  24010. };
  24011. lang.mixin(baseConfig, config);
  24012. require(baseConfig);
  24013. if (modules) {
  24014. modules.forEach(function (module) {
  24015. if (module.name) {
  24016. module._buildPath = buildContext.nameToUrl(module.name, null);
  24017. //If buildPath and sourcePath are the same, throw since this
  24018. //would result in modifying source. This condition can happen
  24019. //with some more tricky paths: config and appDir/baseUrl
  24020. //setting, which is a sign of incorrect config.
  24021. if (module._buildPath === module._sourcePath) {
  24022. throw new Error('Module ID \'' + module.name +
  24023. '\' has a source path that is same as output path: ' +
  24024. module._sourcePath +
  24025. '. Stopping, config is malformed.');
  24026. }
  24027. if (!module.create) {
  24028. file.copyFile(module._sourcePath, module._buildPath);
  24029. }
  24030. }
  24031. });
  24032. }
  24033. }
  24034. //Run CSS optimizations before doing JS module tracing, to allow
  24035. //things like text loader plugins loading CSS to get the optimized
  24036. //CSS.
  24037. if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) {
  24038. buildFileContents += optimize.css(config.dir, config);
  24039. }
  24040. }).then(function() {
  24041. baseConfig = lang.deeplikeCopy(require.s.contexts._.config);
  24042. }).then(function () {
  24043. var actions = [];
  24044. if (modules) {
  24045. actions = modules.map(function (module, i) {
  24046. return function () {
  24047. //Save off buildPath to module index in a hash for quicker
  24048. //lookup later.
  24049. config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i;
  24050. //Call require to calculate dependencies.
  24051. return build.traceDependencies(module, config, baseConfig)
  24052. .then(function (layer) {
  24053. module.layer = layer;
  24054. });
  24055. };
  24056. });
  24057. return prim.serial(actions);
  24058. }
  24059. }).then(function () {
  24060. var actions;
  24061. if (modules) {
  24062. //Now build up shadow layers for anything that should be excluded.
  24063. //Do this after tracing dependencies for each module, in case one
  24064. //of those modules end up being one of the excluded values.
  24065. actions = modules.map(function (module) {
  24066. return function () {
  24067. if (module.exclude) {
  24068. module.excludeLayers = [];
  24069. return prim.serial(module.exclude.map(function (exclude, i) {
  24070. return function () {
  24071. //See if it is already in the list of modules.
  24072. //If not trace dependencies for it.
  24073. var found = build.findBuildModule(exclude, modules);
  24074. if (found) {
  24075. module.excludeLayers[i] = found;
  24076. } else {
  24077. return build.traceDependencies({name: exclude}, config, baseConfig)
  24078. .then(function (layer) {
  24079. module.excludeLayers[i] = { layer: layer };
  24080. });
  24081. }
  24082. };
  24083. }));
  24084. }
  24085. };
  24086. });
  24087. return prim.serial(actions);
  24088. }
  24089. }).then(function () {
  24090. if (modules) {
  24091. return prim.serial(modules.map(function (module) {
  24092. return function () {
  24093. if (module.exclude) {
  24094. //module.exclude is an array of module names. For each one,
  24095. //get the nested dependencies for it via a matching entry
  24096. //in the module.excludeLayers array.
  24097. module.exclude.forEach(function (excludeModule, i) {
  24098. var excludeLayer = module.excludeLayers[i].layer,
  24099. map = excludeLayer.buildFileToModule;
  24100. excludeLayer.buildFilePaths.forEach(function(filePath){
  24101. build.removeModulePath(map[filePath], filePath, module.layer);
  24102. });
  24103. });
  24104. }
  24105. if (module.excludeShallow) {
  24106. //module.excludeShallow is an array of module names.
  24107. //shallow exclusions are just that module itself, and not
  24108. //its nested dependencies.
  24109. module.excludeShallow.forEach(function (excludeShallowModule) {
  24110. var path = getOwn(module.layer.buildPathMap, excludeShallowModule);
  24111. if (path) {
  24112. build.removeModulePath(excludeShallowModule, path, module.layer);
  24113. }
  24114. });
  24115. }
  24116. //Flatten them and collect the build output for each module.
  24117. return build.flattenModule(module, module.layer, config).then(function (builtModule) {
  24118. var finalText, baseName;
  24119. //Save it to a temp file for now, in case there are other layers that
  24120. //contain optimized content that should not be included in later
  24121. //layer optimizations. See issue #56.
  24122. if (module._buildPath === 'FUNCTION') {
  24123. module._buildText = builtModule.text;
  24124. module._buildSourceMap = builtModule.sourceMap;
  24125. } else {
  24126. finalText = builtModule.text;
  24127. if (builtModule.sourceMap) {
  24128. baseName = module._buildPath.split('/');
  24129. baseName = baseName.pop();
  24130. finalText += '\n//# sourceMappingURL=' + baseName + '.map';
  24131. file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap);
  24132. }
  24133. file.saveUtf8File(module._buildPath + '-temp', finalText);
  24134. }
  24135. buildFileContents += builtModule.buildText;
  24136. });
  24137. };
  24138. }));
  24139. }
  24140. }).then(function () {
  24141. var moduleName, outOrigSourceMap;
  24142. if (modules) {
  24143. //Now move the build layers to their final position.
  24144. modules.forEach(function (module) {
  24145. var finalPath = module._buildPath;
  24146. if (finalPath !== 'FUNCTION') {
  24147. if (file.exists(finalPath)) {
  24148. file.deleteFile(finalPath);
  24149. }
  24150. file.renameFile(finalPath + '-temp', finalPath);
  24151. //And finally, if removeCombined is specified, remove
  24152. //any of the files that were used in this layer.
  24153. //Be sure not to remove other build layers.
  24154. if (config.removeCombined && !config.out) {
  24155. module.layer.buildFilePaths.forEach(function (path) {
  24156. var isLayer = modules.some(function (mod) {
  24157. return mod._buildPath === path;
  24158. }),
  24159. relPath = build.makeRelativeFilePath(config.dir, path);
  24160. if (file.exists(path) &&
  24161. // not a build layer target
  24162. !isLayer &&
  24163. // not outside the build directory
  24164. relPath.indexOf('..') !== 0) {
  24165. file.deleteFile(path);
  24166. }
  24167. });
  24168. }
  24169. }
  24170. //Signal layer is done
  24171. if (config.onModuleBundleComplete) {
  24172. config.onModuleBundleComplete(module.onCompleteData);
  24173. }
  24174. });
  24175. }
  24176. //If removeCombined in play, remove any empty directories that
  24177. //may now exist because of its use
  24178. if (config.removeCombined && !config.out && config.dir) {
  24179. file.deleteEmptyDirs(config.dir);
  24180. }
  24181. //Do other optimizations.
  24182. if (config.out && !config.cssIn) {
  24183. //Just need to worry about one JS file.
  24184. fileName = config.modules[0]._buildPath;
  24185. if (fileName === 'FUNCTION') {
  24186. outOrigSourceMap = config.modules[0]._buildSourceMap;
  24187. config._buildSourceMap = outOrigSourceMap;
  24188. config.modules[0]._buildText = optimize.js((config.modules[0].name ||
  24189. config.modules[0].include[0] ||
  24190. fileName) + '.build.js',
  24191. config.modules[0]._buildText,
  24192. null,
  24193. config);
  24194. if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) {
  24195. config.modules[0]._buildSourceMap = config._buildSourceMap;
  24196. config._buildSourceMap = null;
  24197. }
  24198. } else {
  24199. optimize.jsFile(fileName, null, fileName, config);
  24200. }
  24201. } else if (!config.cssIn) {
  24202. //Normal optimizations across modules.
  24203. //JS optimizations.
  24204. fileNames = file.getFilteredFileList(config.dir, /\.js$/, true);
  24205. fileNames.forEach(function (fileName) {
  24206. var cfg, override, moduleIndex;
  24207. //Generate the module name from the config.dir root.
  24208. moduleName = fileName.replace(config.dir, '');
  24209. //Get rid of the extension
  24210. moduleName = moduleName.substring(0, moduleName.length - 3);
  24211. //If there is an override for a specific layer build module,
  24212. //and this file is that module, mix in the override for use
  24213. //by optimize.jsFile.
  24214. moduleIndex = getOwn(config._buildPathToModuleIndex, fileName);
  24215. //Normalize, since getOwn could have returned undefined
  24216. moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1;
  24217. //Try to avoid extra work if the other files do not need to
  24218. //be read. Build layers should be processed at the very
  24219. //least for optimization.
  24220. if (moduleIndex > -1 || !config.skipDirOptimize ||
  24221. config.normalizeDirDefines === "all" ||
  24222. config.cjsTranslate) {
  24223. //Convert the file to transport format, but without a name
  24224. //inserted (by passing null for moduleName) since the files are
  24225. //standalone, one module per file.
  24226. fileContents = file.readFile(fileName);
  24227. //For builds, if wanting cjs translation, do it now, so that
  24228. //the individual modules can be loaded cross domain via
  24229. //plain script tags.
  24230. if (config.cjsTranslate &&
  24231. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  24232. fileContents = commonJs.convert(fileName, fileContents);
  24233. }
  24234. if (moduleIndex === -1) {
  24235. if (config.onBuildRead) {
  24236. fileContents = config.onBuildRead(moduleName,
  24237. fileName,
  24238. fileContents);
  24239. }
  24240. //Only do transport normalization if this is not a build
  24241. //layer (since it was already normalized) and if
  24242. //normalizeDirDefines indicated all should be done.
  24243. if (config.normalizeDirDefines === "all") {
  24244. fileContents = build.toTransport(config.namespace,
  24245. null,
  24246. fileName,
  24247. fileContents);
  24248. }
  24249. if (config.onBuildWrite) {
  24250. fileContents = config.onBuildWrite(moduleName,
  24251. fileName,
  24252. fileContents);
  24253. }
  24254. }
  24255. override = moduleIndex > -1 ?
  24256. config.modules[moduleIndex].override : null;
  24257. if (override) {
  24258. cfg = build.createOverrideConfig(config, override);
  24259. } else {
  24260. cfg = config;
  24261. }
  24262. if (moduleIndex > -1 || !config.skipDirOptimize) {
  24263. optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector);
  24264. }
  24265. }
  24266. });
  24267. //Normalize all the plugin resources.
  24268. context = require.s.contexts._;
  24269. for (moduleName in pluginCollector) {
  24270. if (hasProp(pluginCollector, moduleName)) {
  24271. parentModuleMap = context.makeModuleMap(moduleName);
  24272. resources = pluginCollector[moduleName];
  24273. for (i = 0; i < resources.length; i++) {
  24274. resource = resources[i];
  24275. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  24276. if (falseProp(context.plugins, moduleMap.prefix)) {
  24277. //Set the value in context.plugins so it
  24278. //will be evaluated as a full plugin.
  24279. context.plugins[moduleMap.prefix] = true;
  24280. //Do not bother if the plugin is not available.
  24281. if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) {
  24282. continue;
  24283. }
  24284. //Rely on the require in the build environment
  24285. //to be synchronous
  24286. context.require([moduleMap.prefix]);
  24287. //Now that the plugin is loaded, redo the moduleMap
  24288. //since the plugin will need to normalize part of the path.
  24289. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  24290. }
  24291. //Only bother with plugin resources that can be handled
  24292. //processed by the plugin, via support of the writeFile
  24293. //method.
  24294. if (falseProp(pluginProcessed, moduleMap.id)) {
  24295. //Only do the work if the plugin was really loaded.
  24296. //Using an internal access because the file may
  24297. //not really be loaded.
  24298. plugin = getOwn(context.defined, moduleMap.prefix);
  24299. if (plugin && plugin.writeFile) {
  24300. plugin.writeFile(
  24301. moduleMap.prefix,
  24302. moduleMap.name,
  24303. require,
  24304. makeWriteFile(
  24305. config.namespace
  24306. ),
  24307. context.config
  24308. );
  24309. }
  24310. pluginProcessed[moduleMap.id] = true;
  24311. }
  24312. }
  24313. }
  24314. }
  24315. //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " "));
  24316. //All module layers are done, write out the build.txt file.
  24317. file.saveUtf8File(config.dir + "build.txt", buildFileContents);
  24318. }
  24319. //If just have one CSS file to optimize, do that here.
  24320. if (config.cssIn) {
  24321. buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText;
  24322. }
  24323. if (typeof config.out === 'function') {
  24324. config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap);
  24325. }
  24326. //Print out what was built into which layers.
  24327. if (buildFileContents) {
  24328. logger.info(buildFileContents);
  24329. return buildFileContents;
  24330. }
  24331. return '';
  24332. });
  24333. };
  24334. /**
  24335. * Converts command line args like "paths.foo=../some/path"
  24336. * result.paths = { foo: '../some/path' } where prop = paths,
  24337. * name = paths.foo and value = ../some/path, so it assumes the
  24338. * name=value splitting has already happened.
  24339. */
  24340. function stringDotToObj(result, name, value) {
  24341. var parts = name.split('.');
  24342. parts.forEach(function (prop, i) {
  24343. if (i === parts.length - 1) {
  24344. result[prop] = value;
  24345. } else {
  24346. if (falseProp(result, prop)) {
  24347. result[prop] = {};
  24348. }
  24349. result = result[prop];
  24350. }
  24351. });
  24352. }
  24353. build.objProps = {
  24354. paths: true,
  24355. wrap: true,
  24356. pragmas: true,
  24357. pragmasOnSave: true,
  24358. has: true,
  24359. hasOnSave: true,
  24360. uglify: true,
  24361. uglify2: true,
  24362. closure: true,
  24363. map: true,
  24364. throwWhen: true
  24365. };
  24366. build.hasDotPropMatch = function (prop) {
  24367. var dotProp,
  24368. index = prop.indexOf('.');
  24369. if (index !== -1) {
  24370. dotProp = prop.substring(0, index);
  24371. return hasProp(build.objProps, dotProp);
  24372. }
  24373. return false;
  24374. };
  24375. /**
  24376. * Converts an array that has String members of "name=value"
  24377. * into an object, where the properties on the object are the names in the array.
  24378. * Also converts the strings "true" and "false" to booleans for the values.
  24379. * member name/value pairs, and converts some comma-separated lists into
  24380. * arrays.
  24381. * @param {Array} ary
  24382. */
  24383. build.convertArrayToObject = function (ary) {
  24384. var result = {}, i, separatorIndex, prop, value,
  24385. needArray = {
  24386. "include": true,
  24387. "exclude": true,
  24388. "excludeShallow": true,
  24389. "insertRequire": true,
  24390. "stubModules": true,
  24391. "deps": true,
  24392. "mainConfigFile": true
  24393. };
  24394. for (i = 0; i < ary.length; i++) {
  24395. separatorIndex = ary[i].indexOf("=");
  24396. if (separatorIndex === -1) {
  24397. throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value";
  24398. }
  24399. value = ary[i].substring(separatorIndex + 1, ary[i].length);
  24400. if (value === "true") {
  24401. value = true;
  24402. } else if (value === "false") {
  24403. value = false;
  24404. }
  24405. prop = ary[i].substring(0, separatorIndex);
  24406. //Convert to array if necessary
  24407. if (getOwn(needArray, prop)) {
  24408. value = value.split(",");
  24409. }
  24410. if (build.hasDotPropMatch(prop)) {
  24411. stringDotToObj(result, prop, value);
  24412. } else {
  24413. result[prop] = value;
  24414. }
  24415. }
  24416. return result; //Object
  24417. };
  24418. build.makeAbsPath = function (path, absFilePath) {
  24419. if (!absFilePath) {
  24420. return path;
  24421. }
  24422. //Add abspath if necessary. If path starts with a slash or has a colon,
  24423. //then already is an abolute path.
  24424. if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) {
  24425. path = absFilePath +
  24426. (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') +
  24427. path;
  24428. path = file.normalize(path);
  24429. }
  24430. return path.replace(lang.backSlashRegExp, '/');
  24431. };
  24432. build.makeAbsObject = function (props, obj, absFilePath) {
  24433. var i, prop;
  24434. if (obj) {
  24435. for (i = 0; i < props.length; i++) {
  24436. prop = props[i];
  24437. if (hasProp(obj, prop) && typeof obj[prop] === 'string') {
  24438. obj[prop] = build.makeAbsPath(obj[prop], absFilePath);
  24439. }
  24440. }
  24441. }
  24442. };
  24443. /**
  24444. * For any path in a possible config, make it absolute relative
  24445. * to the absFilePath passed in.
  24446. */
  24447. build.makeAbsConfig = function (config, absFilePath) {
  24448. var props, prop, i;
  24449. props = ["appDir", "dir", "baseUrl"];
  24450. for (i = 0; i < props.length; i++) {
  24451. prop = props[i];
  24452. if (getOwn(config, prop)) {
  24453. //Add abspath if necessary, make sure these paths end in
  24454. //slashes
  24455. if (prop === "baseUrl") {
  24456. config.originalBaseUrl = config.baseUrl;
  24457. if (config.appDir) {
  24458. //If baseUrl with an appDir, the baseUrl is relative to
  24459. //the appDir, *not* the absFilePath. appDir and dir are
  24460. //made absolute before baseUrl, so this will work.
  24461. config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir);
  24462. } else {
  24463. //The dir output baseUrl is same as regular baseUrl, both
  24464. //relative to the absFilePath.
  24465. config.baseUrl = build.makeAbsPath(config[prop], absFilePath);
  24466. }
  24467. } else {
  24468. config[prop] = build.makeAbsPath(config[prop], absFilePath);
  24469. }
  24470. config[prop] = endsWithSlash(config[prop]);
  24471. }
  24472. }
  24473. build.makeAbsObject((config.out === "stdout" ? ["cssIn"] : ["out", "cssIn"]),
  24474. config, absFilePath);
  24475. build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath);
  24476. };
  24477. /**
  24478. * Creates a relative path to targetPath from refPath.
  24479. * Only deals with file paths, not folders. If folders,
  24480. * make sure paths end in a trailing '/'.
  24481. */
  24482. build.makeRelativeFilePath = function (refPath, targetPath) {
  24483. var i, dotLength, finalParts, length, targetParts, targetName,
  24484. refParts = refPath.split('/'),
  24485. hasEndSlash = endsWithSlashRegExp.test(targetPath),
  24486. dotParts = [];
  24487. targetPath = file.normalize(targetPath);
  24488. if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) {
  24489. targetPath += '/';
  24490. }
  24491. targetParts = targetPath.split('/');
  24492. //Pull off file name
  24493. targetName = targetParts.pop();
  24494. //Also pop off the ref file name to make the matches against
  24495. //targetParts equivalent.
  24496. refParts.pop();
  24497. length = refParts.length;
  24498. for (i = 0; i < length; i += 1) {
  24499. if (refParts[i] !== targetParts[i]) {
  24500. break;
  24501. }
  24502. }
  24503. //Now i is the index in which they diverge.
  24504. finalParts = targetParts.slice(i);
  24505. dotLength = length - i;
  24506. for (i = 0; i > -1 && i < dotLength; i += 1) {
  24507. dotParts.push('..');
  24508. }
  24509. return dotParts.join('/') + (dotParts.length ? '/' : '') +
  24510. finalParts.join('/') + (finalParts.length ? '/' : '') +
  24511. targetName;
  24512. };
  24513. build.nestedMix = {
  24514. paths: true,
  24515. has: true,
  24516. hasOnSave: true,
  24517. pragmas: true,
  24518. pragmasOnSave: true
  24519. };
  24520. /**
  24521. * Mixes additional source config into target config, and merges some
  24522. * nested config, like paths, correctly.
  24523. */
  24524. function mixConfig(target, source, skipArrays) {
  24525. var prop, value, isArray, targetValue;
  24526. for (prop in source) {
  24527. if (hasProp(source, prop)) {
  24528. //If the value of the property is a plain object, then
  24529. //allow a one-level-deep mixing of it.
  24530. value = source[prop];
  24531. isArray = lang.isArray(value);
  24532. if (typeof value === 'object' && value &&
  24533. !isArray && !lang.isFunction(value) &&
  24534. !lang.isRegExp(value)) {
  24535. // TODO: need to generalize this work, maybe also reuse
  24536. // the work done in requirejs configure, perhaps move to
  24537. // just a deep copy/merge overall. However, given the
  24538. // amount of observable change, wait for a dot release.
  24539. // This change is in relation to #645
  24540. if (prop === 'map') {
  24541. if (!target.map) {
  24542. target.map = {};
  24543. }
  24544. lang.deepMix(target.map, source.map);
  24545. } else {
  24546. target[prop] = lang.mixin({}, target[prop], value, true);
  24547. }
  24548. } else if (isArray) {
  24549. if (!skipArrays) {
  24550. // Some config, like packages, are arrays. For those,
  24551. // just merge the results.
  24552. targetValue = target[prop];
  24553. if (lang.isArray(targetValue)) {
  24554. target[prop] = targetValue.concat(value);
  24555. } else {
  24556. target[prop] = value;
  24557. }
  24558. }
  24559. } else {
  24560. target[prop] = value;
  24561. }
  24562. }
  24563. }
  24564. //Set up log level since it can affect if errors are thrown
  24565. //or caught and passed to errbacks while doing config setup.
  24566. if (lang.hasProp(target, 'logLevel')) {
  24567. logger.logLevel(target.logLevel);
  24568. }
  24569. }
  24570. /**
  24571. * Converts a wrap.startFile or endFile to be start/end as a string.
  24572. * the startFile/endFile values can be arrays.
  24573. */
  24574. function flattenWrapFile(wrap, keyName, absFilePath) {
  24575. var keyFileName = keyName + 'File';
  24576. if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) {
  24577. wrap[keyName] = '';
  24578. if (typeof wrap[keyFileName] === 'string') {
  24579. wrap[keyFileName] = [wrap[keyFileName]];
  24580. }
  24581. wrap[keyFileName].forEach(function (fileName) {
  24582. wrap[keyName] += (wrap[keyName] ? '\n' : '') +
  24583. file.readFile(build.makeAbsPath(fileName, absFilePath));
  24584. });
  24585. } else if (wrap[keyName] === null || wrap[keyName] === undefined) {
  24586. //Allow missing one, just set to empty string.
  24587. wrap[keyName] = '';
  24588. } else if (typeof wrap[keyName] !== 'string') {
  24589. throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed');
  24590. }
  24591. }
  24592. function normalizeWrapConfig(config, absFilePath) {
  24593. //Get any wrap text.
  24594. try {
  24595. if (config.wrap) {
  24596. if (config.wrap === true) {
  24597. //Use default values.
  24598. config.wrap = {
  24599. start: '(function () {',
  24600. end: '}());'
  24601. };
  24602. } else {
  24603. flattenWrapFile(config.wrap, 'start', absFilePath);
  24604. flattenWrapFile(config.wrap, 'end', absFilePath);
  24605. }
  24606. }
  24607. } catch (wrapError) {
  24608. throw new Error('Malformed wrap config: ' + wrapError.toString());
  24609. }
  24610. }
  24611. /**
  24612. * Creates a config object for an optimization build.
  24613. * It will also read the build profile if it is available, to create
  24614. * the configuration.
  24615. *
  24616. * @param {Object} cfg config options that take priority
  24617. * over defaults and ones in the build file. These options could
  24618. * be from a command line, for instance.
  24619. *
  24620. * @param {Object} the created config object.
  24621. */
  24622. build.createConfig = function (cfg) {
  24623. /*jslint evil: true */
  24624. var buildFileContents, buildFileConfig, mainConfig,
  24625. mainConfigFile, mainConfigPath, buildFile, absFilePath,
  24626. config = {},
  24627. buildBaseConfig = makeBuildBaseConfig();
  24628. //Make sure all paths are relative to current directory.
  24629. absFilePath = file.absPath('.');
  24630. build.makeAbsConfig(cfg, absFilePath);
  24631. build.makeAbsConfig(buildBaseConfig, absFilePath);
  24632. lang.mixin(config, buildBaseConfig);
  24633. lang.mixin(config, cfg, true);
  24634. //Set up log level early since it can affect if errors are thrown
  24635. //or caught and passed to errbacks, even while constructing config.
  24636. if (lang.hasProp(config, 'logLevel')) {
  24637. logger.logLevel(config.logLevel);
  24638. }
  24639. if (config.buildFile) {
  24640. //A build file exists, load it to get more config.
  24641. buildFile = file.absPath(config.buildFile);
  24642. //Find the build file, and make sure it exists, if this is a build
  24643. //that has a build profile, and not just command line args with an in=path
  24644. if (!file.exists(buildFile)) {
  24645. throw new Error("ERROR: build file does not exist: " + buildFile);
  24646. }
  24647. absFilePath = config.baseUrl = file.absPath(file.parent(buildFile));
  24648. //Load build file options.
  24649. buildFileContents = file.readFile(buildFile);
  24650. try {
  24651. //Be a bit lenient in the file ending in a ; or ending with
  24652. //a //# sourceMappingUrl comment, mostly for compiled languages
  24653. //that create a config, like typescript.
  24654. buildFileContents = buildFileContents
  24655. .replace(/\/\/\#[^\n\r]+[\n\r]*$/, '')
  24656. .trim()
  24657. .replace(/;$/, '');
  24658. buildFileConfig = eval("(" + buildFileContents + ")");
  24659. build.makeAbsConfig(buildFileConfig, absFilePath);
  24660. //Mix in the config now so that items in mainConfigFile can
  24661. //be resolved relative to them if necessary, like if appDir
  24662. //is set here, but the baseUrl is in mainConfigFile. Will
  24663. //re-mix in the same build config later after mainConfigFile
  24664. //is processed, since build config should take priority.
  24665. mixConfig(config, buildFileConfig);
  24666. } catch (e) {
  24667. throw new Error("Build file " + buildFile + " is malformed: " + e);
  24668. }
  24669. }
  24670. mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile);
  24671. if (mainConfigFile) {
  24672. if (typeof mainConfigFile === 'string') {
  24673. mainConfigFile = [mainConfigFile];
  24674. }
  24675. mainConfigFile.forEach(function (configFile) {
  24676. configFile = build.makeAbsPath(configFile, absFilePath);
  24677. if (!file.exists(configFile)) {
  24678. throw new Error(configFile + ' does not exist.');
  24679. }
  24680. try {
  24681. mainConfig = parse.findConfig(file.readFile(configFile)).config;
  24682. } catch (configError) {
  24683. throw new Error('The config in mainConfigFile ' +
  24684. configFile +
  24685. ' cannot be used because it cannot be evaluated' +
  24686. ' correctly while running in the optimizer. Try only' +
  24687. ' using a config that is also valid JSON, or do not use' +
  24688. ' mainConfigFile and instead copy the config values needed' +
  24689. ' into a build file or command line arguments given to the optimizer.\n' +
  24690. 'Source error from parsing: ' + configFile + ': ' + configError);
  24691. }
  24692. if (mainConfig) {
  24693. mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/'));
  24694. //Add in some existing config, like appDir, since they can be
  24695. //used inside the configFile -- paths and baseUrl are
  24696. //relative to them.
  24697. if (config.appDir && !mainConfig.appDir) {
  24698. mainConfig.appDir = config.appDir;
  24699. }
  24700. //If no baseUrl, then use the directory holding the main config.
  24701. if (!mainConfig.baseUrl) {
  24702. mainConfig.baseUrl = mainConfigPath;
  24703. }
  24704. build.makeAbsConfig(mainConfig, mainConfigPath);
  24705. mixConfig(config, mainConfig);
  24706. }
  24707. });
  24708. }
  24709. //Mix in build file config, but only after mainConfig has been mixed in.
  24710. //Since this is a re-application, skip array merging.
  24711. if (buildFileConfig) {
  24712. mixConfig(config, buildFileConfig, true);
  24713. }
  24714. //Re-apply the override config values. Command line
  24715. //args should take precedence over build file values.
  24716. //Since this is a re-application, skip array merging.
  24717. mixConfig(config, cfg, true);
  24718. //Fix paths to full paths so that they can be adjusted consistently
  24719. //lately to be in the output area.
  24720. lang.eachProp(config.paths, function (value, prop) {
  24721. if (lang.isArray(value)) {
  24722. throw new Error('paths fallback not supported in optimizer. ' +
  24723. 'Please provide a build config path override ' +
  24724. 'for ' + prop);
  24725. }
  24726. config.paths[prop] = build.makeAbsPath(value, config.baseUrl);
  24727. });
  24728. //Set final output dir
  24729. if (hasProp(config, "baseUrl")) {
  24730. if (config.appDir) {
  24731. if (!config.originalBaseUrl) {
  24732. throw new Error('Please set a baseUrl in the build config');
  24733. }
  24734. config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir);
  24735. } else {
  24736. config.dirBaseUrl = config.dir || config.baseUrl;
  24737. }
  24738. //Make sure dirBaseUrl ends in a slash, since it is
  24739. //concatenated with other strings.
  24740. config.dirBaseUrl = endsWithSlash(config.dirBaseUrl);
  24741. }
  24742. //If out=stdout, write output to STDOUT instead of a file.
  24743. if (config.out && config.out === 'stdout') {
  24744. config.out = function (content) {
  24745. var e = env.get();
  24746. if (e === 'rhino') {
  24747. var out = new java.io.PrintStream(java.lang.System.out, true, 'UTF-8');
  24748. out.println(content);
  24749. } else if (e === 'node') {
  24750. process.stdout.setEncoding('utf8');
  24751. process.stdout.write(content);
  24752. } else {
  24753. console.log(content);
  24754. }
  24755. };
  24756. }
  24757. //Check for errors in config
  24758. if (config.main) {
  24759. throw new Error('"main" passed as an option, but the ' +
  24760. 'supported option is called "name".');
  24761. }
  24762. if (config.out && !config.name && !config.modules && !config.include &&
  24763. !config.cssIn) {
  24764. throw new Error('Missing either a "name", "include" or "modules" ' +
  24765. 'option');
  24766. }
  24767. if (config.cssIn) {
  24768. if (config.dir || config.appDir) {
  24769. throw new Error('cssIn is only for the output of single file ' +
  24770. 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.');
  24771. }
  24772. if (!config.out) {
  24773. throw new Error('"out" option missing.');
  24774. }
  24775. }
  24776. if (!config.cssIn && !config.baseUrl) {
  24777. //Just use the current directory as the baseUrl
  24778. config.baseUrl = './';
  24779. }
  24780. if (!config.out && !config.dir) {
  24781. throw new Error('Missing either an "out" or "dir" config value. ' +
  24782. 'If using "appDir" for a full project optimization, ' +
  24783. 'use "dir". If you want to optimize to one file, ' +
  24784. 'use "out".');
  24785. }
  24786. if (config.appDir && config.out) {
  24787. throw new Error('"appDir" is not compatible with "out". Use "dir" ' +
  24788. 'instead. appDir is used to copy whole projects, ' +
  24789. 'where "out" with "baseUrl" is used to just ' +
  24790. 'optimize to one file.');
  24791. }
  24792. if (config.out && config.dir) {
  24793. throw new Error('The "out" and "dir" options are incompatible.' +
  24794. ' Use "out" if you are targeting a single file' +
  24795. ' for optimization, and "dir" if you want the appDir' +
  24796. ' or baseUrl directories optimized.');
  24797. }
  24798. if (config.dir) {
  24799. // Make sure the output dir is not set to a parent of the
  24800. // source dir or the same dir, as it will result in source
  24801. // code deletion.
  24802. if (!config.allowSourceOverwrites && (config.dir === config.baseUrl ||
  24803. config.dir === config.appDir ||
  24804. (config.baseUrl && build.makeRelativeFilePath(config.dir,
  24805. config.baseUrl).indexOf('..') !== 0) ||
  24806. (config.appDir &&
  24807. build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) {
  24808. throw new Error('"dir" is set to a parent or same directory as' +
  24809. ' "appDir" or "baseUrl". This can result in' +
  24810. ' the deletion of source code. Stopping. If' +
  24811. ' you want to allow possible overwriting of' +
  24812. ' source code, set "allowSourceOverwrites"' +
  24813. ' to true in the build config, but do so at' +
  24814. ' your own risk. In that case, you may want' +
  24815. ' to also set "keepBuildDir" to true.');
  24816. }
  24817. }
  24818. if (config.insertRequire && !lang.isArray(config.insertRequire)) {
  24819. throw new Error('insertRequire should be a list of module IDs' +
  24820. ' to insert in to a require([]) call.');
  24821. }
  24822. if (config.generateSourceMaps) {
  24823. if (config.preserveLicenseComments && config.optimize !== 'none') {
  24824. throw new Error('Cannot use preserveLicenseComments and ' +
  24825. 'generateSourceMaps together. Either explcitly set ' +
  24826. 'preserveLicenseComments to false (default is true) or ' +
  24827. 'turn off generateSourceMaps. If you want source maps with ' +
  24828. 'license comments, see: ' +
  24829. 'http://requirejs.org/docs/errors.html#sourcemapcomments');
  24830. } else if (config.optimize !== 'none' &&
  24831. config.optimize !== 'closure' &&
  24832. config.optimize !== 'uglify2') {
  24833. //Allow optimize: none to pass, since it is useful when toggling
  24834. //minification on and off to debug something, and it implicitly
  24835. //works, since it does not need a source map.
  24836. throw new Error('optimize: "' + config.optimize +
  24837. '" does not support generateSourceMaps.');
  24838. }
  24839. }
  24840. if ((config.name || config.include) && !config.modules) {
  24841. //Just need to build one file, but may be part of a whole appDir/
  24842. //baseUrl copy, but specified on the command line, so cannot do
  24843. //the modules array setup. So create a modules section in that
  24844. //case.
  24845. config.modules = [
  24846. {
  24847. name: config.name,
  24848. out: config.out,
  24849. create: config.create,
  24850. include: config.include,
  24851. exclude: config.exclude,
  24852. excludeShallow: config.excludeShallow,
  24853. insertRequire: config.insertRequire,
  24854. stubModules: config.stubModules
  24855. }
  24856. ];
  24857. delete config.stubModules;
  24858. } else if (config.modules && config.out) {
  24859. throw new Error('If the "modules" option is used, then there ' +
  24860. 'should be a "dir" option set and "out" should ' +
  24861. 'not be used since "out" is only for single file ' +
  24862. 'optimization output.');
  24863. } else if (config.modules && config.name) {
  24864. throw new Error('"name" and "modules" options are incompatible. ' +
  24865. 'Either use "name" if doing a single file ' +
  24866. 'optimization, or "modules" if you want to target ' +
  24867. 'more than one file for optimization.');
  24868. }
  24869. if (config.out && !config.cssIn) {
  24870. //Just one file to optimize.
  24871. //Does not have a build file, so set up some defaults.
  24872. //Optimizing CSS should not be allowed, unless explicitly
  24873. //asked for on command line. In that case the only task is
  24874. //to optimize a CSS file.
  24875. if (!cfg.optimizeCss) {
  24876. config.optimizeCss = "none";
  24877. }
  24878. }
  24879. //Normalize cssPrefix
  24880. if (config.cssPrefix) {
  24881. //Make sure cssPrefix ends in a slash
  24882. config.cssPrefix = endsWithSlash(config.cssPrefix);
  24883. } else {
  24884. config.cssPrefix = '';
  24885. }
  24886. //Cycle through modules and normalize
  24887. if (config.modules && config.modules.length) {
  24888. config.modules.forEach(function (mod) {
  24889. //Combine any local stubModules with global values.
  24890. if (config.stubModules) {
  24891. mod.stubModules = config.stubModules.concat(mod.stubModules || []);
  24892. }
  24893. //Create a hash lookup for the stubModules config to make lookup
  24894. //cheaper later.
  24895. if (mod.stubModules) {
  24896. mod.stubModules._byName = {};
  24897. mod.stubModules.forEach(function (id) {
  24898. mod.stubModules._byName[id] = true;
  24899. });
  24900. }
  24901. // Legacy command support, which allowed a single string ID
  24902. // for include.
  24903. if (typeof mod.include === 'string') {
  24904. mod.include = [mod.include];
  24905. }
  24906. //Allow wrap config in overrides, but normalize it.
  24907. if (mod.override) {
  24908. normalizeWrapConfig(mod.override, absFilePath);
  24909. }
  24910. });
  24911. }
  24912. normalizeWrapConfig(config, absFilePath);
  24913. //Do final input verification
  24914. if (config.context) {
  24915. throw new Error('The build argument "context" is not supported' +
  24916. ' in a build. It should only be used in web' +
  24917. ' pages.');
  24918. }
  24919. //Set up normalizeDirDefines. If not explicitly set, if optimize "none",
  24920. //set to "skip" otherwise set to "all".
  24921. if (!hasProp(config, 'normalizeDirDefines')) {
  24922. if (config.optimize === 'none' || config.skipDirOptimize) {
  24923. config.normalizeDirDefines = 'skip';
  24924. } else {
  24925. config.normalizeDirDefines = 'all';
  24926. }
  24927. }
  24928. //Set file.fileExclusionRegExp if desired
  24929. if (hasProp(config, 'fileExclusionRegExp')) {
  24930. if (typeof config.fileExclusionRegExp === "string") {
  24931. file.exclusionRegExp = new RegExp(config.fileExclusionRegExp);
  24932. } else {
  24933. file.exclusionRegExp = config.fileExclusionRegExp;
  24934. }
  24935. } else if (hasProp(config, 'dirExclusionRegExp')) {
  24936. //Set file.dirExclusionRegExp if desired, this is the old
  24937. //name for fileExclusionRegExp before 1.0.2. Support for backwards
  24938. //compatibility
  24939. file.exclusionRegExp = config.dirExclusionRegExp;
  24940. }
  24941. //Track the deps, but in a different key, so that they are not loaded
  24942. //as part of config seeding before all config is in play (#648). Was
  24943. //going to merge this in with "include", but include is added after
  24944. //the "name" target. To preserve what r.js has done previously, make
  24945. //sure "deps" comes before the "name".
  24946. if (config.deps) {
  24947. config._depsInclude = config.deps;
  24948. }
  24949. //Remove things that may cause problems in the build.
  24950. //deps already merged above
  24951. delete config.deps;
  24952. delete config.jQuery;
  24953. delete config.enforceDefine;
  24954. delete config.urlArgs;
  24955. return config;
  24956. };
  24957. /**
  24958. * finds the module being built/optimized with the given moduleName,
  24959. * or returns null.
  24960. * @param {String} moduleName
  24961. * @param {Array} modules
  24962. * @returns {Object} the module object from the build profile, or null.
  24963. */
  24964. build.findBuildModule = function (moduleName, modules) {
  24965. var i, module;
  24966. for (i = 0; i < modules.length; i++) {
  24967. module = modules[i];
  24968. if (module.name === moduleName) {
  24969. return module;
  24970. }
  24971. }
  24972. return null;
  24973. };
  24974. /**
  24975. * Removes a module name and path from a layer, if it is supposed to be
  24976. * excluded from the layer.
  24977. * @param {String} moduleName the name of the module
  24978. * @param {String} path the file path for the module
  24979. * @param {Object} layer the layer to remove the module/path from
  24980. */
  24981. build.removeModulePath = function (module, path, layer) {
  24982. var index = layer.buildFilePaths.indexOf(path);
  24983. if (index !== -1) {
  24984. layer.buildFilePaths.splice(index, 1);
  24985. }
  24986. };
  24987. /**
  24988. * Uses the module build config object to trace the dependencies for the
  24989. * given module.
  24990. *
  24991. * @param {Object} module the module object from the build config info.
  24992. * @param {Object} config the build config object.
  24993. * @param {Object} [baseLoaderConfig] the base loader config to use for env resets.
  24994. *
  24995. * @returns {Object} layer information about what paths and modules should
  24996. * be in the flattened module.
  24997. */
  24998. build.traceDependencies = function (module, config, baseLoaderConfig) {
  24999. var include, override, layer, context, oldContext,
  25000. rawTextByIds,
  25001. syncChecks = {
  25002. rhino: true,
  25003. node: true,
  25004. xpconnect: true
  25005. },
  25006. deferred = prim();
  25007. //Reset some state set up in requirePatch.js, and clean up require's
  25008. //current context.
  25009. oldContext = require._buildReset();
  25010. //Grab the reset layer and context after the reset, but keep the
  25011. //old config to reuse in the new context.
  25012. layer = require._layer;
  25013. context = layer.context;
  25014. //Put back basic config, use a fresh object for it.
  25015. if (baseLoaderConfig) {
  25016. require(lang.deeplikeCopy(baseLoaderConfig));
  25017. }
  25018. logger.trace("\nTracing dependencies for: " + (module.name ||
  25019. (typeof module.out === 'function' ? 'FUNCTION' : module.out)));
  25020. include = config._depsInclude || [];
  25021. include = include.concat(module.name && !module.create ? [module.name] : []);
  25022. if (module.include) {
  25023. include = include.concat(module.include);
  25024. }
  25025. //If there are overrides to basic config, set that up now.;
  25026. if (module.override) {
  25027. if (baseLoaderConfig) {
  25028. override = build.createOverrideConfig(baseLoaderConfig, module.override);
  25029. } else {
  25030. override = lang.deeplikeCopy(module.override);
  25031. }
  25032. require(override);
  25033. }
  25034. //Now, populate the rawText cache with any values explicitly passed in
  25035. //via config.
  25036. rawTextByIds = require.s.contexts._.config.rawText;
  25037. if (rawTextByIds) {
  25038. lang.eachProp(rawTextByIds, function (contents, id) {
  25039. var url = require.toUrl(id) + '.js';
  25040. require._cachedRawText[url] = contents;
  25041. });
  25042. }
  25043. //Configure the callbacks to be called.
  25044. deferred.reject.__requireJsBuild = true;
  25045. //Use a wrapping function so can check for errors.
  25046. function includeFinished(value) {
  25047. //If a sync build environment, check for errors here, instead of
  25048. //in the then callback below, since some errors, like two IDs pointed
  25049. //to same URL but only one anon ID will leave the loader in an
  25050. //unresolved state since a setTimeout cannot be used to check for
  25051. //timeout.
  25052. var hasError = false;
  25053. if (syncChecks[env.get()]) {
  25054. try {
  25055. build.checkForErrors(context);
  25056. } catch (e) {
  25057. hasError = true;
  25058. deferred.reject(e);
  25059. }
  25060. }
  25061. if (!hasError) {
  25062. deferred.resolve(value);
  25063. }
  25064. }
  25065. includeFinished.__requireJsBuild = true;
  25066. //Figure out module layer dependencies by calling require to do the work.
  25067. require(include, includeFinished, deferred.reject);
  25068. // If a sync env, then with the "two IDs to same anon module path"
  25069. // issue, the require never completes, need to check for errors
  25070. // here.
  25071. if (syncChecks[env.get()]) {
  25072. build.checkForErrors(context);
  25073. }
  25074. return deferred.promise.then(function () {
  25075. //Reset config
  25076. if (module.override && baseLoaderConfig) {
  25077. require(lang.deeplikeCopy(baseLoaderConfig));
  25078. }
  25079. build.checkForErrors(context);
  25080. return layer;
  25081. });
  25082. };
  25083. build.checkForErrors = function (context) {
  25084. //Check to see if it all loaded. If not, then throw, and give
  25085. //a message on what is left.
  25086. var id, prop, mod, idParts, pluginId, pluginResources,
  25087. errMessage = '',
  25088. failedPluginMap = {},
  25089. failedPluginIds = [],
  25090. errIds = [],
  25091. errUrlMap = {},
  25092. errUrlConflicts = {},
  25093. hasErrUrl = false,
  25094. hasUndefined = false,
  25095. defined = context.defined,
  25096. registry = context.registry;
  25097. function populateErrUrlMap(id, errUrl, skipNew) {
  25098. // Loader plugins do not have an errUrl, so skip them.
  25099. if (!errUrl) {
  25100. return;
  25101. }
  25102. if (!skipNew) {
  25103. errIds.push(id);
  25104. }
  25105. if (errUrlMap[errUrl]) {
  25106. hasErrUrl = true;
  25107. //This error module has the same URL as another
  25108. //error module, could be misconfiguration.
  25109. if (!errUrlConflicts[errUrl]) {
  25110. errUrlConflicts[errUrl] = [];
  25111. //Store the original module that had the same URL.
  25112. errUrlConflicts[errUrl].push(errUrlMap[errUrl]);
  25113. }
  25114. errUrlConflicts[errUrl].push(id);
  25115. } else if (!skipNew) {
  25116. errUrlMap[errUrl] = id;
  25117. }
  25118. }
  25119. for (id in registry) {
  25120. if (hasProp(registry, id) && id.indexOf('_@r') !== 0) {
  25121. hasUndefined = true;
  25122. mod = getOwn(registry, id);
  25123. idParts = id.split('!');
  25124. pluginId = idParts[0];
  25125. if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) {
  25126. populateErrUrlMap(id, mod.map.url);
  25127. }
  25128. //Look for plugins that did not call load()
  25129. if (idParts.length > 1) {
  25130. if (falseProp(failedPluginMap, pluginId)) {
  25131. failedPluginIds.push(pluginId);
  25132. }
  25133. pluginResources = failedPluginMap[pluginId];
  25134. if (!pluginResources) {
  25135. pluginResources = failedPluginMap[pluginId] = [];
  25136. }
  25137. pluginResources.push(id + (mod.error ? ': ' + mod.error : ''));
  25138. }
  25139. }
  25140. }
  25141. // If have some modules that are not defined/stuck in the registry,
  25142. // then check defined modules for URL overlap.
  25143. if (hasUndefined) {
  25144. for (id in defined) {
  25145. if (hasProp(defined, id) && id.indexOf('!') === -1) {
  25146. populateErrUrlMap(id, require.toUrl(id) + '.js', true);
  25147. }
  25148. }
  25149. }
  25150. if (errIds.length || failedPluginIds.length) {
  25151. if (failedPluginIds.length) {
  25152. errMessage += 'Loader plugin' +
  25153. (failedPluginIds.length === 1 ? '' : 's') +
  25154. ' did not call ' +
  25155. 'the load callback in the build:\n' +
  25156. failedPluginIds.map(function (pluginId) {
  25157. var pluginResources = failedPluginMap[pluginId];
  25158. return pluginId + ':\n ' + pluginResources.join('\n ');
  25159. }).join('\n') + '\n';
  25160. }
  25161. errMessage += 'Module loading did not complete for: ' + errIds.join(', ');
  25162. if (hasErrUrl) {
  25163. errMessage += '\nThe following modules share the same URL. This ' +
  25164. 'could be a misconfiguration if that URL only has ' +
  25165. 'one anonymous module in it:';
  25166. for (prop in errUrlConflicts) {
  25167. if (hasProp(errUrlConflicts, prop)) {
  25168. errMessage += '\n' + prop + ': ' +
  25169. errUrlConflicts[prop].join(', ');
  25170. }
  25171. }
  25172. }
  25173. throw new Error(errMessage);
  25174. }
  25175. };
  25176. build.createOverrideConfig = function (config, override) {
  25177. var cfg = lang.deeplikeCopy(config),
  25178. oride = lang.deeplikeCopy(override);
  25179. lang.eachProp(oride, function (value, prop) {
  25180. if (hasProp(build.objProps, prop)) {
  25181. //An object property, merge keys. Start a new object
  25182. //so that source object in config does not get modified.
  25183. cfg[prop] = {};
  25184. lang.mixin(cfg[prop], config[prop], true);
  25185. lang.mixin(cfg[prop], override[prop], true);
  25186. } else {
  25187. cfg[prop] = override[prop];
  25188. }
  25189. });
  25190. return cfg;
  25191. };
  25192. /**
  25193. * Uses the module build config object to create an flattened version
  25194. * of the module, with deep dependencies included.
  25195. *
  25196. * @param {Object} module the module object from the build config info.
  25197. *
  25198. * @param {Object} layer the layer object returned from build.traceDependencies.
  25199. *
  25200. * @param {Object} the build config object.
  25201. *
  25202. * @returns {Object} with two properties: "text", the text of the flattened
  25203. * module, and "buildText", a string of text representing which files were
  25204. * included in the flattened module text.
  25205. */
  25206. build.flattenModule = function (module, layer, config) {
  25207. var fileContents, sourceMapGenerator,
  25208. sourceMapBase,
  25209. buildFileContents = '';
  25210. return prim().start(function () {
  25211. var reqIndex, currContents, fileForSourceMap,
  25212. moduleName, shim, packageName,
  25213. parts, builder, writeApi,
  25214. namespace, namespaceWithDot, stubModulesByName,
  25215. context = layer.context,
  25216. onLayerEnds = [],
  25217. onLayerEndAdded = {},
  25218. pkgsMainMap = {};
  25219. //Use override settings, particularly for pragmas
  25220. //Do this before the var readings since it reads config values.
  25221. if (module.override) {
  25222. config = build.createOverrideConfig(config, module.override);
  25223. }
  25224. namespace = config.namespace || '';
  25225. namespaceWithDot = namespace ? namespace + '.' : '';
  25226. stubModulesByName = (module.stubModules && module.stubModules._byName) || {};
  25227. //Start build output for the module.
  25228. module.onCompleteData = {
  25229. name: module.name,
  25230. path: (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath),
  25231. included: []
  25232. };
  25233. buildFileContents += "\n" +
  25234. module.onCompleteData.path +
  25235. "\n----------------\n";
  25236. //If there was an existing file with require in it, hoist to the top.
  25237. if (layer.existingRequireUrl) {
  25238. reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl);
  25239. if (reqIndex !== -1) {
  25240. layer.buildFilePaths.splice(reqIndex, 1);
  25241. layer.buildFilePaths.unshift(layer.existingRequireUrl);
  25242. }
  25243. }
  25244. if (config.generateSourceMaps) {
  25245. sourceMapBase = config.dir || config.baseUrl;
  25246. fileForSourceMap = module._buildPath === 'FUNCTION' ?
  25247. (module.name || module.include[0] || 'FUNCTION') + '.build.js' :
  25248. module._buildPath.replace(sourceMapBase, '');
  25249. sourceMapGenerator = new SourceMapGenerator.SourceMapGenerator({
  25250. file: fileForSourceMap
  25251. });
  25252. }
  25253. //Create a reverse lookup for packages main module IDs to their package
  25254. //names, useful for knowing when to write out define() package main ID
  25255. //adapters.
  25256. lang.eachProp(layer.context.config.pkgs, function(value, prop) {
  25257. pkgsMainMap[value] = prop;
  25258. });
  25259. //Write the built module to disk, and build up the build output.
  25260. fileContents = config.wrap ? config.wrap.start : "";
  25261. return prim.serial(layer.buildFilePaths.map(function (path) {
  25262. return function () {
  25263. var lineCount,
  25264. singleContents = '';
  25265. moduleName = layer.buildFileToModule[path];
  25266. //If the moduleName is a package main, then hold on to the
  25267. //packageName in case an adapter needs to be written.
  25268. packageName = getOwn(pkgsMainMap, moduleName);
  25269. return prim().start(function () {
  25270. //Figure out if the module is a result of a build plugin, and if so,
  25271. //then delegate to that plugin.
  25272. parts = context.makeModuleMap(moduleName);
  25273. builder = parts.prefix && getOwn(context.defined, parts.prefix);
  25274. if (builder) {
  25275. if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) {
  25276. onLayerEnds.push(builder);
  25277. onLayerEndAdded[parts.prefix] = true;
  25278. }
  25279. if (builder.write) {
  25280. writeApi = function (input) {
  25281. singleContents += "\n" + addSemiColon(input, config);
  25282. if (config.onBuildWrite) {
  25283. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  25284. }
  25285. };
  25286. writeApi.asModule = function (moduleName, input) {
  25287. singleContents += "\n" +
  25288. addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, {
  25289. useSourceUrl: layer.context.config.useSourceUrl
  25290. }), config);
  25291. if (config.onBuildWrite) {
  25292. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  25293. }
  25294. };
  25295. builder.write(parts.prefix, parts.name, writeApi);
  25296. }
  25297. return;
  25298. } else {
  25299. return prim().start(function () {
  25300. if (hasProp(stubModulesByName, moduleName)) {
  25301. //Just want to insert a simple module definition instead
  25302. //of the source module. Useful for plugins that inline
  25303. //all their resources.
  25304. if (hasProp(layer.context.plugins, moduleName)) {
  25305. //Slightly different content for plugins, to indicate
  25306. //that dynamic loading will not work.
  25307. return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});';
  25308. } else {
  25309. return 'define({});';
  25310. }
  25311. } else {
  25312. return require._cacheReadAsync(path);
  25313. }
  25314. }).then(function (text) {
  25315. var hasPackageName;
  25316. currContents = text;
  25317. if (config.cjsTranslate &&
  25318. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  25319. currContents = commonJs.convert(path, currContents);
  25320. }
  25321. if (config.onBuildRead) {
  25322. currContents = config.onBuildRead(moduleName, path, currContents);
  25323. }
  25324. if (packageName) {
  25325. hasPackageName = (packageName === parse.getNamedDefine(currContents));
  25326. }
  25327. if (namespace) {
  25328. currContents = pragma.namespace(currContents, namespace);
  25329. }
  25330. currContents = build.toTransport(namespace, moduleName, path, currContents, layer, {
  25331. useSourceUrl: config.useSourceUrl
  25332. });
  25333. if (packageName && !hasPackageName) {
  25334. currContents = addSemiColon(currContents, config) + '\n';
  25335. currContents += namespaceWithDot + "define('" +
  25336. packageName + "', ['" + moduleName +
  25337. "'], function (main) { return main; });\n";
  25338. }
  25339. if (config.onBuildWrite) {
  25340. currContents = config.onBuildWrite(moduleName, path, currContents);
  25341. }
  25342. //Semicolon is for files that are not well formed when
  25343. //concatenated with other content.
  25344. singleContents += addSemiColon(currContents, config);
  25345. });
  25346. }
  25347. }).then(function () {
  25348. var refPath, pluginId, resourcePath,
  25349. sourceMapPath, sourceMapLineNumber,
  25350. shortPath = path.replace(config.dir, "");
  25351. module.onCompleteData.included.push(shortPath);
  25352. buildFileContents += shortPath + "\n";
  25353. //Some files may not have declared a require module, and if so,
  25354. //put in a placeholder call so the require does not try to load them
  25355. //after the module is processed.
  25356. //If we have a name, but no defined module, then add in the placeholder.
  25357. if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) {
  25358. shim = config.shim && (getOwn(config.shim, moduleName) || (packageName && getOwn(config.shim, packageName)));
  25359. if (shim) {
  25360. if (config.wrapShim) {
  25361. singleContents = '(function(root) {\n' +
  25362. namespaceWithDot + 'define("' + moduleName + '", ' +
  25363. (shim.deps && shim.deps.length ?
  25364. build.makeJsArrayString(shim.deps) + ', ' : '[], ') +
  25365. 'function() {\n' +
  25366. ' return (function() {\n' +
  25367. singleContents +
  25368. // Start with a \n in case last line is a comment
  25369. // in the singleContents, like a sourceURL comment.
  25370. '\n' + (shim.exportsFn ? shim.exportsFn() : '') +
  25371. '\n' +
  25372. ' }).apply(root, arguments);\n' +
  25373. '});\n' +
  25374. '}(this));\n';
  25375. } else {
  25376. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' +
  25377. (shim.deps && shim.deps.length ?
  25378. build.makeJsArrayString(shim.deps) + ', ' : '') +
  25379. (shim.exportsFn ? shim.exportsFn() : 'function(){}') +
  25380. ');\n';
  25381. }
  25382. } else {
  25383. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n';
  25384. }
  25385. }
  25386. //Add line break at end of file, instead of at beginning,
  25387. //so source map line numbers stay correct, but still allow
  25388. //for some space separation between files in case ASI issues
  25389. //for concatenation would cause an error otherwise.
  25390. singleContents += '\n';
  25391. //Add to the source map
  25392. if (sourceMapGenerator) {
  25393. refPath = config.out ? config.baseUrl : module._buildPath;
  25394. parts = path.split('!');
  25395. if (parts.length === 1) {
  25396. //Not a plugin resource, fix the path
  25397. sourceMapPath = build.makeRelativeFilePath(refPath, path);
  25398. } else {
  25399. //Plugin resource. If it looks like just a plugin
  25400. //followed by a module ID, pull off the plugin
  25401. //and put it at the end of the name, otherwise
  25402. //just leave it alone.
  25403. pluginId = parts.shift();
  25404. resourcePath = parts.join('!');
  25405. if (resourceIsModuleIdRegExp.test(resourcePath)) {
  25406. sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) +
  25407. '!' + pluginId;
  25408. } else {
  25409. sourceMapPath = path;
  25410. }
  25411. }
  25412. sourceMapLineNumber = fileContents.split('\n').length - 1;
  25413. lineCount = singleContents.split('\n').length;
  25414. for (var i = 1; i <= lineCount; i += 1) {
  25415. sourceMapGenerator.addMapping({
  25416. generated: {
  25417. line: sourceMapLineNumber + i,
  25418. column: 0
  25419. },
  25420. original: {
  25421. line: i,
  25422. column: 0
  25423. },
  25424. source: sourceMapPath
  25425. });
  25426. }
  25427. //Store the content of the original in the source
  25428. //map since other transforms later like minification
  25429. //can mess up translating back to the original
  25430. //source.
  25431. sourceMapGenerator.setSourceContent(sourceMapPath, singleContents);
  25432. }
  25433. //Add the file to the final contents
  25434. fileContents += singleContents;
  25435. });
  25436. };
  25437. })).then(function () {
  25438. if (onLayerEnds.length) {
  25439. onLayerEnds.forEach(function (builder) {
  25440. var path;
  25441. if (typeof module.out === 'string') {
  25442. path = module.out;
  25443. } else if (typeof module._buildPath === 'string') {
  25444. path = module._buildPath;
  25445. }
  25446. builder.onLayerEnd(function (input) {
  25447. fileContents += "\n" + addSemiColon(input, config);
  25448. }, {
  25449. name: module.name,
  25450. path: path
  25451. });
  25452. });
  25453. }
  25454. if (module.create) {
  25455. //The ID is for a created layer. Write out
  25456. //a module definition for it in case the
  25457. //built file is used with enforceDefine
  25458. //(#432)
  25459. fileContents += '\n' + namespaceWithDot + 'define("' + module.name + '", function(){});\n';
  25460. }
  25461. //Add a require at the end to kick start module execution, if that
  25462. //was desired. Usually this is only specified when using small shim
  25463. //loaders like almond.
  25464. if (module.insertRequire) {
  25465. fileContents += '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') + '"]);\n';
  25466. }
  25467. });
  25468. }).then(function () {
  25469. return {
  25470. text: config.wrap ?
  25471. fileContents + config.wrap.end :
  25472. fileContents,
  25473. buildText: buildFileContents,
  25474. sourceMap: sourceMapGenerator ?
  25475. JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') :
  25476. undefined
  25477. };
  25478. });
  25479. };
  25480. //Converts an JS array of strings to a string representation.
  25481. //Not using JSON.stringify() for Rhino's sake.
  25482. build.makeJsArrayString = function (ary) {
  25483. return '["' + ary.map(function (item) {
  25484. //Escape any double quotes, backslashes
  25485. return lang.jsEscape(item);
  25486. }).join('","') + '"]';
  25487. };
  25488. build.toTransport = function (namespace, moduleName, path, contents, layer, options) {
  25489. var baseUrl = layer && layer.context.config.baseUrl;
  25490. function onFound(info) {
  25491. //Only mark this module as having a name if not a named module,
  25492. //or if a named module and the name matches expectations.
  25493. if (layer && (info.needsId || info.foundId === moduleName)) {
  25494. layer.modulesWithNames[moduleName] = true;
  25495. }
  25496. }
  25497. //Convert path to be a local one to the baseUrl, useful for
  25498. //useSourceUrl.
  25499. if (baseUrl) {
  25500. path = path.replace(baseUrl, '');
  25501. }
  25502. return transform.toTransport(namespace, moduleName, path, contents, onFound, options);
  25503. };
  25504. return build;
  25505. });
  25506. }
  25507. /**
  25508. * Sets the default baseUrl for requirejs to be directory of top level
  25509. * script.
  25510. */
  25511. function setBaseUrl(fileName) {
  25512. //Use the file name's directory as the baseUrl if available.
  25513. dir = fileName.replace(/\\/g, '/');
  25514. if (dir.indexOf('/') !== -1) {
  25515. dir = dir.split('/');
  25516. dir.pop();
  25517. dir = dir.join('/');
  25518. //Make sure dir is JS-escaped, since it will be part of a JS string.
  25519. exec("require({baseUrl: '" + dir.replace(/[\\"']/g, '\\$&') + "'});");
  25520. }
  25521. }
  25522. function createRjsApi() {
  25523. //Create a method that will run the optimzer given an object
  25524. //config.
  25525. requirejs.optimize = function (config, callback, errback) {
  25526. if (!loadedOptimizedLib) {
  25527. loadLib();
  25528. loadedOptimizedLib = true;
  25529. }
  25530. //Create the function that will be called once build modules
  25531. //have been loaded.
  25532. var runBuild = function (build, logger, quit) {
  25533. //Make sure config has a log level, and if not,
  25534. //make it "silent" by default.
  25535. config.logLevel = config.hasOwnProperty('logLevel') ?
  25536. config.logLevel : logger.SILENT;
  25537. //Reset build internals first in case this is part
  25538. //of a long-running server process that could have
  25539. //exceptioned out in a bad state. It is only defined
  25540. //after the first call though.
  25541. if (requirejs._buildReset) {
  25542. requirejs._buildReset();
  25543. requirejs._cacheReset();
  25544. }
  25545. function done(result) {
  25546. //And clean up, in case something else triggers
  25547. //a build in another pathway.
  25548. if (requirejs._buildReset) {
  25549. requirejs._buildReset();
  25550. requirejs._cacheReset();
  25551. }
  25552. // Ensure errors get propagated to the errback
  25553. if (result instanceof Error) {
  25554. throw result;
  25555. }
  25556. return result;
  25557. }
  25558. errback = errback || function (err) {
  25559. // Using console here since logger may have
  25560. // turned off error logging. Since quit is
  25561. // called want to be sure a message is printed.
  25562. console.log(err);
  25563. quit(1);
  25564. };
  25565. build(config).then(done, done).then(callback, errback);
  25566. };
  25567. requirejs({
  25568. context: 'build'
  25569. }, ['build', 'logger', 'env!env/quit'], runBuild);
  25570. };
  25571. requirejs.tools = {
  25572. useLib: function (contextName, callback) {
  25573. if (!callback) {
  25574. callback = contextName;
  25575. contextName = 'uselib';
  25576. }
  25577. if (!useLibLoaded[contextName]) {
  25578. loadLib();
  25579. useLibLoaded[contextName] = true;
  25580. }
  25581. var req = requirejs({
  25582. context: contextName
  25583. });
  25584. req(['build'], function () {
  25585. callback(req);
  25586. });
  25587. }
  25588. };
  25589. requirejs.define = define;
  25590. }
  25591. //If in Node, and included via a require('requirejs'), just export and
  25592. //THROW IT ON THE GROUND!
  25593. if (env === 'node' && reqMain !== module) {
  25594. setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.'));
  25595. createRjsApi();
  25596. module.exports = requirejs;
  25597. return;
  25598. } else if (env === 'browser') {
  25599. //Only option is to use the API.
  25600. setBaseUrl(location.href);
  25601. createRjsApi();
  25602. return;
  25603. } else if ((env === 'rhino' || env === 'xpconnect') &&
  25604. //User sets up requirejsAsLib variable to indicate it is loaded
  25605. //via load() to be used as a library.
  25606. typeof requirejsAsLib !== 'undefined' && requirejsAsLib) {
  25607. //This script is loaded via rhino's load() method, expose the
  25608. //API and get out.
  25609. setBaseUrl(fileName);
  25610. createRjsApi();
  25611. return;
  25612. }
  25613. if (commandOption === 'o') {
  25614. //Do the optimizer work.
  25615. loadLib();
  25616. /**
  25617. * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
  25618. * Available via the MIT or new BSD license.
  25619. * see: http://github.com/jrburke/requirejs for details
  25620. */
  25621. /*
  25622. * Create a build.js file that has the build options you want and pass that
  25623. * build file to this file to do the build. See example.build.js for more information.
  25624. */
  25625. /*jslint strict: false, nomen: false */
  25626. /*global require: false */
  25627. require({
  25628. baseUrl: require.s.contexts._.config.baseUrl,
  25629. //Use a separate context than the default context so that the
  25630. //build can use the default context.
  25631. context: 'build',
  25632. catchError: {
  25633. define: true
  25634. }
  25635. }, ['env!env/args', 'env!env/quit', 'logger', 'build'],
  25636. function (args, quit, logger, build) {
  25637. build(args).then(function () {}, function (err) {
  25638. logger.error(err);
  25639. quit(1);
  25640. });
  25641. });
  25642. } else if (commandOption === 'v') {
  25643. console.log('r.js: ' + version +
  25644. ', RequireJS: ' + this.requirejsVars.require.version +
  25645. ', UglifyJS2: 2.4.16, UglifyJS: 1.3.4');
  25646. } else if (commandOption === 'convert') {
  25647. loadLib();
  25648. this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'],
  25649. function (args, commonJs, print) {
  25650. var srcDir, outDir;
  25651. srcDir = args[0];
  25652. outDir = args[1];
  25653. if (!srcDir || !outDir) {
  25654. print('Usage: path/to/commonjs/modules output/dir');
  25655. return;
  25656. }
  25657. commonJs.convertDir(args[0], args[1]);
  25658. });
  25659. } else {
  25660. //Just run an app
  25661. //Load the bundled libraries for use in the app.
  25662. if (commandOption === 'lib') {
  25663. loadLib();
  25664. }
  25665. setBaseUrl(fileName);
  25666. if (exists(fileName)) {
  25667. exec(readFile(fileName), fileName);
  25668. } else {
  25669. showHelp();
  25670. }
  25671. }
  25672. }((typeof console !== 'undefined' ? console : undefined),
  25673. (typeof Packages !== 'undefined' || (typeof window === 'undefined' &&
  25674. typeof Components !== 'undefined' && Components.interfaces) ?
  25675. Array.prototype.slice.call(arguments, 0) : []),
  25676. (typeof readFile !== 'undefined' ? readFile : undefined)));