r.js 910 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530
  1. /**
  2. * @license r.js 2.1.5 Copyright (c) 2010-2012, 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.5',
  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 Packages !== 'undefined') {
  46. env = 'rhino';
  47. fileName = args[0];
  48. if (fileName && fileName.indexOf('-') === 0) {
  49. commandOption = fileName.substring(1);
  50. fileName = args[1];
  51. }
  52. //Set up execution context.
  53. rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext();
  54. exec = function (string, name) {
  55. return rhinoContext.evaluateString(this, string, name, 0, null);
  56. };
  57. exists = function (fileName) {
  58. return (new java.io.File(fileName)).exists();
  59. };
  60. //Define a console.log for easier logging. Don't
  61. //get fancy though.
  62. if (typeof console === 'undefined') {
  63. console = {
  64. log: function () {
  65. print.apply(undefined, arguments);
  66. }
  67. };
  68. }
  69. } else if (typeof process !== 'undefined') {
  70. env = 'node';
  71. //Get the fs module via Node's require before it
  72. //gets replaced. Used in require/node.js
  73. fs = require('fs');
  74. vm = require('vm');
  75. path = require('path');
  76. //In Node 0.7+ existsSync is on fs.
  77. existsForNode = fs.existsSync || path.existsSync;
  78. nodeRequire = require;
  79. nodeDefine = define;
  80. reqMain = require.main;
  81. //Temporarily hide require and define to allow require.js to define
  82. //them.
  83. require = undefined;
  84. define = undefined;
  85. readFile = function (path) {
  86. return fs.readFileSync(path, 'utf8');
  87. };
  88. exec = function (string, name) {
  89. return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string),
  90. name ? fs.realpathSync(name) : '');
  91. };
  92. exists = function (fileName) {
  93. return existsForNode(fileName);
  94. };
  95. fileName = process.argv[2];
  96. if (fileName && fileName.indexOf('-') === 0) {
  97. commandOption = fileName.substring(1);
  98. fileName = process.argv[3];
  99. }
  100. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  101. env = 'xpconnect';
  102. Components.utils['import']('resource://gre/modules/FileUtils.jsm');
  103. Cc = Components.classes;
  104. Ci = Components.interfaces;
  105. fileName = args[0];
  106. if (fileName && fileName.indexOf('-') === 0) {
  107. commandOption = fileName.substring(1);
  108. fileName = args[1];
  109. }
  110. xpcUtil = {
  111. cwd: function () {
  112. return FileUtils.getFile("CurWorkD", []).path;
  113. },
  114. //Remove . and .. from paths, normalize on front slashes
  115. normalize: function (path) {
  116. //There has to be an easier way to do this.
  117. var i, part, ary,
  118. firstChar = path.charAt(0);
  119. if (firstChar !== '/' &&
  120. firstChar !== '\\' &&
  121. path.indexOf(':') === -1) {
  122. //A relative path. Use the current working directory.
  123. path = xpcUtil.cwd() + '/' + path;
  124. }
  125. ary = path.replace(/\\/g, '/').split('/');
  126. for (i = 0; i < ary.length; i += 1) {
  127. part = ary[i];
  128. if (part === '.') {
  129. ary.splice(i, 1);
  130. i -= 1;
  131. } else if (part === '..') {
  132. ary.splice(i - 1, 2);
  133. i -= 2;
  134. }
  135. }
  136. return ary.join('/');
  137. },
  138. xpfile: function (path) {
  139. try {
  140. return new FileUtils.File(xpcUtil.normalize(path));
  141. } catch (e) {
  142. throw new Error(path + ' failed: ' + e);
  143. }
  144. },
  145. readFile: function (/*String*/path, /*String?*/encoding) {
  146. //A file read function that can deal with BOMs
  147. encoding = encoding || "utf-8";
  148. var inStream, convertStream,
  149. readData = {},
  150. fileObj = xpcUtil.xpfile(path);
  151. //XPCOM, you so crazy
  152. try {
  153. inStream = Cc['@mozilla.org/network/file-input-stream;1']
  154. .createInstance(Ci.nsIFileInputStream);
  155. inStream.init(fileObj, 1, 0, false);
  156. convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
  157. .createInstance(Ci.nsIConverterInputStream);
  158. convertStream.init(inStream, encoding, inStream.available(),
  159. Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
  160. convertStream.readString(inStream.available(), readData);
  161. return readData.value;
  162. } catch (e) {
  163. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  164. } finally {
  165. if (convertStream) {
  166. convertStream.close();
  167. }
  168. if (inStream) {
  169. inStream.close();
  170. }
  171. }
  172. }
  173. };
  174. readFile = xpcUtil.readFile;
  175. exec = function (string) {
  176. return eval(string);
  177. };
  178. exists = function (fileName) {
  179. return xpcUtil.xpfile(fileName).exists();
  180. };
  181. //Define a console.log for easier logging. Don't
  182. //get fancy though.
  183. if (typeof console === 'undefined') {
  184. console = {
  185. log: function () {
  186. print.apply(undefined, arguments);
  187. }
  188. };
  189. }
  190. }
  191. /** vim: et:ts=4:sw=4:sts=4
  192. * @license RequireJS 2.1.5 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
  193. * Available via the MIT or new BSD license.
  194. * see: http://github.com/jrburke/requirejs for details
  195. */
  196. //Not using strict: uneven strict support in browsers, #392, and causes
  197. //problems with requirejs.exec()/transpiler plugins that may not be strict.
  198. /*jslint regexp: true, nomen: true, sloppy: true */
  199. /*global window, navigator, document, importScripts, setTimeout, opera */
  200. (function (global) {
  201. var req, s, head, baseElement, dataMain, src,
  202. interactiveScript, currentlyAddingScript, mainScript, subPath,
  203. version = '2.1.5',
  204. commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
  205. cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
  206. jsSuffixRegExp = /\.js$/,
  207. currDirRegExp = /^\.\//,
  208. op = Object.prototype,
  209. ostring = op.toString,
  210. hasOwn = op.hasOwnProperty,
  211. ap = Array.prototype,
  212. apsp = ap.splice,
  213. isBrowser = !!(typeof window !== 'undefined' && navigator && document),
  214. isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
  215. //PS3 indicates loaded and complete, but need to wait for complete
  216. //specifically. Sequence is 'loading', 'loaded', execution,
  217. // then 'complete'. The UA check is unfortunate, but not sure how
  218. //to feature test w/o causing perf issues.
  219. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
  220. /^complete$/ : /^(complete|loaded)$/,
  221. defContextName = '_',
  222. //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
  223. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
  224. contexts = {},
  225. cfg = {},
  226. globalDefQueue = [],
  227. useInteractive = false;
  228. function isFunction(it) {
  229. return ostring.call(it) === '[object Function]';
  230. }
  231. function isArray(it) {
  232. return ostring.call(it) === '[object Array]';
  233. }
  234. /**
  235. * Helper function for iterating over an array. If the func returns
  236. * a true value, it will break out of the loop.
  237. */
  238. function each(ary, func) {
  239. if (ary) {
  240. var i;
  241. for (i = 0; i < ary.length; i += 1) {
  242. if (ary[i] && func(ary[i], i, ary)) {
  243. break;
  244. }
  245. }
  246. }
  247. }
  248. /**
  249. * Helper function for iterating over an array backwards. If the func
  250. * returns a true value, it will break out of the loop.
  251. */
  252. function eachReverse(ary, func) {
  253. if (ary) {
  254. var i;
  255. for (i = ary.length - 1; i > -1; i -= 1) {
  256. if (ary[i] && func(ary[i], i, ary)) {
  257. break;
  258. }
  259. }
  260. }
  261. }
  262. function hasProp(obj, prop) {
  263. return hasOwn.call(obj, prop);
  264. }
  265. function getOwn(obj, prop) {
  266. return hasProp(obj, prop) && obj[prop];
  267. }
  268. /**
  269. * Cycles over properties in an object and calls a function for each
  270. * property value. If the function returns a truthy value, then the
  271. * iteration is stopped.
  272. */
  273. function eachProp(obj, func) {
  274. var prop;
  275. for (prop in obj) {
  276. if (hasProp(obj, prop)) {
  277. if (func(obj[prop], prop)) {
  278. break;
  279. }
  280. }
  281. }
  282. }
  283. /**
  284. * Simple function to mix in properties from source into target,
  285. * but only if target does not already have a property of the same name.
  286. */
  287. function mixin(target, source, force, deepStringMixin) {
  288. if (source) {
  289. eachProp(source, function (value, prop) {
  290. if (force || !hasProp(target, prop)) {
  291. if (deepStringMixin && typeof value !== 'string') {
  292. if (!target[prop]) {
  293. target[prop] = {};
  294. }
  295. mixin(target[prop], value, force, deepStringMixin);
  296. } else {
  297. target[prop] = value;
  298. }
  299. }
  300. });
  301. }
  302. return target;
  303. }
  304. //Similar to Function.prototype.bind, but the 'this' object is specified
  305. //first, since it is easier to read/figure out what 'this' will be.
  306. function bind(obj, fn) {
  307. return function () {
  308. return fn.apply(obj, arguments);
  309. };
  310. }
  311. function scripts() {
  312. return document.getElementsByTagName('script');
  313. }
  314. //Allow getting a global that expressed in
  315. //dot notation, like 'a.b.c'.
  316. function getGlobal(value) {
  317. if (!value) {
  318. return value;
  319. }
  320. var g = global;
  321. each(value.split('.'), function (part) {
  322. g = g[part];
  323. });
  324. return g;
  325. }
  326. /**
  327. * Constructs an error with a pointer to an URL with more information.
  328. * @param {String} id the error ID that maps to an ID on a web page.
  329. * @param {String} message human readable error.
  330. * @param {Error} [err] the original error, if there is one.
  331. *
  332. * @returns {Error}
  333. */
  334. function makeError(id, msg, err, requireModules) {
  335. var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
  336. e.requireType = id;
  337. e.requireModules = requireModules;
  338. if (err) {
  339. e.originalError = err;
  340. }
  341. return e;
  342. }
  343. if (typeof define !== 'undefined') {
  344. //If a define is already in play via another AMD loader,
  345. //do not overwrite.
  346. return;
  347. }
  348. if (typeof requirejs !== 'undefined') {
  349. if (isFunction(requirejs)) {
  350. //Do not overwrite and existing requirejs instance.
  351. return;
  352. }
  353. cfg = requirejs;
  354. requirejs = undefined;
  355. }
  356. //Allow for a require config object
  357. if (typeof require !== 'undefined' && !isFunction(require)) {
  358. //assume it is a config object.
  359. cfg = require;
  360. require = undefined;
  361. }
  362. function newContext(contextName) {
  363. var inCheckLoaded, Module, context, handlers,
  364. checkLoadedTimeoutId,
  365. config = {
  366. //Defaults. Do not set a default for map
  367. //config to speed up normalize(), which
  368. //will run faster if there is no default.
  369. waitSeconds: 7,
  370. baseUrl: './',
  371. paths: {},
  372. pkgs: {},
  373. shim: {},
  374. config: {}
  375. },
  376. registry = {},
  377. //registry of just enabled modules, to speed
  378. //cycle breaking code when lots of modules
  379. //are registered, but not activated.
  380. enabledRegistry = {},
  381. undefEvents = {},
  382. defQueue = [],
  383. defined = {},
  384. urlFetched = {},
  385. requireCounter = 1,
  386. unnormalizedCounter = 1;
  387. /**
  388. * Trims the . and .. from an array of path segments.
  389. * It will keep a leading path segment if a .. will become
  390. * the first path segment, to help with module name lookups,
  391. * which act like paths, but can be remapped. But the end result,
  392. * all paths that use this function should look normalized.
  393. * NOTE: this method MODIFIES the input array.
  394. * @param {Array} ary the array of path segments.
  395. */
  396. function trimDots(ary) {
  397. var i, part;
  398. for (i = 0; ary[i]; i += 1) {
  399. part = ary[i];
  400. if (part === '.') {
  401. ary.splice(i, 1);
  402. i -= 1;
  403. } else if (part === '..') {
  404. if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
  405. //End of the line. Keep at least one non-dot
  406. //path segment at the front so it can be mapped
  407. //correctly to disk. Otherwise, there is likely
  408. //no path mapping for a path starting with '..'.
  409. //This can still fail, but catches the most reasonable
  410. //uses of ..
  411. break;
  412. } else if (i > 0) {
  413. ary.splice(i - 1, 2);
  414. i -= 2;
  415. }
  416. }
  417. }
  418. }
  419. /**
  420. * Given a relative module name, like ./something, normalize it to
  421. * a real name that can be mapped to a path.
  422. * @param {String} name the relative name
  423. * @param {String} baseName a real name that the name arg is relative
  424. * to.
  425. * @param {Boolean} applyMap apply the map config to the value. Should
  426. * only be done if this normalization is for a dependency ID.
  427. * @returns {String} normalized name
  428. */
  429. function normalize(name, baseName, applyMap) {
  430. var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
  431. foundMap, foundI, foundStarMap, starI,
  432. baseParts = baseName && baseName.split('/'),
  433. normalizedBaseParts = baseParts,
  434. map = config.map,
  435. starMap = map && map['*'];
  436. //Adjust any relative paths.
  437. if (name && name.charAt(0) === '.') {
  438. //If have a base name, try to normalize against it,
  439. //otherwise, assume it is a top-level require that will
  440. //be relative to baseUrl in the end.
  441. if (baseName) {
  442. if (getOwn(config.pkgs, baseName)) {
  443. //If the baseName is a package name, then just treat it as one
  444. //name to concat the name with.
  445. normalizedBaseParts = baseParts = [baseName];
  446. } else {
  447. //Convert baseName to array, and lop off the last part,
  448. //so that . matches that 'directory' and not name of the baseName's
  449. //module. For instance, baseName of 'one/two/three', maps to
  450. //'one/two/three.js', but we want the directory, 'one/two' for
  451. //this normalization.
  452. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
  453. }
  454. name = normalizedBaseParts.concat(name.split('/'));
  455. trimDots(name);
  456. //Some use of packages may use a . path to reference the
  457. //'main' module name, so normalize for that.
  458. pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));
  459. name = name.join('/');
  460. if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
  461. name = pkgName;
  462. }
  463. } else if (name.indexOf('./') === 0) {
  464. // No baseName, so this is ID is resolved relative
  465. // to baseUrl, pull off the leading dot.
  466. name = name.substring(2);
  467. }
  468. }
  469. //Apply map config if available.
  470. if (applyMap && map && (baseParts || starMap)) {
  471. nameParts = name.split('/');
  472. for (i = nameParts.length; i > 0; i -= 1) {
  473. nameSegment = nameParts.slice(0, i).join('/');
  474. if (baseParts) {
  475. //Find the longest baseName segment match in the config.
  476. //So, do joins on the biggest to smallest lengths of baseParts.
  477. for (j = baseParts.length; j > 0; j -= 1) {
  478. mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
  479. //baseName segment has config, find if it has one for
  480. //this name.
  481. if (mapValue) {
  482. mapValue = getOwn(mapValue, nameSegment);
  483. if (mapValue) {
  484. //Match, update name to the new value.
  485. foundMap = mapValue;
  486. foundI = i;
  487. break;
  488. }
  489. }
  490. }
  491. }
  492. if (foundMap) {
  493. break;
  494. }
  495. //Check for a star map match, but just hold on to it,
  496. //if there is a shorter segment match later in a matching
  497. //config, then favor over this star map.
  498. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
  499. foundStarMap = getOwn(starMap, nameSegment);
  500. starI = i;
  501. }
  502. }
  503. if (!foundMap && foundStarMap) {
  504. foundMap = foundStarMap;
  505. foundI = starI;
  506. }
  507. if (foundMap) {
  508. nameParts.splice(0, foundI, foundMap);
  509. name = nameParts.join('/');
  510. }
  511. }
  512. return name;
  513. }
  514. function removeScript(name) {
  515. if (isBrowser) {
  516. each(scripts(), function (scriptNode) {
  517. if (scriptNode.getAttribute('data-requiremodule') === name &&
  518. scriptNode.getAttribute('data-requirecontext') === context.contextName) {
  519. scriptNode.parentNode.removeChild(scriptNode);
  520. return true;
  521. }
  522. });
  523. }
  524. }
  525. function hasPathFallback(id) {
  526. var pathConfig = getOwn(config.paths, id);
  527. if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
  528. removeScript(id);
  529. //Pop off the first array value, since it failed, and
  530. //retry
  531. pathConfig.shift();
  532. context.require.undef(id);
  533. context.require([id]);
  534. return true;
  535. }
  536. }
  537. //Turns a plugin!resource to [plugin, resource]
  538. //with the plugin being undefined if the name
  539. //did not have a plugin prefix.
  540. function splitPrefix(name) {
  541. var prefix,
  542. index = name ? name.indexOf('!') : -1;
  543. if (index > -1) {
  544. prefix = name.substring(0, index);
  545. name = name.substring(index + 1, name.length);
  546. }
  547. return [prefix, name];
  548. }
  549. /**
  550. * Creates a module mapping that includes plugin prefix, module
  551. * name, and path. If parentModuleMap is provided it will
  552. * also normalize the name via require.normalize()
  553. *
  554. * @param {String} name the module name
  555. * @param {String} [parentModuleMap] parent module map
  556. * for the module name, used to resolve relative names.
  557. * @param {Boolean} isNormalized: is the ID already normalized.
  558. * This is true if this call is done for a define() module ID.
  559. * @param {Boolean} applyMap: apply the map config to the ID.
  560. * Should only be true if this map is for a dependency.
  561. *
  562. * @returns {Object}
  563. */
  564. function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
  565. var url, pluginModule, suffix, nameParts,
  566. prefix = null,
  567. parentName = parentModuleMap ? parentModuleMap.name : null,
  568. originalName = name,
  569. isDefine = true,
  570. normalizedName = '';
  571. //If no name, then it means it is a require call, generate an
  572. //internal name.
  573. if (!name) {
  574. isDefine = false;
  575. name = '_@r' + (requireCounter += 1);
  576. }
  577. nameParts = splitPrefix(name);
  578. prefix = nameParts[0];
  579. name = nameParts[1];
  580. if (prefix) {
  581. prefix = normalize(prefix, parentName, applyMap);
  582. pluginModule = getOwn(defined, prefix);
  583. }
  584. //Account for relative paths if there is a base name.
  585. if (name) {
  586. if (prefix) {
  587. if (pluginModule && pluginModule.normalize) {
  588. //Plugin is loaded, use its normalize method.
  589. normalizedName = pluginModule.normalize(name, function (name) {
  590. return normalize(name, parentName, applyMap);
  591. });
  592. } else {
  593. normalizedName = normalize(name, parentName, applyMap);
  594. }
  595. } else {
  596. //A regular module.
  597. normalizedName = normalize(name, parentName, applyMap);
  598. //Normalized name may be a plugin ID due to map config
  599. //application in normalize. The map config values must
  600. //already be normalized, so do not need to redo that part.
  601. nameParts = splitPrefix(normalizedName);
  602. prefix = nameParts[0];
  603. normalizedName = nameParts[1];
  604. isNormalized = true;
  605. url = context.nameToUrl(normalizedName);
  606. }
  607. }
  608. //If the id is a plugin id that cannot be determined if it needs
  609. //normalization, stamp it with a unique ID so two matching relative
  610. //ids that may conflict can be separate.
  611. suffix = prefix && !pluginModule && !isNormalized ?
  612. '_unnormalized' + (unnormalizedCounter += 1) :
  613. '';
  614. return {
  615. prefix: prefix,
  616. name: normalizedName,
  617. parentMap: parentModuleMap,
  618. unnormalized: !!suffix,
  619. url: url,
  620. originalName: originalName,
  621. isDefine: isDefine,
  622. id: (prefix ?
  623. prefix + '!' + normalizedName :
  624. normalizedName) + suffix
  625. };
  626. }
  627. function getModule(depMap) {
  628. var id = depMap.id,
  629. mod = getOwn(registry, id);
  630. if (!mod) {
  631. mod = registry[id] = new context.Module(depMap);
  632. }
  633. return mod;
  634. }
  635. function on(depMap, name, fn) {
  636. var id = depMap.id,
  637. mod = getOwn(registry, id);
  638. if (hasProp(defined, id) &&
  639. (!mod || mod.defineEmitComplete)) {
  640. if (name === 'defined') {
  641. fn(defined[id]);
  642. }
  643. } else {
  644. getModule(depMap).on(name, fn);
  645. }
  646. }
  647. function onError(err, errback) {
  648. var ids = err.requireModules,
  649. notified = false;
  650. if (errback) {
  651. errback(err);
  652. } else {
  653. each(ids, function (id) {
  654. var mod = getOwn(registry, id);
  655. if (mod) {
  656. //Set error on module, so it skips timeout checks.
  657. mod.error = err;
  658. if (mod.events.error) {
  659. notified = true;
  660. mod.emit('error', err);
  661. }
  662. }
  663. });
  664. if (!notified) {
  665. req.onError(err);
  666. }
  667. }
  668. }
  669. /**
  670. * Internal method to transfer globalQueue items to this context's
  671. * defQueue.
  672. */
  673. function takeGlobalQueue() {
  674. //Push all the globalDefQueue items into the context's defQueue
  675. if (globalDefQueue.length) {
  676. //Array splice in the values since the context code has a
  677. //local var ref to defQueue, so cannot just reassign the one
  678. //on context.
  679. apsp.apply(defQueue,
  680. [defQueue.length - 1, 0].concat(globalDefQueue));
  681. globalDefQueue = [];
  682. }
  683. }
  684. handlers = {
  685. 'require': function (mod) {
  686. if (mod.require) {
  687. return mod.require;
  688. } else {
  689. return (mod.require = context.makeRequire(mod.map));
  690. }
  691. },
  692. 'exports': function (mod) {
  693. mod.usingExports = true;
  694. if (mod.map.isDefine) {
  695. if (mod.exports) {
  696. return mod.exports;
  697. } else {
  698. return (mod.exports = defined[mod.map.id] = {});
  699. }
  700. }
  701. },
  702. 'module': function (mod) {
  703. if (mod.module) {
  704. return mod.module;
  705. } else {
  706. return (mod.module = {
  707. id: mod.map.id,
  708. uri: mod.map.url,
  709. config: function () {
  710. return (config.config && getOwn(config.config, mod.map.id)) || {};
  711. },
  712. exports: defined[mod.map.id]
  713. });
  714. }
  715. }
  716. };
  717. function cleanRegistry(id) {
  718. //Clean up machinery used for waiting modules.
  719. delete registry[id];
  720. delete enabledRegistry[id];
  721. }
  722. function breakCycle(mod, traced, processed) {
  723. var id = mod.map.id;
  724. if (mod.error) {
  725. mod.emit('error', mod.error);
  726. } else {
  727. traced[id] = true;
  728. each(mod.depMaps, function (depMap, i) {
  729. var depId = depMap.id,
  730. dep = getOwn(registry, depId);
  731. //Only force things that have not completed
  732. //being defined, so still in the registry,
  733. //and only if it has not been matched up
  734. //in the module already.
  735. if (dep && !mod.depMatched[i] && !processed[depId]) {
  736. if (getOwn(traced, depId)) {
  737. mod.defineDep(i, defined[depId]);
  738. mod.check(); //pass false?
  739. } else {
  740. breakCycle(dep, traced, processed);
  741. }
  742. }
  743. });
  744. processed[id] = true;
  745. }
  746. }
  747. function checkLoaded() {
  748. var map, modId, err, usingPathFallback,
  749. waitInterval = config.waitSeconds * 1000,
  750. //It is possible to disable the wait interval by using waitSeconds of 0.
  751. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
  752. noLoads = [],
  753. reqCalls = [],
  754. stillLoading = false,
  755. needCycleCheck = true;
  756. //Do not bother if this call was a result of a cycle break.
  757. if (inCheckLoaded) {
  758. return;
  759. }
  760. inCheckLoaded = true;
  761. //Figure out the state of all the modules.
  762. eachProp(enabledRegistry, function (mod) {
  763. map = mod.map;
  764. modId = map.id;
  765. //Skip things that are not enabled or in error state.
  766. if (!mod.enabled) {
  767. return;
  768. }
  769. if (!map.isDefine) {
  770. reqCalls.push(mod);
  771. }
  772. if (!mod.error) {
  773. //If the module should be executed, and it has not
  774. //been inited and time is up, remember it.
  775. if (!mod.inited && expired) {
  776. if (hasPathFallback(modId)) {
  777. usingPathFallback = true;
  778. stillLoading = true;
  779. } else {
  780. noLoads.push(modId);
  781. removeScript(modId);
  782. }
  783. } else if (!mod.inited && mod.fetched && map.isDefine) {
  784. stillLoading = true;
  785. if (!map.prefix) {
  786. //No reason to keep looking for unfinished
  787. //loading. If the only stillLoading is a
  788. //plugin resource though, keep going,
  789. //because it may be that a plugin resource
  790. //is waiting on a non-plugin cycle.
  791. return (needCycleCheck = false);
  792. }
  793. }
  794. }
  795. });
  796. if (expired && noLoads.length) {
  797. //If wait time expired, throw error of unloaded modules.
  798. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
  799. err.contextName = context.contextName;
  800. return onError(err);
  801. }
  802. //Not expired, check for a cycle.
  803. if (needCycleCheck) {
  804. each(reqCalls, function (mod) {
  805. breakCycle(mod, {}, {});
  806. });
  807. }
  808. //If still waiting on loads, and the waiting load is something
  809. //other than a plugin resource, or there are still outstanding
  810. //scripts, then just try back later.
  811. if ((!expired || usingPathFallback) && stillLoading) {
  812. //Something is still waiting to load. Wait for it, but only
  813. //if a timeout is not already in effect.
  814. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
  815. checkLoadedTimeoutId = setTimeout(function () {
  816. checkLoadedTimeoutId = 0;
  817. checkLoaded();
  818. }, 50);
  819. }
  820. }
  821. inCheckLoaded = false;
  822. }
  823. Module = function (map) {
  824. this.events = getOwn(undefEvents, map.id) || {};
  825. this.map = map;
  826. this.shim = getOwn(config.shim, map.id);
  827. this.depExports = [];
  828. this.depMaps = [];
  829. this.depMatched = [];
  830. this.pluginMaps = {};
  831. this.depCount = 0;
  832. /* this.exports this.factory
  833. this.depMaps = [],
  834. this.enabled, this.fetched
  835. */
  836. };
  837. Module.prototype = {
  838. init: function (depMaps, factory, errback, options) {
  839. options = options || {};
  840. //Do not do more inits if already done. Can happen if there
  841. //are multiple define calls for the same module. That is not
  842. //a normal, common case, but it is also not unexpected.
  843. if (this.inited) {
  844. return;
  845. }
  846. this.factory = factory;
  847. if (errback) {
  848. //Register for errors on this module.
  849. this.on('error', errback);
  850. } else if (this.events.error) {
  851. //If no errback already, but there are error listeners
  852. //on this module, set up an errback to pass to the deps.
  853. errback = bind(this, function (err) {
  854. this.emit('error', err);
  855. });
  856. }
  857. //Do a copy of the dependency array, so that
  858. //source inputs are not modified. For example
  859. //"shim" deps are passed in here directly, and
  860. //doing a direct modification of the depMaps array
  861. //would affect that config.
  862. this.depMaps = depMaps && depMaps.slice(0);
  863. this.errback = errback;
  864. //Indicate this module has be initialized
  865. this.inited = true;
  866. this.ignore = options.ignore;
  867. //Could have option to init this module in enabled mode,
  868. //or could have been previously marked as enabled. However,
  869. //the dependencies are not known until init is called. So
  870. //if enabled previously, now trigger dependencies as enabled.
  871. if (options.enabled || this.enabled) {
  872. //Enable this module and dependencies.
  873. //Will call this.check()
  874. this.enable();
  875. } else {
  876. this.check();
  877. }
  878. },
  879. defineDep: function (i, depExports) {
  880. //Because of cycles, defined callback for a given
  881. //export can be called more than once.
  882. if (!this.depMatched[i]) {
  883. this.depMatched[i] = true;
  884. this.depCount -= 1;
  885. this.depExports[i] = depExports;
  886. }
  887. },
  888. fetch: function () {
  889. if (this.fetched) {
  890. return;
  891. }
  892. this.fetched = true;
  893. context.startTime = (new Date()).getTime();
  894. var map = this.map;
  895. //If the manager is for a plugin managed resource,
  896. //ask the plugin to load it now.
  897. if (this.shim) {
  898. context.makeRequire(this.map, {
  899. enableBuildCallback: true
  900. })(this.shim.deps || [], bind(this, function () {
  901. return map.prefix ? this.callPlugin() : this.load();
  902. }));
  903. } else {
  904. //Regular dependency.
  905. return map.prefix ? this.callPlugin() : this.load();
  906. }
  907. },
  908. load: function () {
  909. var url = this.map.url;
  910. //Regular dependency.
  911. if (!urlFetched[url]) {
  912. urlFetched[url] = true;
  913. context.load(this.map.id, url);
  914. }
  915. },
  916. /**
  917. * Checks if the module is ready to define itself, and if so,
  918. * define it.
  919. */
  920. check: function () {
  921. if (!this.enabled || this.enabling) {
  922. return;
  923. }
  924. var err, cjsModule,
  925. id = this.map.id,
  926. depExports = this.depExports,
  927. exports = this.exports,
  928. factory = this.factory;
  929. if (!this.inited) {
  930. this.fetch();
  931. } else if (this.error) {
  932. this.emit('error', this.error);
  933. } else if (!this.defining) {
  934. //The factory could trigger another require call
  935. //that would result in checking this module to
  936. //define itself again. If already in the process
  937. //of doing that, skip this work.
  938. this.defining = true;
  939. if (this.depCount < 1 && !this.defined) {
  940. if (isFunction(factory)) {
  941. //If there is an error listener, favor passing
  942. //to that instead of throwing an error.
  943. if (this.events.error) {
  944. try {
  945. exports = context.execCb(id, factory, depExports, exports);
  946. } catch (e) {
  947. err = e;
  948. }
  949. } else {
  950. exports = context.execCb(id, factory, depExports, exports);
  951. }
  952. if (this.map.isDefine) {
  953. //If setting exports via 'module' is in play,
  954. //favor that over return value and exports. After that,
  955. //favor a non-undefined return value over exports use.
  956. cjsModule = this.module;
  957. if (cjsModule &&
  958. cjsModule.exports !== undefined &&
  959. //Make sure it is not already the exports value
  960. cjsModule.exports !== this.exports) {
  961. exports = cjsModule.exports;
  962. } else if (exports === undefined && this.usingExports) {
  963. //exports already set the defined value.
  964. exports = this.exports;
  965. }
  966. }
  967. if (err) {
  968. err.requireMap = this.map;
  969. err.requireModules = [this.map.id];
  970. err.requireType = 'define';
  971. return onError((this.error = err));
  972. }
  973. } else {
  974. //Just a literal value
  975. exports = factory;
  976. }
  977. this.exports = exports;
  978. if (this.map.isDefine && !this.ignore) {
  979. defined[id] = exports;
  980. if (req.onResourceLoad) {
  981. req.onResourceLoad(context, this.map, this.depMaps);
  982. }
  983. }
  984. //Clean up
  985. cleanRegistry(id);
  986. this.defined = true;
  987. }
  988. //Finished the define stage. Allow calling check again
  989. //to allow define notifications below in the case of a
  990. //cycle.
  991. this.defining = false;
  992. if (this.defined && !this.defineEmitted) {
  993. this.defineEmitted = true;
  994. this.emit('defined', this.exports);
  995. this.defineEmitComplete = true;
  996. }
  997. }
  998. },
  999. callPlugin: function () {
  1000. var map = this.map,
  1001. id = map.id,
  1002. //Map already normalized the prefix.
  1003. pluginMap = makeModuleMap(map.prefix);
  1004. //Mark this as a dependency for this plugin, so it
  1005. //can be traced for cycles.
  1006. this.depMaps.push(pluginMap);
  1007. on(pluginMap, 'defined', bind(this, function (plugin) {
  1008. var load, normalizedMap, normalizedMod,
  1009. name = this.map.name,
  1010. parentName = this.map.parentMap ? this.map.parentMap.name : null,
  1011. localRequire = context.makeRequire(map.parentMap, {
  1012. enableBuildCallback: true
  1013. });
  1014. //If current map is not normalized, wait for that
  1015. //normalized name to load instead of continuing.
  1016. if (this.map.unnormalized) {
  1017. //Normalize the ID if the plugin allows it.
  1018. if (plugin.normalize) {
  1019. name = plugin.normalize(name, function (name) {
  1020. return normalize(name, parentName, true);
  1021. }) || '';
  1022. }
  1023. //prefix and name should already be normalized, no need
  1024. //for applying map config again either.
  1025. normalizedMap = makeModuleMap(map.prefix + '!' + name,
  1026. this.map.parentMap);
  1027. on(normalizedMap,
  1028. 'defined', bind(this, function (value) {
  1029. this.init([], function () { return value; }, null, {
  1030. enabled: true,
  1031. ignore: true
  1032. });
  1033. }));
  1034. normalizedMod = getOwn(registry, normalizedMap.id);
  1035. if (normalizedMod) {
  1036. //Mark this as a dependency for this plugin, so it
  1037. //can be traced for cycles.
  1038. this.depMaps.push(normalizedMap);
  1039. if (this.events.error) {
  1040. normalizedMod.on('error', bind(this, function (err) {
  1041. this.emit('error', err);
  1042. }));
  1043. }
  1044. normalizedMod.enable();
  1045. }
  1046. return;
  1047. }
  1048. load = bind(this, function (value) {
  1049. this.init([], function () { return value; }, null, {
  1050. enabled: true
  1051. });
  1052. });
  1053. load.error = bind(this, function (err) {
  1054. this.inited = true;
  1055. this.error = err;
  1056. err.requireModules = [id];
  1057. //Remove temp unnormalized modules for this module,
  1058. //since they will never be resolved otherwise now.
  1059. eachProp(registry, function (mod) {
  1060. if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
  1061. cleanRegistry(mod.map.id);
  1062. }
  1063. });
  1064. onError(err);
  1065. });
  1066. //Allow plugins to load other code without having to know the
  1067. //context or how to 'complete' the load.
  1068. load.fromText = bind(this, function (text, textAlt) {
  1069. /*jslint evil: true */
  1070. var moduleName = map.name,
  1071. moduleMap = makeModuleMap(moduleName),
  1072. hasInteractive = useInteractive;
  1073. //As of 2.1.0, support just passing the text, to reinforce
  1074. //fromText only being called once per resource. Still
  1075. //support old style of passing moduleName but discard
  1076. //that moduleName in favor of the internal ref.
  1077. if (textAlt) {
  1078. text = textAlt;
  1079. }
  1080. //Turn off interactive script matching for IE for any define
  1081. //calls in the text, then turn it back on at the end.
  1082. if (hasInteractive) {
  1083. useInteractive = false;
  1084. }
  1085. //Prime the system by creating a module instance for
  1086. //it.
  1087. getModule(moduleMap);
  1088. //Transfer any config to this other module.
  1089. if (hasProp(config.config, id)) {
  1090. config.config[moduleName] = config.config[id];
  1091. }
  1092. try {
  1093. req.exec(text);
  1094. } catch (e) {
  1095. return onError(makeError('fromtexteval',
  1096. 'fromText eval for ' + id +
  1097. ' failed: ' + e,
  1098. e,
  1099. [id]));
  1100. }
  1101. if (hasInteractive) {
  1102. useInteractive = true;
  1103. }
  1104. //Mark this as a dependency for the plugin
  1105. //resource
  1106. this.depMaps.push(moduleMap);
  1107. //Support anonymous modules.
  1108. context.completeLoad(moduleName);
  1109. //Bind the value of that module to the value for this
  1110. //resource ID.
  1111. localRequire([moduleName], load);
  1112. });
  1113. //Use parentName here since the plugin's name is not reliable,
  1114. //could be some weird string with no path that actually wants to
  1115. //reference the parentName's path.
  1116. plugin.load(map.name, localRequire, load, config);
  1117. }));
  1118. context.enable(pluginMap, this);
  1119. this.pluginMaps[pluginMap.id] = pluginMap;
  1120. },
  1121. enable: function () {
  1122. enabledRegistry[this.map.id] = this;
  1123. this.enabled = true;
  1124. //Set flag mentioning that the module is enabling,
  1125. //so that immediate calls to the defined callbacks
  1126. //for dependencies do not trigger inadvertent load
  1127. //with the depCount still being zero.
  1128. this.enabling = true;
  1129. //Enable each dependency
  1130. each(this.depMaps, bind(this, function (depMap, i) {
  1131. var id, mod, handler;
  1132. if (typeof depMap === 'string') {
  1133. //Dependency needs to be converted to a depMap
  1134. //and wired up to this module.
  1135. depMap = makeModuleMap(depMap,
  1136. (this.map.isDefine ? this.map : this.map.parentMap),
  1137. false,
  1138. !this.skipMap);
  1139. this.depMaps[i] = depMap;
  1140. handler = getOwn(handlers, depMap.id);
  1141. if (handler) {
  1142. this.depExports[i] = handler(this);
  1143. return;
  1144. }
  1145. this.depCount += 1;
  1146. on(depMap, 'defined', bind(this, function (depExports) {
  1147. this.defineDep(i, depExports);
  1148. this.check();
  1149. }));
  1150. if (this.errback) {
  1151. on(depMap, 'error', this.errback);
  1152. }
  1153. }
  1154. id = depMap.id;
  1155. mod = registry[id];
  1156. //Skip special modules like 'require', 'exports', 'module'
  1157. //Also, don't call enable if it is already enabled,
  1158. //important in circular dependency cases.
  1159. if (!hasProp(handlers, id) && mod && !mod.enabled) {
  1160. context.enable(depMap, this);
  1161. }
  1162. }));
  1163. //Enable each plugin that is used in
  1164. //a dependency
  1165. eachProp(this.pluginMaps, bind(this, function (pluginMap) {
  1166. var mod = getOwn(registry, pluginMap.id);
  1167. if (mod && !mod.enabled) {
  1168. context.enable(pluginMap, this);
  1169. }
  1170. }));
  1171. this.enabling = false;
  1172. this.check();
  1173. },
  1174. on: function (name, cb) {
  1175. var cbs = this.events[name];
  1176. if (!cbs) {
  1177. cbs = this.events[name] = [];
  1178. }
  1179. cbs.push(cb);
  1180. },
  1181. emit: function (name, evt) {
  1182. each(this.events[name], function (cb) {
  1183. cb(evt);
  1184. });
  1185. if (name === 'error') {
  1186. //Now that the error handler was triggered, remove
  1187. //the listeners, since this broken Module instance
  1188. //can stay around for a while in the registry.
  1189. delete this.events[name];
  1190. }
  1191. }
  1192. };
  1193. function callGetModule(args) {
  1194. //Skip modules already defined.
  1195. if (!hasProp(defined, args[0])) {
  1196. getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
  1197. }
  1198. }
  1199. function removeListener(node, func, name, ieName) {
  1200. //Favor detachEvent because of IE9
  1201. //issue, see attachEvent/addEventListener comment elsewhere
  1202. //in this file.
  1203. if (node.detachEvent && !isOpera) {
  1204. //Probably IE. If not it will throw an error, which will be
  1205. //useful to know.
  1206. if (ieName) {
  1207. node.detachEvent(ieName, func);
  1208. }
  1209. } else {
  1210. node.removeEventListener(name, func, false);
  1211. }
  1212. }
  1213. /**
  1214. * Given an event from a script node, get the requirejs info from it,
  1215. * and then removes the event listeners on the node.
  1216. * @param {Event} evt
  1217. * @returns {Object}
  1218. */
  1219. function getScriptData(evt) {
  1220. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1221. //all old browsers will be supported, but this one was easy enough
  1222. //to support and still makes sense.
  1223. var node = evt.currentTarget || evt.srcElement;
  1224. //Remove the listeners once here.
  1225. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
  1226. removeListener(node, context.onScriptError, 'error');
  1227. return {
  1228. node: node,
  1229. id: node && node.getAttribute('data-requiremodule')
  1230. };
  1231. }
  1232. function intakeDefines() {
  1233. var args;
  1234. //Any defined modules in the global queue, intake them now.
  1235. takeGlobalQueue();
  1236. //Make sure any remaining defQueue items get properly processed.
  1237. while (defQueue.length) {
  1238. args = defQueue.shift();
  1239. if (args[0] === null) {
  1240. return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
  1241. } else {
  1242. //args are id, deps, factory. Should be normalized by the
  1243. //define() function.
  1244. callGetModule(args);
  1245. }
  1246. }
  1247. }
  1248. context = {
  1249. config: config,
  1250. contextName: contextName,
  1251. registry: registry,
  1252. defined: defined,
  1253. urlFetched: urlFetched,
  1254. defQueue: defQueue,
  1255. Module: Module,
  1256. makeModuleMap: makeModuleMap,
  1257. nextTick: req.nextTick,
  1258. onError: onError,
  1259. /**
  1260. * Set a configuration for the context.
  1261. * @param {Object} cfg config object to integrate.
  1262. */
  1263. configure: function (cfg) {
  1264. //Make sure the baseUrl ends in a slash.
  1265. if (cfg.baseUrl) {
  1266. if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
  1267. cfg.baseUrl += '/';
  1268. }
  1269. }
  1270. //Save off the paths and packages since they require special processing,
  1271. //they are additive.
  1272. var pkgs = config.pkgs,
  1273. shim = config.shim,
  1274. objs = {
  1275. paths: true,
  1276. config: true,
  1277. map: true
  1278. };
  1279. eachProp(cfg, function (value, prop) {
  1280. if (objs[prop]) {
  1281. if (prop === 'map') {
  1282. if (!config.map) {
  1283. config.map = {};
  1284. }
  1285. mixin(config[prop], value, true, true);
  1286. } else {
  1287. mixin(config[prop], value, true);
  1288. }
  1289. } else {
  1290. config[prop] = value;
  1291. }
  1292. });
  1293. //Merge shim
  1294. if (cfg.shim) {
  1295. eachProp(cfg.shim, function (value, id) {
  1296. //Normalize the structure
  1297. if (isArray(value)) {
  1298. value = {
  1299. deps: value
  1300. };
  1301. }
  1302. if ((value.exports || value.init) && !value.exportsFn) {
  1303. value.exportsFn = context.makeShimExports(value);
  1304. }
  1305. shim[id] = value;
  1306. });
  1307. config.shim = shim;
  1308. }
  1309. //Adjust packages if necessary.
  1310. if (cfg.packages) {
  1311. each(cfg.packages, function (pkgObj) {
  1312. var location;
  1313. pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
  1314. location = pkgObj.location;
  1315. //Create a brand new object on pkgs, since currentPackages can
  1316. //be passed in again, and config.pkgs is the internal transformed
  1317. //state for all package configs.
  1318. pkgs[pkgObj.name] = {
  1319. name: pkgObj.name,
  1320. location: location || pkgObj.name,
  1321. //Remove leading dot in main, so main paths are normalized,
  1322. //and remove any trailing .js, since different package
  1323. //envs have different conventions: some use a module name,
  1324. //some use a file name.
  1325. main: (pkgObj.main || 'main')
  1326. .replace(currDirRegExp, '')
  1327. .replace(jsSuffixRegExp, '')
  1328. };
  1329. });
  1330. //Done with modifications, assing packages back to context config
  1331. config.pkgs = pkgs;
  1332. }
  1333. //If there are any "waiting to execute" modules in the registry,
  1334. //update the maps for them, since their info, like URLs to load,
  1335. //may have changed.
  1336. eachProp(registry, function (mod, id) {
  1337. //If module already has init called, since it is too
  1338. //late to modify them, and ignore unnormalized ones
  1339. //since they are transient.
  1340. if (!mod.inited && !mod.map.unnormalized) {
  1341. mod.map = makeModuleMap(id);
  1342. }
  1343. });
  1344. //If a deps array or a config callback is specified, then call
  1345. //require with those args. This is useful when require is defined as a
  1346. //config object before require.js is loaded.
  1347. if (cfg.deps || cfg.callback) {
  1348. context.require(cfg.deps || [], cfg.callback);
  1349. }
  1350. },
  1351. makeShimExports: function (value) {
  1352. function fn() {
  1353. var ret;
  1354. if (value.init) {
  1355. ret = value.init.apply(global, arguments);
  1356. }
  1357. return ret || (value.exports && getGlobal(value.exports));
  1358. }
  1359. return fn;
  1360. },
  1361. makeRequire: function (relMap, options) {
  1362. options = options || {};
  1363. function localRequire(deps, callback, errback) {
  1364. var id, map, requireMod;
  1365. if (options.enableBuildCallback && callback && isFunction(callback)) {
  1366. callback.__requireJsBuild = true;
  1367. }
  1368. if (typeof deps === 'string') {
  1369. if (isFunction(callback)) {
  1370. //Invalid call
  1371. return onError(makeError('requireargs', 'Invalid require call'), errback);
  1372. }
  1373. //If require|exports|module are requested, get the
  1374. //value for them from the special handlers. Caveat:
  1375. //this only works while module is being defined.
  1376. if (relMap && hasProp(handlers, deps)) {
  1377. return handlers[deps](registry[relMap.id]);
  1378. }
  1379. //Synchronous access to one module. If require.get is
  1380. //available (as in the Node adapter), prefer that.
  1381. if (req.get) {
  1382. return req.get(context, deps, relMap, localRequire);
  1383. }
  1384. //Normalize module name, if it contains . or ..
  1385. map = makeModuleMap(deps, relMap, false, true);
  1386. id = map.id;
  1387. if (!hasProp(defined, id)) {
  1388. return onError(makeError('notloaded', 'Module name "' +
  1389. id +
  1390. '" has not been loaded yet for context: ' +
  1391. contextName +
  1392. (relMap ? '' : '. Use require([])')));
  1393. }
  1394. return defined[id];
  1395. }
  1396. //Grab defines waiting in the global queue.
  1397. intakeDefines();
  1398. //Mark all the dependencies as needing to be loaded.
  1399. context.nextTick(function () {
  1400. //Some defines could have been added since the
  1401. //require call, collect them.
  1402. intakeDefines();
  1403. requireMod = getModule(makeModuleMap(null, relMap));
  1404. //Store if map config should be applied to this require
  1405. //call for dependencies.
  1406. requireMod.skipMap = options.skipMap;
  1407. requireMod.init(deps, callback, errback, {
  1408. enabled: true
  1409. });
  1410. checkLoaded();
  1411. });
  1412. return localRequire;
  1413. }
  1414. mixin(localRequire, {
  1415. isBrowser: isBrowser,
  1416. /**
  1417. * Converts a module name + .extension into an URL path.
  1418. * *Requires* the use of a module name. It does not support using
  1419. * plain URLs like nameToUrl.
  1420. */
  1421. toUrl: function (moduleNamePlusExt) {
  1422. var ext,
  1423. index = moduleNamePlusExt.lastIndexOf('.'),
  1424. segment = moduleNamePlusExt.split('/')[0],
  1425. isRelative = segment === '.' || segment === '..';
  1426. //Have a file extension alias, and it is not the
  1427. //dots from a relative path.
  1428. if (index !== -1 && (!isRelative || index > 1)) {
  1429. ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
  1430. moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
  1431. }
  1432. return context.nameToUrl(normalize(moduleNamePlusExt,
  1433. relMap && relMap.id, true), ext, true);
  1434. },
  1435. defined: function (id) {
  1436. return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
  1437. },
  1438. specified: function (id) {
  1439. id = makeModuleMap(id, relMap, false, true).id;
  1440. return hasProp(defined, id) || hasProp(registry, id);
  1441. }
  1442. });
  1443. //Only allow undef on top level require calls
  1444. if (!relMap) {
  1445. localRequire.undef = function (id) {
  1446. //Bind any waiting define() calls to this context,
  1447. //fix for #408
  1448. takeGlobalQueue();
  1449. var map = makeModuleMap(id, relMap, true),
  1450. mod = getOwn(registry, id);
  1451. delete defined[id];
  1452. delete urlFetched[map.url];
  1453. delete undefEvents[id];
  1454. if (mod) {
  1455. //Hold on to listeners in case the
  1456. //module will be attempted to be reloaded
  1457. //using a different config.
  1458. if (mod.events.defined) {
  1459. undefEvents[id] = mod.events;
  1460. }
  1461. cleanRegistry(id);
  1462. }
  1463. };
  1464. }
  1465. return localRequire;
  1466. },
  1467. /**
  1468. * Called to enable a module if it is still in the registry
  1469. * awaiting enablement. A second arg, parent, the parent module,
  1470. * is passed in for context, when this method is overriden by
  1471. * the optimizer. Not shown here to keep code compact.
  1472. */
  1473. enable: function (depMap) {
  1474. var mod = getOwn(registry, depMap.id);
  1475. if (mod) {
  1476. getModule(depMap).enable();
  1477. }
  1478. },
  1479. /**
  1480. * Internal method used by environment adapters to complete a load event.
  1481. * A load event could be a script load or just a load pass from a synchronous
  1482. * load call.
  1483. * @param {String} moduleName the name of the module to potentially complete.
  1484. */
  1485. completeLoad: function (moduleName) {
  1486. var found, args, mod,
  1487. shim = getOwn(config.shim, moduleName) || {},
  1488. shExports = shim.exports;
  1489. takeGlobalQueue();
  1490. while (defQueue.length) {
  1491. args = defQueue.shift();
  1492. if (args[0] === null) {
  1493. args[0] = moduleName;
  1494. //If already found an anonymous module and bound it
  1495. //to this name, then this is some other anon module
  1496. //waiting for its completeLoad to fire.
  1497. if (found) {
  1498. break;
  1499. }
  1500. found = true;
  1501. } else if (args[0] === moduleName) {
  1502. //Found matching define call for this script!
  1503. found = true;
  1504. }
  1505. callGetModule(args);
  1506. }
  1507. //Do this after the cycle of callGetModule in case the result
  1508. //of those calls/init calls changes the registry.
  1509. mod = getOwn(registry, moduleName);
  1510. if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
  1511. if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
  1512. if (hasPathFallback(moduleName)) {
  1513. return;
  1514. } else {
  1515. return onError(makeError('nodefine',
  1516. 'No define call for ' + moduleName,
  1517. null,
  1518. [moduleName]));
  1519. }
  1520. } else {
  1521. //A script that does not call define(), so just simulate
  1522. //the call for it.
  1523. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
  1524. }
  1525. }
  1526. checkLoaded();
  1527. },
  1528. /**
  1529. * Converts a module name to a file path. Supports cases where
  1530. * moduleName may actually be just an URL.
  1531. * Note that it **does not** call normalize on the moduleName,
  1532. * it is assumed to have already been normalized. This is an
  1533. * internal API, not a public one. Use toUrl for the public API.
  1534. */
  1535. nameToUrl: function (moduleName, ext, skipExt) {
  1536. var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
  1537. parentPath;
  1538. //If a colon is in the URL, it indicates a protocol is used and it is just
  1539. //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
  1540. //or ends with .js, then assume the user meant to use an url and not a module id.
  1541. //The slash is important for protocol-less URLs as well as full paths.
  1542. if (req.jsExtRegExp.test(moduleName)) {
  1543. //Just a plain path, not module name lookup, so just return it.
  1544. //Add extension if it is included. This is a bit wonky, only non-.js things pass
  1545. //an extension, this method probably needs to be reworked.
  1546. url = moduleName + (ext || '');
  1547. } else {
  1548. //A module that needs to be converted to a path.
  1549. paths = config.paths;
  1550. pkgs = config.pkgs;
  1551. syms = moduleName.split('/');
  1552. //For each module name segment, see if there is a path
  1553. //registered for it. Start with most specific name
  1554. //and work up from it.
  1555. for (i = syms.length; i > 0; i -= 1) {
  1556. parentModule = syms.slice(0, i).join('/');
  1557. pkg = getOwn(pkgs, parentModule);
  1558. parentPath = getOwn(paths, parentModule);
  1559. if (parentPath) {
  1560. //If an array, it means there are a few choices,
  1561. //Choose the one that is desired
  1562. if (isArray(parentPath)) {
  1563. parentPath = parentPath[0];
  1564. }
  1565. syms.splice(0, i, parentPath);
  1566. break;
  1567. } else if (pkg) {
  1568. //If module name is just the package name, then looking
  1569. //for the main module.
  1570. if (moduleName === pkg.name) {
  1571. pkgPath = pkg.location + '/' + pkg.main;
  1572. } else {
  1573. pkgPath = pkg.location;
  1574. }
  1575. syms.splice(0, i, pkgPath);
  1576. break;
  1577. }
  1578. }
  1579. //Join the path parts together, then figure out if baseUrl is needed.
  1580. url = syms.join('/');
  1581. url += (ext || (/\?/.test(url) || skipExt ? '' : '.js'));
  1582. url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
  1583. }
  1584. return config.urlArgs ? url +
  1585. ((url.indexOf('?') === -1 ? '?' : '&') +
  1586. config.urlArgs) : url;
  1587. },
  1588. //Delegates to req.load. Broken out as a separate function to
  1589. //allow overriding in the optimizer.
  1590. load: function (id, url) {
  1591. req.load(context, id, url);
  1592. },
  1593. /**
  1594. * Executes a module callack function. Broken out as a separate function
  1595. * solely to allow the build system to sequence the files in the built
  1596. * layer in the right sequence.
  1597. *
  1598. * @private
  1599. */
  1600. execCb: function (name, callback, args, exports) {
  1601. return callback.apply(exports, args);
  1602. },
  1603. /**
  1604. * callback for script loads, used to check status of loading.
  1605. *
  1606. * @param {Event} evt the event from the browser for the script
  1607. * that was loaded.
  1608. */
  1609. onScriptLoad: function (evt) {
  1610. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1611. //all old browsers will be supported, but this one was easy enough
  1612. //to support and still makes sense.
  1613. if (evt.type === 'load' ||
  1614. (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
  1615. //Reset interactive script so a script node is not held onto for
  1616. //to long.
  1617. interactiveScript = null;
  1618. //Pull out the name of the module and the context.
  1619. var data = getScriptData(evt);
  1620. context.completeLoad(data.id);
  1621. }
  1622. },
  1623. /**
  1624. * Callback for script errors.
  1625. */
  1626. onScriptError: function (evt) {
  1627. var data = getScriptData(evt);
  1628. if (!hasPathFallback(data.id)) {
  1629. return onError(makeError('scripterror', 'Script error', evt, [data.id]));
  1630. }
  1631. }
  1632. };
  1633. context.require = context.makeRequire();
  1634. return context;
  1635. }
  1636. /**
  1637. * Main entry point.
  1638. *
  1639. * If the only argument to require is a string, then the module that
  1640. * is represented by that string is fetched for the appropriate context.
  1641. *
  1642. * If the first argument is an array, then it will be treated as an array
  1643. * of dependency string names to fetch. An optional function callback can
  1644. * be specified to execute when all of those dependencies are available.
  1645. *
  1646. * Make a local req variable to help Caja compliance (it assumes things
  1647. * on a require that are not standardized), and to give a short
  1648. * name for minification/local scope use.
  1649. */
  1650. req = requirejs = function (deps, callback, errback, optional) {
  1651. //Find the right context, use default
  1652. var context, config,
  1653. contextName = defContextName;
  1654. // Determine if have config object in the call.
  1655. if (!isArray(deps) && typeof deps !== 'string') {
  1656. // deps is a config object
  1657. config = deps;
  1658. if (isArray(callback)) {
  1659. // Adjust args if there are dependencies
  1660. deps = callback;
  1661. callback = errback;
  1662. errback = optional;
  1663. } else {
  1664. deps = [];
  1665. }
  1666. }
  1667. if (config && config.context) {
  1668. contextName = config.context;
  1669. }
  1670. context = getOwn(contexts, contextName);
  1671. if (!context) {
  1672. context = contexts[contextName] = req.s.newContext(contextName);
  1673. }
  1674. if (config) {
  1675. context.configure(config);
  1676. }
  1677. return context.require(deps, callback, errback);
  1678. };
  1679. /**
  1680. * Support require.config() to make it easier to cooperate with other
  1681. * AMD loaders on globally agreed names.
  1682. */
  1683. req.config = function (config) {
  1684. return req(config);
  1685. };
  1686. /**
  1687. * Execute something after the current tick
  1688. * of the event loop. Override for other envs
  1689. * that have a better solution than setTimeout.
  1690. * @param {Function} fn function to execute later.
  1691. */
  1692. req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
  1693. setTimeout(fn, 4);
  1694. } : function (fn) { fn(); };
  1695. /**
  1696. * Export require as a global, but only if it does not already exist.
  1697. */
  1698. if (!require) {
  1699. require = req;
  1700. }
  1701. req.version = version;
  1702. //Used to filter out dependencies that are already paths.
  1703. req.jsExtRegExp = /^\/|:|\?|\.js$/;
  1704. req.isBrowser = isBrowser;
  1705. s = req.s = {
  1706. contexts: contexts,
  1707. newContext: newContext
  1708. };
  1709. //Create default context.
  1710. req({});
  1711. //Exports some context-sensitive methods on global require.
  1712. each([
  1713. 'toUrl',
  1714. 'undef',
  1715. 'defined',
  1716. 'specified'
  1717. ], function (prop) {
  1718. //Reference from contexts instead of early binding to default context,
  1719. //so that during builds, the latest instance of the default context
  1720. //with its config gets used.
  1721. req[prop] = function () {
  1722. var ctx = contexts[defContextName];
  1723. return ctx.require[prop].apply(ctx, arguments);
  1724. };
  1725. });
  1726. if (isBrowser) {
  1727. head = s.head = document.getElementsByTagName('head')[0];
  1728. //If BASE tag is in play, using appendChild is a problem for IE6.
  1729. //When that browser dies, this can be removed. Details in this jQuery bug:
  1730. //http://dev.jquery.com/ticket/2709
  1731. baseElement = document.getElementsByTagName('base')[0];
  1732. if (baseElement) {
  1733. head = s.head = baseElement.parentNode;
  1734. }
  1735. }
  1736. /**
  1737. * Any errors that require explicitly generates will be passed to this
  1738. * function. Intercept/override it if you want custom error handling.
  1739. * @param {Error} err the error object.
  1740. */
  1741. req.onError = function (err) {
  1742. throw err;
  1743. };
  1744. /**
  1745. * Does the request to load a module for the browser case.
  1746. * Make this a separate function to allow other environments
  1747. * to override it.
  1748. *
  1749. * @param {Object} context the require context to find state.
  1750. * @param {String} moduleName the name of the module.
  1751. * @param {Object} url the URL to the module.
  1752. */
  1753. req.load = function (context, moduleName, url) {
  1754. var config = (context && context.config) || {},
  1755. node;
  1756. if (isBrowser) {
  1757. //In the browser so use a script tag
  1758. node = config.xhtml ?
  1759. document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
  1760. document.createElement('script');
  1761. node.type = config.scriptType || 'text/javascript';
  1762. node.charset = 'utf-8';
  1763. node.async = true;
  1764. node.setAttribute('data-requirecontext', context.contextName);
  1765. node.setAttribute('data-requiremodule', moduleName);
  1766. //Set up load listener. Test attachEvent first because IE9 has
  1767. //a subtle issue in its addEventListener and script onload firings
  1768. //that do not match the behavior of all other browsers with
  1769. //addEventListener support, which fire the onload event for a
  1770. //script right after the script execution. See:
  1771. //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
  1772. //UNFORTUNATELY Opera implements attachEvent but does not follow the script
  1773. //script execution mode.
  1774. if (node.attachEvent &&
  1775. //Check if node.attachEvent is artificially added by custom script or
  1776. //natively supported by browser
  1777. //read https://github.com/jrburke/requirejs/issues/187
  1778. //if we can NOT find [native code] then it must NOT natively supported.
  1779. //in IE8, node.attachEvent does not have toString()
  1780. //Note the test for "[native code" with no closing brace, see:
  1781. //https://github.com/jrburke/requirejs/issues/273
  1782. !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
  1783. !isOpera) {
  1784. //Probably IE. IE (at least 6-8) do not fire
  1785. //script onload right after executing the script, so
  1786. //we cannot tie the anonymous define call to a name.
  1787. //However, IE reports the script as being in 'interactive'
  1788. //readyState at the time of the define call.
  1789. useInteractive = true;
  1790. node.attachEvent('onreadystatechange', context.onScriptLoad);
  1791. //It would be great to add an error handler here to catch
  1792. //404s in IE9+. However, onreadystatechange will fire before
  1793. //the error handler, so that does not help. If addEventListener
  1794. //is used, then IE will fire error before load, but we cannot
  1795. //use that pathway given the connect.microsoft.com issue
  1796. //mentioned above about not doing the 'script execute,
  1797. //then fire the script load event listener before execute
  1798. //next script' that other browsers do.
  1799. //Best hope: IE10 fixes the issues,
  1800. //and then destroys all installs of IE 6-9.
  1801. //node.attachEvent('onerror', context.onScriptError);
  1802. } else {
  1803. node.addEventListener('load', context.onScriptLoad, false);
  1804. node.addEventListener('error', context.onScriptError, false);
  1805. }
  1806. node.src = url;
  1807. //For some cache cases in IE 6-8, the script executes before the end
  1808. //of the appendChild execution, so to tie an anonymous define
  1809. //call to the module name (which is stored on the node), hold on
  1810. //to a reference to this node, but clear after the DOM insertion.
  1811. currentlyAddingScript = node;
  1812. if (baseElement) {
  1813. head.insertBefore(node, baseElement);
  1814. } else {
  1815. head.appendChild(node);
  1816. }
  1817. currentlyAddingScript = null;
  1818. return node;
  1819. } else if (isWebWorker) {
  1820. try {
  1821. //In a web worker, use importScripts. This is not a very
  1822. //efficient use of importScripts, importScripts will block until
  1823. //its script is downloaded and evaluated. However, if web workers
  1824. //are in play, the expectation that a build has been done so that
  1825. //only one script needs to be loaded anyway. This may need to be
  1826. //reevaluated if other use cases become common.
  1827. importScripts(url);
  1828. //Account for anonymous modules
  1829. context.completeLoad(moduleName);
  1830. } catch (e) {
  1831. context.onError(makeError('importscripts',
  1832. 'importScripts failed for ' +
  1833. moduleName + ' at ' + url,
  1834. e,
  1835. [moduleName]));
  1836. }
  1837. }
  1838. };
  1839. function getInteractiveScript() {
  1840. if (interactiveScript && interactiveScript.readyState === 'interactive') {
  1841. return interactiveScript;
  1842. }
  1843. eachReverse(scripts(), function (script) {
  1844. if (script.readyState === 'interactive') {
  1845. return (interactiveScript = script);
  1846. }
  1847. });
  1848. return interactiveScript;
  1849. }
  1850. //Look for a data-main script attribute, which could also adjust the baseUrl.
  1851. if (isBrowser) {
  1852. //Figure out baseUrl. Get it from the script tag with require.js in it.
  1853. eachReverse(scripts(), function (script) {
  1854. //Set the 'head' where we can append children by
  1855. //using the script's parent.
  1856. if (!head) {
  1857. head = script.parentNode;
  1858. }
  1859. //Look for a data-main attribute to set main script for the page
  1860. //to load. If it is there, the path to data main becomes the
  1861. //baseUrl, if it is not already set.
  1862. dataMain = script.getAttribute('data-main');
  1863. if (dataMain) {
  1864. //Set final baseUrl if there is not already an explicit one.
  1865. if (!cfg.baseUrl) {
  1866. //Pull off the directory of data-main for use as the
  1867. //baseUrl.
  1868. src = dataMain.split('/');
  1869. mainScript = src.pop();
  1870. subPath = src.length ? src.join('/') + '/' : './';
  1871. cfg.baseUrl = subPath;
  1872. dataMain = mainScript;
  1873. }
  1874. //Strip off any trailing .js since dataMain is now
  1875. //like a module name.
  1876. dataMain = dataMain.replace(jsSuffixRegExp, '');
  1877. //Put the data-main script in the files to load.
  1878. cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
  1879. return true;
  1880. }
  1881. });
  1882. }
  1883. /**
  1884. * The function that handles definitions of modules. Differs from
  1885. * require() in that a string for the module should be the first argument,
  1886. * and the function to execute after dependencies are loaded should
  1887. * return a value to define the module corresponding to the first argument's
  1888. * name.
  1889. */
  1890. define = function (name, deps, callback) {
  1891. var node, context;
  1892. //Allow for anonymous modules
  1893. if (typeof name !== 'string') {
  1894. //Adjust args appropriately
  1895. callback = deps;
  1896. deps = name;
  1897. name = null;
  1898. }
  1899. //This module may not have dependencies
  1900. if (!isArray(deps)) {
  1901. callback = deps;
  1902. deps = [];
  1903. }
  1904. //If no name, and callback is a function, then figure out if it a
  1905. //CommonJS thing with dependencies.
  1906. if (!deps.length && isFunction(callback)) {
  1907. //Remove comments from the callback string,
  1908. //look for require calls, and pull them into the dependencies,
  1909. //but only if there are function args.
  1910. if (callback.length) {
  1911. callback
  1912. .toString()
  1913. .replace(commentRegExp, '')
  1914. .replace(cjsRequireRegExp, function (match, dep) {
  1915. deps.push(dep);
  1916. });
  1917. //May be a CommonJS thing even without require calls, but still
  1918. //could use exports, and module. Avoid doing exports and module
  1919. //work though if it just needs require.
  1920. //REQUIRES the function to expect the CommonJS variables in the
  1921. //order listed below.
  1922. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
  1923. }
  1924. }
  1925. //If in IE 6-8 and hit an anonymous define() call, do the interactive
  1926. //work.
  1927. if (useInteractive) {
  1928. node = currentlyAddingScript || getInteractiveScript();
  1929. if (node) {
  1930. if (!name) {
  1931. name = node.getAttribute('data-requiremodule');
  1932. }
  1933. context = contexts[node.getAttribute('data-requirecontext')];
  1934. }
  1935. }
  1936. //Always save off evaluating the def call until the script onload handler.
  1937. //This allows multiple modules to be in a file without prematurely
  1938. //tracing dependencies, and allows for anonymous module support,
  1939. //where the module name is not known until the script onload event
  1940. //occurs. If no context, use the global queue, and get it processed
  1941. //in the onscript load callback.
  1942. (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
  1943. };
  1944. define.amd = {
  1945. jQuery: true
  1946. };
  1947. /**
  1948. * Executes the text. Normally just uses eval, but can be modified
  1949. * to use a better, environment-specific call. Only used for transpiling
  1950. * loader plugins, not for plain JS modules.
  1951. * @param {String} text the text to execute/evaluate.
  1952. */
  1953. req.exec = function (text) {
  1954. /*jslint evil: true */
  1955. return eval(text);
  1956. };
  1957. //Set up with config info.
  1958. req(cfg);
  1959. }(this));
  1960. this.requirejsVars = {
  1961. require: require,
  1962. requirejs: require,
  1963. define: define
  1964. };
  1965. if (env === 'browser') {
  1966. /**
  1967. * @license RequireJS rhino Copyright (c) 2012, The Dojo Foundation All Rights Reserved.
  1968. * Available via the MIT or new BSD license.
  1969. * see: http://github.com/jrburke/requirejs for details
  1970. */
  1971. //sloppy since eval enclosed with use strict causes problems if the source
  1972. //text is not strict-compliant.
  1973. /*jslint sloppy: true, evil: true */
  1974. /*global require, XMLHttpRequest */
  1975. (function () {
  1976. require.load = function (context, moduleName, url) {
  1977. var xhr = new XMLHttpRequest();
  1978. xhr.open('GET', url, true);
  1979. xhr.send();
  1980. xhr.onreadystatechange = function () {
  1981. if (xhr.readyState === 4) {
  1982. eval(xhr.responseText);
  1983. //Support anonymous modules.
  1984. context.completeLoad(moduleName);
  1985. }
  1986. };
  1987. };
  1988. }());
  1989. } else if (env === 'rhino') {
  1990. /**
  1991. * @license RequireJS rhino Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  1992. * Available via the MIT or new BSD license.
  1993. * see: http://github.com/jrburke/requirejs for details
  1994. */
  1995. /*jslint */
  1996. /*global require: false, java: false, load: false */
  1997. (function () {
  1998. 'use strict';
  1999. require.load = function (context, moduleName, url) {
  2000. load(url);
  2001. //Support anonymous modules.
  2002. context.completeLoad(moduleName);
  2003. };
  2004. }());
  2005. } else if (env === 'node') {
  2006. this.requirejsVars.nodeRequire = nodeRequire;
  2007. require.nodeRequire = nodeRequire;
  2008. /**
  2009. * @license RequireJS node Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2010. * Available via the MIT or new BSD license.
  2011. * see: http://github.com/jrburke/requirejs for details
  2012. */
  2013. /*jslint regexp: false */
  2014. /*global require: false, define: false, requirejsVars: false, process: false */
  2015. /**
  2016. * This adapter assumes that x.js has loaded it and set up
  2017. * some variables. This adapter just allows limited RequireJS
  2018. * usage from within the requirejs directory. The general
  2019. * node adapater is r.js.
  2020. */
  2021. (function () {
  2022. 'use strict';
  2023. var nodeReq = requirejsVars.nodeRequire,
  2024. req = requirejsVars.require,
  2025. def = requirejsVars.define,
  2026. fs = nodeReq('fs'),
  2027. path = nodeReq('path'),
  2028. vm = nodeReq('vm'),
  2029. //In Node 0.7+ existsSync is on fs.
  2030. exists = fs.existsSync || path.existsSync,
  2031. hasOwn = Object.prototype.hasOwnProperty;
  2032. function hasProp(obj, prop) {
  2033. return hasOwn.call(obj, prop);
  2034. }
  2035. function syncTick(fn) {
  2036. fn();
  2037. }
  2038. //Supply an implementation that allows synchronous get of a module.
  2039. req.get = function (context, moduleName, relModuleMap, localRequire) {
  2040. if (moduleName === "require" || moduleName === "exports" || moduleName === "module") {
  2041. req.onError(new Error("Explicit require of " + moduleName + " is not allowed."));
  2042. }
  2043. var ret, oldTick,
  2044. moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true);
  2045. //Normalize module name, if it contains . or ..
  2046. moduleName = moduleMap.id;
  2047. if (hasProp(context.defined, moduleName)) {
  2048. ret = context.defined[moduleName];
  2049. } else {
  2050. if (ret === undefined) {
  2051. //Make sure nextTick for this type of call is sync-based.
  2052. oldTick = context.nextTick;
  2053. context.nextTick = syncTick;
  2054. try {
  2055. if (moduleMap.prefix) {
  2056. //A plugin, call requirejs to handle it. Now that
  2057. //nextTick is syncTick, the require will complete
  2058. //synchronously.
  2059. localRequire([moduleMap.originalName]);
  2060. //Now that plugin is loaded, can regenerate the moduleMap
  2061. //to get the final, normalized ID.
  2062. moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true);
  2063. moduleName = moduleMap.id;
  2064. } else {
  2065. //Try to dynamically fetch it.
  2066. req.load(context, moduleName, moduleMap.url);
  2067. //Enable the module
  2068. context.enable(moduleMap, relModuleMap);
  2069. }
  2070. //Break any cycles by requiring it normally, but this will
  2071. //finish synchronously
  2072. require([moduleName]);
  2073. //The above calls are sync, so can do the next thing safely.
  2074. ret = context.defined[moduleName];
  2075. } finally {
  2076. context.nextTick = oldTick;
  2077. }
  2078. }
  2079. }
  2080. return ret;
  2081. };
  2082. req.nextTick = function (fn) {
  2083. process.nextTick(fn);
  2084. };
  2085. //Add wrapper around the code so that it gets the requirejs
  2086. //API instead of the Node API, and it is done lexically so
  2087. //that it survives later execution.
  2088. req.makeNodeWrapper = function (contents) {
  2089. return '(function (require, requirejs, define) { ' +
  2090. contents +
  2091. '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));';
  2092. };
  2093. req.load = function (context, moduleName, url) {
  2094. var contents, err;
  2095. if (exists(url)) {
  2096. contents = fs.readFileSync(url, 'utf8');
  2097. contents = req.makeNodeWrapper(contents);
  2098. try {
  2099. vm.runInThisContext(contents, fs.realpathSync(url));
  2100. } catch (e) {
  2101. err = new Error('Evaluating ' + url + ' as module "' +
  2102. moduleName + '" failed with error: ' + e);
  2103. err.originalError = e;
  2104. err.moduleName = moduleName;
  2105. err.fileName = url;
  2106. return req.onError(err);
  2107. }
  2108. } else {
  2109. def(moduleName, function () {
  2110. //Get the original name, since relative requires may be
  2111. //resolved differently in node (issue #202)
  2112. var originalName = hasProp(context.registry, moduleName) &&
  2113. context.registry[moduleName].map.originalName;
  2114. try {
  2115. return (context.config.nodeRequire || req.nodeRequire)(originalName);
  2116. } catch (e) {
  2117. err = new Error('Calling node\'s require("' +
  2118. originalName + '") failed with error: ' + e);
  2119. err.originalError = e;
  2120. err.moduleName = originalName;
  2121. return req.onError(err);
  2122. }
  2123. });
  2124. }
  2125. //Support anonymous modules.
  2126. context.completeLoad(moduleName);
  2127. };
  2128. //Override to provide the function wrapper for define/require.
  2129. req.exec = function (text) {
  2130. /*jslint evil: true */
  2131. text = req.makeNodeWrapper(text);
  2132. return eval(text);
  2133. };
  2134. }());
  2135. } else if (env === 'xpconnect') {
  2136. /**
  2137. * @license RequireJS xpconnect Copyright (c) 2013, The Dojo Foundation All Rights Reserved.
  2138. * Available via the MIT or new BSD license.
  2139. * see: http://github.com/jrburke/requirejs for details
  2140. */
  2141. /*jslint */
  2142. /*global require, load */
  2143. (function () {
  2144. 'use strict';
  2145. require.load = function (context, moduleName, url) {
  2146. load(url);
  2147. //Support anonymous modules.
  2148. context.completeLoad(moduleName);
  2149. };
  2150. }());
  2151. }
  2152. //Support a default file name to execute. Useful for hosted envs
  2153. //like Joyent where it defaults to a server.js as the only executed
  2154. //script. But only do it if this is not an optimization run.
  2155. if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) {
  2156. fileName = 'main.js';
  2157. }
  2158. /**
  2159. * Loads the library files that can be used for the optimizer, or for other
  2160. * tasks.
  2161. */
  2162. function loadLib() {
  2163. /**
  2164. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2165. * Available via the MIT or new BSD license.
  2166. * see: http://github.com/jrburke/requirejs for details
  2167. */
  2168. /*jslint strict: false */
  2169. /*global Packages: false, process: false, window: false, navigator: false,
  2170. document: false, define: false */
  2171. /**
  2172. * A plugin that modifies any /env/ path to be the right path based on
  2173. * the host environment. Right now only works for Node, Rhino and browser.
  2174. */
  2175. (function () {
  2176. var pathRegExp = /(\/|^)env\/|\{env\}/,
  2177. env = 'unknown';
  2178. if (typeof Packages !== 'undefined') {
  2179. env = 'rhino';
  2180. } else if (typeof process !== 'undefined') {
  2181. env = 'node';
  2182. } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  2183. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  2184. env = 'browser';
  2185. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  2186. env = 'xpconnect';
  2187. }
  2188. define('env', {
  2189. get: function () {
  2190. return env;
  2191. },
  2192. load: function (name, req, load, config) {
  2193. //Allow override in the config.
  2194. if (config.env) {
  2195. env = config.env;
  2196. }
  2197. name = name.replace(pathRegExp, function (match, prefix) {
  2198. if (match.indexOf('{') === -1) {
  2199. return prefix + env + '/';
  2200. } else {
  2201. return env;
  2202. }
  2203. });
  2204. req([name], function (mod) {
  2205. load(mod);
  2206. });
  2207. }
  2208. });
  2209. }());/**
  2210. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2211. * Available via the MIT or new BSD license.
  2212. * see: http://github.com/jrburke/requirejs for details
  2213. */
  2214. /*jslint plusplus: true */
  2215. /*global define */
  2216. define('lang', function () {
  2217. 'use strict';
  2218. var lang,
  2219. hasOwn = Object.prototype.hasOwnProperty;
  2220. function hasProp(obj, prop) {
  2221. return hasOwn.call(obj, prop);
  2222. }
  2223. lang = {
  2224. backSlashRegExp: /\\/g,
  2225. ostring: Object.prototype.toString,
  2226. isArray: Array.isArray || function (it) {
  2227. return lang.ostring.call(it) === "[object Array]";
  2228. },
  2229. isFunction: function(it) {
  2230. return lang.ostring.call(it) === "[object Function]";
  2231. },
  2232. isRegExp: function(it) {
  2233. return it && it instanceof RegExp;
  2234. },
  2235. hasProp: hasProp,
  2236. //returns true if the object does not have an own property prop,
  2237. //or if it does, it is a falsy value.
  2238. falseProp: function (obj, prop) {
  2239. return !hasProp(obj, prop) || !obj[prop];
  2240. },
  2241. //gets own property value for given prop on object
  2242. getOwn: function (obj, prop) {
  2243. return hasProp(obj, prop) && obj[prop];
  2244. },
  2245. _mixin: function(dest, source, override){
  2246. var name;
  2247. for (name in source) {
  2248. if(source.hasOwnProperty(name)
  2249. && (override || !dest.hasOwnProperty(name))) {
  2250. dest[name] = source[name];
  2251. }
  2252. }
  2253. return dest; // Object
  2254. },
  2255. /**
  2256. * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,
  2257. * then the source objects properties are force copied over to dest.
  2258. */
  2259. mixin: function(dest){
  2260. var parameters = Array.prototype.slice.call(arguments),
  2261. override, i, l;
  2262. if (!dest) { dest = {}; }
  2263. if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {
  2264. override = parameters.pop();
  2265. }
  2266. for (i = 1, l = parameters.length; i < l; i++) {
  2267. lang._mixin(dest, parameters[i], override);
  2268. }
  2269. return dest; // Object
  2270. },
  2271. delegate: (function () {
  2272. // boodman/crockford delegation w/ cornford optimization
  2273. function TMP() {}
  2274. return function (obj, props) {
  2275. TMP.prototype = obj;
  2276. var tmp = new TMP();
  2277. TMP.prototype = null;
  2278. if (props) {
  2279. lang.mixin(tmp, props);
  2280. }
  2281. return tmp; // Object
  2282. };
  2283. }()),
  2284. /**
  2285. * Helper function for iterating over an array. If the func returns
  2286. * a true value, it will break out of the loop.
  2287. */
  2288. each: function each(ary, func) {
  2289. if (ary) {
  2290. var i;
  2291. for (i = 0; i < ary.length; i += 1) {
  2292. if (func(ary[i], i, ary)) {
  2293. break;
  2294. }
  2295. }
  2296. }
  2297. },
  2298. /**
  2299. * Cycles over properties in an object and calls a function for each
  2300. * property value. If the function returns a truthy value, then the
  2301. * iteration is stopped.
  2302. */
  2303. eachProp: function eachProp(obj, func) {
  2304. var prop;
  2305. for (prop in obj) {
  2306. if (hasProp(obj, prop)) {
  2307. if (func(obj[prop], prop)) {
  2308. break;
  2309. }
  2310. }
  2311. }
  2312. },
  2313. //Similar to Function.prototype.bind, but the "this" object is specified
  2314. //first, since it is easier to read/figure out what "this" will be.
  2315. bind: function bind(obj, fn) {
  2316. return function () {
  2317. return fn.apply(obj, arguments);
  2318. };
  2319. },
  2320. //Escapes a content string to be be a string that has characters escaped
  2321. //for inclusion as part of a JS string.
  2322. jsEscape: function (content) {
  2323. return content.replace(/(["'\\])/g, '\\$1')
  2324. .replace(/[\f]/g, "\\f")
  2325. .replace(/[\b]/g, "\\b")
  2326. .replace(/[\n]/g, "\\n")
  2327. .replace(/[\t]/g, "\\t")
  2328. .replace(/[\r]/g, "\\r");
  2329. }
  2330. };
  2331. return lang;
  2332. });
  2333. /**
  2334. * prim 0.0.1 Copyright (c) 2012-2013, The Dojo Foundation All Rights Reserved.
  2335. * Available via the MIT or new BSD license.
  2336. * see: http://github.com/requirejs/prim for details
  2337. */
  2338. /*global setImmediate, process, setTimeout, define, module */
  2339. //Set prime.hideResolutionConflict = true to allow "resolution-races"
  2340. //in promise-tests to pass.
  2341. //Since the goal of prim is to be a small impl for trusted code, it is
  2342. //more important to normally throw in this case so that we can find
  2343. //logic errors quicker.
  2344. var prim;
  2345. (function () {
  2346. 'use strict';
  2347. var op = Object.prototype,
  2348. hasOwn = op.hasOwnProperty;
  2349. function hasProp(obj, prop) {
  2350. return hasOwn.call(obj, prop);
  2351. }
  2352. /**
  2353. * Helper function for iterating over an array. If the func returns
  2354. * a true value, it will break out of the loop.
  2355. */
  2356. function each(ary, func) {
  2357. if (ary) {
  2358. var i;
  2359. for (i = 0; i < ary.length; i += 1) {
  2360. if (ary[i]) {
  2361. func(ary[i], i, ary);
  2362. }
  2363. }
  2364. }
  2365. }
  2366. function check(p) {
  2367. if (hasProp(p, 'e') || hasProp(p, 'v')) {
  2368. if (!prim.hideResolutionConflict) {
  2369. throw new Error('nope');
  2370. }
  2371. return false;
  2372. }
  2373. return true;
  2374. }
  2375. function notify(ary, value) {
  2376. prim.nextTick(function () {
  2377. each(ary, function (item) {
  2378. item(value);
  2379. });
  2380. });
  2381. }
  2382. prim = function prim() {
  2383. var p,
  2384. ok = [],
  2385. fail = [];
  2386. return (p = {
  2387. callback: function (yes, no) {
  2388. if (no) {
  2389. p.errback(no);
  2390. }
  2391. if (hasProp(p, 'v')) {
  2392. prim.nextTick(function () {
  2393. yes(p.v);
  2394. });
  2395. } else {
  2396. ok.push(yes);
  2397. }
  2398. },
  2399. errback: function (no) {
  2400. if (hasProp(p, 'e')) {
  2401. prim.nextTick(function () {
  2402. no(p.e);
  2403. });
  2404. } else {
  2405. fail.push(no);
  2406. }
  2407. },
  2408. finished: function () {
  2409. return hasProp(p, 'e') || hasProp(p, 'v');
  2410. },
  2411. rejected: function () {
  2412. return hasProp(p, 'e');
  2413. },
  2414. resolve: function (v) {
  2415. if (check(p)) {
  2416. p.v = v;
  2417. notify(ok, v);
  2418. }
  2419. return p;
  2420. },
  2421. reject: function (e) {
  2422. if (check(p)) {
  2423. p.e = e;
  2424. notify(fail, e);
  2425. }
  2426. return p;
  2427. },
  2428. start: function (fn) {
  2429. p.resolve();
  2430. return p.promise.then(fn);
  2431. },
  2432. promise: {
  2433. then: function (yes, no) {
  2434. var next = prim();
  2435. p.callback(function (v) {
  2436. try {
  2437. if (yes && typeof yes === 'function') {
  2438. v = yes(v);
  2439. }
  2440. if (v && v.then) {
  2441. v.then(next.resolve, next.reject);
  2442. } else {
  2443. next.resolve(v);
  2444. }
  2445. } catch (e) {
  2446. next.reject(e);
  2447. }
  2448. }, function (e) {
  2449. var err;
  2450. try {
  2451. if (!no || typeof no !== 'function') {
  2452. next.reject(e);
  2453. } else {
  2454. err = no(e);
  2455. if (err && err.then) {
  2456. err.then(next.resolve, next.reject);
  2457. } else {
  2458. next.resolve(err);
  2459. }
  2460. }
  2461. } catch (e2) {
  2462. next.reject(e2);
  2463. }
  2464. });
  2465. return next.promise;
  2466. },
  2467. fail: function (no) {
  2468. return p.promise.then(null, no);
  2469. },
  2470. end: function () {
  2471. p.errback(function (e) {
  2472. throw e;
  2473. });
  2474. }
  2475. }
  2476. });
  2477. };
  2478. prim.serial = function (ary) {
  2479. var result = prim().resolve().promise;
  2480. each(ary, function (item) {
  2481. result = result.then(function () {
  2482. return item();
  2483. });
  2484. });
  2485. return result;
  2486. };
  2487. prim.nextTick = typeof setImmediate === 'function' ? setImmediate :
  2488. (typeof process !== 'undefined' && process.nextTick ?
  2489. process.nextTick : (typeof setTimeout !== 'undefined' ?
  2490. function (fn) {
  2491. setTimeout(fn, 0);
  2492. } : function (fn) {
  2493. fn();
  2494. }));
  2495. if (typeof define === 'function' && define.amd) {
  2496. define('prim', function () { return prim; });
  2497. } else if (typeof module !== 'undefined' && module.exports) {
  2498. module.exports = prim;
  2499. }
  2500. }());
  2501. if(env === 'browser') {
  2502. /**
  2503. * @license RequireJS Copyright (c) 2012, The Dojo Foundation All Rights Reserved.
  2504. * Available via the MIT or new BSD license.
  2505. * see: http://github.com/jrburke/requirejs for details
  2506. */
  2507. /*jslint strict: false */
  2508. /*global define: false, load: false */
  2509. //Just a stub for use with uglify's consolidator.js
  2510. define('browser/assert', function () {
  2511. return {};
  2512. });
  2513. }
  2514. if(env === 'node') {
  2515. /**
  2516. * @license RequireJS Copyright (c) 2012, The Dojo Foundation All Rights Reserved.
  2517. * Available via the MIT or new BSD license.
  2518. * see: http://github.com/jrburke/requirejs for details
  2519. */
  2520. /*jslint strict: false */
  2521. /*global define: false, load: false */
  2522. //Needed so that rhino/assert can return a stub for uglify's consolidator.js
  2523. define('node/assert', ['assert'], function (assert) {
  2524. return assert;
  2525. });
  2526. }
  2527. if(env === 'rhino') {
  2528. /**
  2529. * @license RequireJS Copyright (c) 2012, The Dojo Foundation All Rights Reserved.
  2530. * Available via the MIT or new BSD license.
  2531. * see: http://github.com/jrburke/requirejs for details
  2532. */
  2533. /*jslint strict: false */
  2534. /*global define: false, load: false */
  2535. //Just a stub for use with uglify's consolidator.js
  2536. define('rhino/assert', function () {
  2537. return {};
  2538. });
  2539. }
  2540. if(env === 'xpconnect') {
  2541. /**
  2542. * @license RequireJS Copyright (c) 2013, The Dojo Foundation All Rights Reserved.
  2543. * Available via the MIT or new BSD license.
  2544. * see: http://github.com/jrburke/requirejs for details
  2545. */
  2546. /*jslint strict: false */
  2547. /*global define: false, load: false */
  2548. //Just a stub for use with uglify's consolidator.js
  2549. define('xpconnect/assert', function () {
  2550. return {};
  2551. });
  2552. }
  2553. if(env === 'browser') {
  2554. /**
  2555. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2556. * Available via the MIT or new BSD license.
  2557. * see: http://github.com/jrburke/requirejs for details
  2558. */
  2559. /*jslint strict: false */
  2560. /*global define: false, process: false */
  2561. define('browser/args', function () {
  2562. //Always expect config via an API call
  2563. return [];
  2564. });
  2565. }
  2566. if(env === 'node') {
  2567. /**
  2568. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2569. * Available via the MIT or new BSD license.
  2570. * see: http://github.com/jrburke/requirejs for details
  2571. */
  2572. /*jslint strict: false */
  2573. /*global define: false, process: false */
  2574. define('node/args', function () {
  2575. //Do not return the "node" or "r.js" arguments
  2576. var args = process.argv.slice(2);
  2577. //Ignore any command option used for rq.js
  2578. if (args[0] && args[0].indexOf('-' === 0)) {
  2579. args = args.slice(1);
  2580. }
  2581. return args;
  2582. });
  2583. }
  2584. if(env === 'rhino') {
  2585. /**
  2586. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2587. * Available via the MIT or new BSD license.
  2588. * see: http://github.com/jrburke/requirejs for details
  2589. */
  2590. /*jslint strict: false */
  2591. /*global define: false, process: false */
  2592. var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2593. define('rhino/args', function () {
  2594. var args = jsLibRhinoArgs;
  2595. //Ignore any command option used for r.js
  2596. if (args[0] && args[0].indexOf('-' === 0)) {
  2597. args = args.slice(1);
  2598. }
  2599. return args;
  2600. });
  2601. }
  2602. if(env === 'xpconnect') {
  2603. /**
  2604. * @license Copyright (c) 2013, The Dojo Foundation All Rights Reserved.
  2605. * Available via the MIT or new BSD license.
  2606. * see: http://github.com/jrburke/requirejs for details
  2607. */
  2608. /*jslint strict: false */
  2609. /*global define, xpconnectArgs */
  2610. var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2611. define('xpconnect/args', function () {
  2612. var args = jsLibXpConnectArgs;
  2613. //Ignore any command option used for r.js
  2614. if (args[0] && args[0].indexOf('-' === 0)) {
  2615. args = args.slice(1);
  2616. }
  2617. return args;
  2618. });
  2619. }
  2620. if(env === 'browser') {
  2621. /**
  2622. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2623. * Available via the MIT or new BSD license.
  2624. * see: http://github.com/jrburke/requirejs for details
  2625. */
  2626. /*jslint strict: false */
  2627. /*global define: false, console: false */
  2628. define('browser/load', ['./file'], function (file) {
  2629. function load(fileName) {
  2630. eval(file.readFile(fileName));
  2631. }
  2632. return load;
  2633. });
  2634. }
  2635. if(env === 'node') {
  2636. /**
  2637. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2638. * Available via the MIT or new BSD license.
  2639. * see: http://github.com/jrburke/requirejs for details
  2640. */
  2641. /*jslint strict: false */
  2642. /*global define: false, console: false */
  2643. define('node/load', ['fs'], function (fs) {
  2644. function load(fileName) {
  2645. var contents = fs.readFileSync(fileName, 'utf8');
  2646. process.compile(contents, fileName);
  2647. }
  2648. return load;
  2649. });
  2650. }
  2651. if(env === 'rhino') {
  2652. /**
  2653. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2654. * Available via the MIT or new BSD license.
  2655. * see: http://github.com/jrburke/requirejs for details
  2656. */
  2657. /*jslint strict: false */
  2658. /*global define: false, load: false */
  2659. define('rhino/load', function () {
  2660. return load;
  2661. });
  2662. }
  2663. if(env === 'xpconnect') {
  2664. /**
  2665. * @license RequireJS Copyright (c) 2013, The Dojo Foundation All Rights Reserved.
  2666. * Available via the MIT or new BSD license.
  2667. * see: http://github.com/jrburke/requirejs for details
  2668. */
  2669. /*jslint strict: false */
  2670. /*global define: false, load: false */
  2671. define('xpconnect/load', function () {
  2672. return load;
  2673. });
  2674. }
  2675. if(env === 'browser') {
  2676. /**
  2677. * @license Copyright (c) 2012, 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 sloppy: true, nomen: true */
  2682. /*global require, define, console, XMLHttpRequest, requirejs, location */
  2683. define('browser/file', ['prim'], function (prim) {
  2684. var file,
  2685. currDirRegExp = /^\.(\/|$)/;
  2686. function frontSlash(path) {
  2687. return path.replace(/\\/g, '/');
  2688. }
  2689. function exists(path) {
  2690. var status, xhr = new XMLHttpRequest();
  2691. //Oh yeah, that is right SYNC IO. Behold its glory
  2692. //and horrible blocking behavior.
  2693. xhr.open('HEAD', path, false);
  2694. xhr.send();
  2695. status = xhr.status;
  2696. return status === 200 || status === 304;
  2697. }
  2698. function mkDir(dir) {
  2699. console.log('mkDir is no-op in browser');
  2700. }
  2701. function mkFullDir(dir) {
  2702. console.log('mkFullDir is no-op in browser');
  2703. }
  2704. file = {
  2705. backSlashRegExp: /\\/g,
  2706. exclusionRegExp: /^\./,
  2707. getLineSeparator: function () {
  2708. return '/';
  2709. },
  2710. exists: function (fileName) {
  2711. return exists(fileName);
  2712. },
  2713. parent: function (fileName) {
  2714. var parts = fileName.split('/');
  2715. parts.pop();
  2716. return parts.join('/');
  2717. },
  2718. /**
  2719. * Gets the absolute file path as a string, normalized
  2720. * to using front slashes for path separators.
  2721. * @param {String} fileName
  2722. */
  2723. absPath: function (fileName) {
  2724. var dir;
  2725. if (currDirRegExp.test(fileName)) {
  2726. dir = frontSlash(location.href);
  2727. if (dir.indexOf('/') !== -1) {
  2728. dir = dir.split('/');
  2729. //Pull off protocol and host, just want
  2730. //to allow paths (other build parts, like
  2731. //require._isSupportedBuildUrl do not support
  2732. //full URLs), but a full path from
  2733. //the root.
  2734. dir.splice(0, 3);
  2735. dir.pop();
  2736. dir = '/' + dir.join('/');
  2737. }
  2738. fileName = dir + fileName.substring(1);
  2739. }
  2740. return fileName;
  2741. },
  2742. normalize: function (fileName) {
  2743. return fileName;
  2744. },
  2745. isFile: function (path) {
  2746. return true;
  2747. },
  2748. isDirectory: function (path) {
  2749. return false;
  2750. },
  2751. getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) {
  2752. console.log('file.getFilteredFileList is no-op in browser');
  2753. },
  2754. copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) {
  2755. console.log('file.copyDir is no-op in browser');
  2756. },
  2757. copyFile: function (srcFileName, destFileName, onlyCopyNew) {
  2758. console.log('file.copyFile is no-op in browser');
  2759. },
  2760. /**
  2761. * Renames a file. May fail if "to" already exists or is on another drive.
  2762. */
  2763. renameFile: function (from, to) {
  2764. console.log('file.renameFile is no-op in browser');
  2765. },
  2766. /**
  2767. * Reads a *text* file.
  2768. */
  2769. readFile: function (path, encoding) {
  2770. var xhr = new XMLHttpRequest();
  2771. //Oh yeah, that is right SYNC IO. Behold its glory
  2772. //and horrible blocking behavior.
  2773. xhr.open('GET', path, false);
  2774. xhr.send();
  2775. return xhr.responseText;
  2776. },
  2777. readFileAsync: function (path, encoding) {
  2778. var xhr = new XMLHttpRequest(),
  2779. d = prim();
  2780. xhr.open('GET', path, true);
  2781. xhr.send();
  2782. xhr.onreadystatechange = function () {
  2783. if (xhr.readyState === 4) {
  2784. if (xhr.status > 400) {
  2785. d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText));
  2786. } else {
  2787. d.resolve(xhr.responseText);
  2788. }
  2789. }
  2790. };
  2791. return d.promise;
  2792. },
  2793. saveUtf8File: function (fileName, fileContents) {
  2794. //summary: saves a *text* file using UTF-8 encoding.
  2795. file.saveFile(fileName, fileContents, "utf8");
  2796. },
  2797. saveFile: function (fileName, fileContents, encoding) {
  2798. requirejs.browser.saveFile(fileName, fileContents, encoding);
  2799. },
  2800. deleteFile: function (fileName) {
  2801. console.log('file.deleteFile is no-op in browser');
  2802. },
  2803. /**
  2804. * Deletes any empty directories under the given directory.
  2805. */
  2806. deleteEmptyDirs: function (startDir) {
  2807. console.log('file.deleteEmptyDirs is no-op in browser');
  2808. }
  2809. };
  2810. return file;
  2811. });
  2812. }
  2813. if(env === 'node') {
  2814. /**
  2815. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  2816. * Available via the MIT or new BSD license.
  2817. * see: http://github.com/jrburke/requirejs for details
  2818. */
  2819. /*jslint plusplus: false, octal:false, strict: false */
  2820. /*global define: false, process: false */
  2821. define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) {
  2822. var isWindows = process.platform === 'win32',
  2823. windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
  2824. file;
  2825. function frontSlash(path) {
  2826. return path.replace(/\\/g, '/');
  2827. }
  2828. function exists(path) {
  2829. if (isWindows && path.charAt(path.length - 1) === '/' &&
  2830. path.charAt(path.length - 2) !== ':') {
  2831. path = path.substring(0, path.length - 1);
  2832. }
  2833. try {
  2834. fs.statSync(path);
  2835. return true;
  2836. } catch (e) {
  2837. return false;
  2838. }
  2839. }
  2840. function mkDir(dir) {
  2841. if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {
  2842. fs.mkdirSync(dir, 511);
  2843. }
  2844. }
  2845. function mkFullDir(dir) {
  2846. var parts = dir.split('/'),
  2847. currDir = '',
  2848. first = true;
  2849. parts.forEach(function (part) {
  2850. //First part may be empty string if path starts with a slash.
  2851. currDir += part + '/';
  2852. first = false;
  2853. if (part) {
  2854. mkDir(currDir);
  2855. }
  2856. });
  2857. }
  2858. file = {
  2859. backSlashRegExp: /\\/g,
  2860. exclusionRegExp: /^\./,
  2861. getLineSeparator: function () {
  2862. return '/';
  2863. },
  2864. exists: function (fileName) {
  2865. return exists(fileName);
  2866. },
  2867. parent: function (fileName) {
  2868. var parts = fileName.split('/');
  2869. parts.pop();
  2870. return parts.join('/');
  2871. },
  2872. /**
  2873. * Gets the absolute file path as a string, normalized
  2874. * to using front slashes for path separators.
  2875. * @param {String} fileName
  2876. */
  2877. absPath: function (fileName) {
  2878. return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));
  2879. },
  2880. normalize: function (fileName) {
  2881. return frontSlash(path.normalize(fileName));
  2882. },
  2883. isFile: function (path) {
  2884. return fs.statSync(path).isFile();
  2885. },
  2886. isDirectory: function (path) {
  2887. return fs.statSync(path).isDirectory();
  2888. },
  2889. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {
  2890. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  2891. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  2892. //and it will be treated as the "include" case.
  2893. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  2894. //is set to another value.
  2895. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  2896. i, stat, filePath, ok, dirFiles, fileName;
  2897. topDir = startDir;
  2898. regExpInclude = regExpFilters.include || regExpFilters;
  2899. regExpExclude = regExpFilters.exclude || null;
  2900. if (file.exists(topDir)) {
  2901. dirFileArray = fs.readdirSync(topDir);
  2902. for (i = 0; i < dirFileArray.length; i++) {
  2903. fileName = dirFileArray[i];
  2904. filePath = path.join(topDir, fileName);
  2905. stat = fs.statSync(filePath);
  2906. if (stat.isFile()) {
  2907. if (makeUnixPaths) {
  2908. //Make sure we have a JS string.
  2909. if (filePath.indexOf("/") === -1) {
  2910. filePath = frontSlash(filePath);
  2911. }
  2912. }
  2913. ok = true;
  2914. if (regExpInclude) {
  2915. ok = filePath.match(regExpInclude);
  2916. }
  2917. if (ok && regExpExclude) {
  2918. ok = !filePath.match(regExpExclude);
  2919. }
  2920. if (ok && (!file.exclusionRegExp ||
  2921. !file.exclusionRegExp.test(fileName))) {
  2922. files.push(filePath);
  2923. }
  2924. } else if (stat.isDirectory() &&
  2925. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {
  2926. dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);
  2927. files.push.apply(files, dirFiles);
  2928. }
  2929. }
  2930. }
  2931. return files; //Array
  2932. },
  2933. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  2934. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  2935. //file should be copied. Returns a list file name strings of the destinations that were copied.
  2936. regExpFilter = regExpFilter || /\w/;
  2937. //Normalize th directory names, but keep front slashes.
  2938. //path module on windows now returns backslashed paths.
  2939. srcDir = frontSlash(path.normalize(srcDir));
  2940. destDir = frontSlash(path.normalize(destDir));
  2941. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  2942. copiedFiles = [], i, srcFileName, destFileName;
  2943. for (i = 0; i < fileNames.length; i++) {
  2944. srcFileName = fileNames[i];
  2945. destFileName = srcFileName.replace(srcDir, destDir);
  2946. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  2947. copiedFiles.push(destFileName);
  2948. }
  2949. }
  2950. return copiedFiles.length ? copiedFiles : null; //Array or null
  2951. },
  2952. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  2953. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  2954. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  2955. var parentDir;
  2956. //logger.trace("Src filename: " + srcFileName);
  2957. //logger.trace("Dest filename: " + destFileName);
  2958. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  2959. //than dest.
  2960. if (onlyCopyNew) {
  2961. if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {
  2962. return false; //Boolean
  2963. }
  2964. }
  2965. //Make sure destination dir exists.
  2966. parentDir = path.dirname(destFileName);
  2967. if (!file.exists(parentDir)) {
  2968. mkFullDir(parentDir);
  2969. }
  2970. fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');
  2971. return true; //Boolean
  2972. },
  2973. /**
  2974. * Renames a file. May fail if "to" already exists or is on another drive.
  2975. */
  2976. renameFile: function (from, to) {
  2977. return fs.renameSync(from, to);
  2978. },
  2979. /**
  2980. * Reads a *text* file.
  2981. */
  2982. readFile: function (/*String*/path, /*String?*/encoding) {
  2983. if (encoding === 'utf-8') {
  2984. encoding = 'utf8';
  2985. }
  2986. if (!encoding) {
  2987. encoding = 'utf8';
  2988. }
  2989. var text = fs.readFileSync(path, encoding);
  2990. //Hmm, would not expect to get A BOM, but it seems to happen,
  2991. //remove it just in case.
  2992. if (text.indexOf('\uFEFF') === 0) {
  2993. text = text.substring(1, text.length);
  2994. }
  2995. return text;
  2996. },
  2997. readFileAsync: function (path, encoding) {
  2998. var d = prim();
  2999. try {
  3000. d.resolve(file.readFile(path, encoding));
  3001. } catch (e) {
  3002. d.reject(e);
  3003. }
  3004. return d.promise;
  3005. },
  3006. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3007. //summary: saves a *text* file using UTF-8 encoding.
  3008. file.saveFile(fileName, fileContents, "utf8");
  3009. },
  3010. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3011. //summary: saves a *text* file.
  3012. var parentDir;
  3013. if (encoding === 'utf-8') {
  3014. encoding = 'utf8';
  3015. }
  3016. if (!encoding) {
  3017. encoding = 'utf8';
  3018. }
  3019. //Make sure destination directories exist.
  3020. parentDir = path.dirname(fileName);
  3021. if (!file.exists(parentDir)) {
  3022. mkFullDir(parentDir);
  3023. }
  3024. fs.writeFileSync(fileName, fileContents, encoding);
  3025. },
  3026. deleteFile: function (/*String*/fileName) {
  3027. //summary: deletes a file or directory if it exists.
  3028. var files, i, stat;
  3029. if (file.exists(fileName)) {
  3030. stat = fs.statSync(fileName);
  3031. if (stat.isDirectory()) {
  3032. files = fs.readdirSync(fileName);
  3033. for (i = 0; i < files.length; i++) {
  3034. this.deleteFile(path.join(fileName, files[i]));
  3035. }
  3036. fs.rmdirSync(fileName);
  3037. } else {
  3038. fs.unlinkSync(fileName);
  3039. }
  3040. }
  3041. },
  3042. /**
  3043. * Deletes any empty directories under the given directory.
  3044. */
  3045. deleteEmptyDirs: function (startDir) {
  3046. var dirFileArray, i, fileName, filePath, stat;
  3047. if (file.exists(startDir)) {
  3048. dirFileArray = fs.readdirSync(startDir);
  3049. for (i = 0; i < dirFileArray.length; i++) {
  3050. fileName = dirFileArray[i];
  3051. filePath = path.join(startDir, fileName);
  3052. stat = fs.statSync(filePath);
  3053. if (stat.isDirectory()) {
  3054. file.deleteEmptyDirs(filePath);
  3055. }
  3056. }
  3057. //If directory is now empty, remove it.
  3058. if (fs.readdirSync(startDir).length === 0) {
  3059. file.deleteFile(startDir);
  3060. }
  3061. }
  3062. }
  3063. };
  3064. return file;
  3065. });
  3066. }
  3067. if(env === 'rhino') {
  3068. /**
  3069. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  3070. * Available via the MIT or new BSD license.
  3071. * see: http://github.com/jrburke/requirejs for details
  3072. */
  3073. //Helper functions to deal with file I/O.
  3074. /*jslint plusplus: false */
  3075. /*global java: false, define: false */
  3076. define('rhino/file', ['prim'], function (prim) {
  3077. var file = {
  3078. backSlashRegExp: /\\/g,
  3079. exclusionRegExp: /^\./,
  3080. getLineSeparator: function () {
  3081. return file.lineSeparator;
  3082. },
  3083. lineSeparator: java.lang.System.getProperty("line.separator"), //Java String
  3084. exists: function (fileName) {
  3085. return (new java.io.File(fileName)).exists();
  3086. },
  3087. parent: function (fileName) {
  3088. return file.absPath((new java.io.File(fileName)).getParentFile());
  3089. },
  3090. normalize: function (fileName) {
  3091. return file.absPath(fileName);
  3092. },
  3093. isFile: function (path) {
  3094. return (new java.io.File(path)).isFile();
  3095. },
  3096. isDirectory: function (path) {
  3097. return (new java.io.File(path)).isDirectory();
  3098. },
  3099. /**
  3100. * Gets the absolute file path as a string, normalized
  3101. * to using front slashes for path separators.
  3102. * @param {java.io.File||String} file
  3103. */
  3104. absPath: function (fileObj) {
  3105. if (typeof fileObj === "string") {
  3106. fileObj = new java.io.File(fileObj);
  3107. }
  3108. return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
  3109. },
  3110. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {
  3111. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3112. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3113. //and it will be treated as the "include" case.
  3114. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3115. //is set to another value.
  3116. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3117. i, fileObj, filePath, ok, dirFiles;
  3118. topDir = startDir;
  3119. if (!startDirIsJavaObject) {
  3120. topDir = new java.io.File(startDir);
  3121. }
  3122. regExpInclude = regExpFilters.include || regExpFilters;
  3123. regExpExclude = regExpFilters.exclude || null;
  3124. if (topDir.exists()) {
  3125. dirFileArray = topDir.listFiles();
  3126. for (i = 0; i < dirFileArray.length; i++) {
  3127. fileObj = dirFileArray[i];
  3128. if (fileObj.isFile()) {
  3129. filePath = fileObj.getPath();
  3130. if (makeUnixPaths) {
  3131. //Make sure we have a JS string.
  3132. filePath = String(filePath);
  3133. if (filePath.indexOf("/") === -1) {
  3134. filePath = filePath.replace(/\\/g, "/");
  3135. }
  3136. }
  3137. ok = true;
  3138. if (regExpInclude) {
  3139. ok = filePath.match(regExpInclude);
  3140. }
  3141. if (ok && regExpExclude) {
  3142. ok = !filePath.match(regExpExclude);
  3143. }
  3144. if (ok && (!file.exclusionRegExp ||
  3145. !file.exclusionRegExp.test(fileObj.getName()))) {
  3146. files.push(filePath);
  3147. }
  3148. } else if (fileObj.isDirectory() &&
  3149. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {
  3150. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3151. files.push.apply(files, dirFiles);
  3152. }
  3153. }
  3154. }
  3155. return files; //Array
  3156. },
  3157. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3158. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3159. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3160. regExpFilter = regExpFilter || /\w/;
  3161. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3162. copiedFiles = [], i, srcFileName, destFileName;
  3163. for (i = 0; i < fileNames.length; i++) {
  3164. srcFileName = fileNames[i];
  3165. destFileName = srcFileName.replace(srcDir, destDir);
  3166. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3167. copiedFiles.push(destFileName);
  3168. }
  3169. }
  3170. return copiedFiles.length ? copiedFiles : null; //Array or null
  3171. },
  3172. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3173. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3174. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3175. var destFile = new java.io.File(destFileName), srcFile, parentDir,
  3176. srcChannel, destChannel;
  3177. //logger.trace("Src filename: " + srcFileName);
  3178. //logger.trace("Dest filename: " + destFileName);
  3179. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3180. //than dest.
  3181. if (onlyCopyNew) {
  3182. srcFile = new java.io.File(srcFileName);
  3183. if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {
  3184. return false; //Boolean
  3185. }
  3186. }
  3187. //Make sure destination dir exists.
  3188. parentDir = destFile.getParentFile();
  3189. if (!parentDir.exists()) {
  3190. if (!parentDir.mkdirs()) {
  3191. throw "Could not create directory: " + parentDir.getCanonicalPath();
  3192. }
  3193. }
  3194. //Java's version of copy file.
  3195. srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
  3196. destChannel = new java.io.FileOutputStream(destFileName).getChannel();
  3197. destChannel.transferFrom(srcChannel, 0, srcChannel.size());
  3198. srcChannel.close();
  3199. destChannel.close();
  3200. return true; //Boolean
  3201. },
  3202. /**
  3203. * Renames a file. May fail if "to" already exists or is on another drive.
  3204. */
  3205. renameFile: function (from, to) {
  3206. return (new java.io.File(from)).renameTo((new java.io.File(to)));
  3207. },
  3208. readFile: function (/*String*/path, /*String?*/encoding) {
  3209. //A file read function that can deal with BOMs
  3210. encoding = encoding || "utf-8";
  3211. var fileObj = new java.io.File(path),
  3212. input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),
  3213. stringBuffer, line;
  3214. try {
  3215. stringBuffer = new java.lang.StringBuffer();
  3216. line = input.readLine();
  3217. // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
  3218. // http://www.unicode.org/faq/utf_bom.html
  3219. // 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:
  3220. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
  3221. if (line && line.length() && line.charAt(0) === 0xfeff) {
  3222. // Eat the BOM, since we've already found the encoding on this file,
  3223. // and we plan to concatenating this buffer with others; the BOM should
  3224. // only appear at the top of a file.
  3225. line = line.substring(1);
  3226. }
  3227. while (line !== null) {
  3228. stringBuffer.append(line);
  3229. stringBuffer.append(file.lineSeparator);
  3230. line = input.readLine();
  3231. }
  3232. //Make sure we return a JavaScript string and not a Java string.
  3233. return String(stringBuffer.toString()); //String
  3234. } finally {
  3235. input.close();
  3236. }
  3237. },
  3238. readFileAsync: function (path, encoding) {
  3239. var d = prim();
  3240. try {
  3241. d.resolve(file.readFile(path, encoding));
  3242. } catch (e) {
  3243. d.reject(e);
  3244. }
  3245. return d.promise;
  3246. },
  3247. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3248. //summary: saves a file using UTF-8 encoding.
  3249. file.saveFile(fileName, fileContents, "utf-8");
  3250. },
  3251. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3252. //summary: saves a file.
  3253. var outFile = new java.io.File(fileName), outWriter, parentDir, os;
  3254. parentDir = outFile.getAbsoluteFile().getParentFile();
  3255. if (!parentDir.exists()) {
  3256. if (!parentDir.mkdirs()) {
  3257. throw "Could not create directory: " + parentDir.getAbsolutePath();
  3258. }
  3259. }
  3260. if (encoding) {
  3261. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  3262. } else {
  3263. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  3264. }
  3265. os = new java.io.BufferedWriter(outWriter);
  3266. try {
  3267. os.write(fileContents);
  3268. } finally {
  3269. os.close();
  3270. }
  3271. },
  3272. deleteFile: function (/*String*/fileName) {
  3273. //summary: deletes a file or directory if it exists.
  3274. var fileObj = new java.io.File(fileName), files, i;
  3275. if (fileObj.exists()) {
  3276. if (fileObj.isDirectory()) {
  3277. files = fileObj.listFiles();
  3278. for (i = 0; i < files.length; i++) {
  3279. this.deleteFile(files[i]);
  3280. }
  3281. }
  3282. fileObj["delete"]();
  3283. }
  3284. },
  3285. /**
  3286. * Deletes any empty directories under the given directory.
  3287. * The startDirIsJavaObject is private to this implementation's
  3288. * recursion needs.
  3289. */
  3290. deleteEmptyDirs: function (startDir, startDirIsJavaObject) {
  3291. var topDir = startDir,
  3292. dirFileArray, i, fileObj;
  3293. if (!startDirIsJavaObject) {
  3294. topDir = new java.io.File(startDir);
  3295. }
  3296. if (topDir.exists()) {
  3297. dirFileArray = topDir.listFiles();
  3298. for (i = 0; i < dirFileArray.length; i++) {
  3299. fileObj = dirFileArray[i];
  3300. if (fileObj.isDirectory()) {
  3301. file.deleteEmptyDirs(fileObj, true);
  3302. }
  3303. }
  3304. //If the directory is empty now, delete it.
  3305. if (topDir.listFiles().length === 0) {
  3306. file.deleteFile(String(topDir.getPath()));
  3307. }
  3308. }
  3309. }
  3310. };
  3311. return file;
  3312. });
  3313. }
  3314. if(env === 'xpconnect') {
  3315. /**
  3316. * @license RequireJS Copyright (c) 2013, The Dojo Foundation All Rights Reserved.
  3317. * Available via the MIT or new BSD license.
  3318. * see: http://github.com/jrburke/requirejs for details
  3319. */
  3320. //Helper functions to deal with file I/O.
  3321. /*jslint plusplus: false */
  3322. /*global define, Components, xpcUtil */
  3323. define('xpconnect/file', ['prim'], function (prim) {
  3324. var file,
  3325. Cc = Components.classes,
  3326. Ci = Components.interfaces,
  3327. //Depends on xpcUtil which is set up in x.js
  3328. xpfile = xpcUtil.xpfile;
  3329. function mkFullDir(dirObj) {
  3330. //1 is DIRECTORY_TYPE, 511 is 0777 permissions
  3331. if (!dirObj.exists()) {
  3332. dirObj.create(1, 511);
  3333. }
  3334. }
  3335. file = {
  3336. backSlashRegExp: /\\/g,
  3337. exclusionRegExp: /^\./,
  3338. getLineSeparator: function () {
  3339. return file.lineSeparator;
  3340. },
  3341. lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ?
  3342. '\r\n' : '\n',
  3343. exists: function (fileName) {
  3344. return xpfile(fileName).exists();
  3345. },
  3346. parent: function (fileName) {
  3347. return xpfile(fileName).parent;
  3348. },
  3349. normalize: function (fileName) {
  3350. return file.absPath(fileName);
  3351. },
  3352. isFile: function (path) {
  3353. return xpfile(path).isFile();
  3354. },
  3355. isDirectory: function (path) {
  3356. return xpfile(path).isDirectory();
  3357. },
  3358. /**
  3359. * Gets the absolute file path as a string, normalized
  3360. * to using front slashes for path separators.
  3361. * @param {java.io.File||String} file
  3362. */
  3363. absPath: function (fileObj) {
  3364. if (typeof fileObj === "string") {
  3365. fileObj = xpfile(fileObj);
  3366. }
  3367. return fileObj.path;
  3368. },
  3369. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) {
  3370. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3371. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3372. //and it will be treated as the "include" case.
  3373. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3374. //is set to another value.
  3375. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3376. fileObj, filePath, ok, dirFiles;
  3377. topDir = startDir;
  3378. if (!startDirIsObject) {
  3379. topDir = xpfile(startDir);
  3380. }
  3381. regExpInclude = regExpFilters.include || regExpFilters;
  3382. regExpExclude = regExpFilters.exclude || null;
  3383. if (topDir.exists()) {
  3384. dirFileArray = topDir.directoryEntries;
  3385. while (dirFileArray.hasMoreElements()) {
  3386. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3387. if (fileObj.isFile()) {
  3388. filePath = fileObj.path;
  3389. if (makeUnixPaths) {
  3390. if (filePath.indexOf("/") === -1) {
  3391. filePath = filePath.replace(/\\/g, "/");
  3392. }
  3393. }
  3394. ok = true;
  3395. if (regExpInclude) {
  3396. ok = filePath.match(regExpInclude);
  3397. }
  3398. if (ok && regExpExclude) {
  3399. ok = !filePath.match(regExpExclude);
  3400. }
  3401. if (ok && (!file.exclusionRegExp ||
  3402. !file.exclusionRegExp.test(fileObj.leafName))) {
  3403. files.push(filePath);
  3404. }
  3405. } else if (fileObj.isDirectory() &&
  3406. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) {
  3407. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3408. files.push.apply(files, dirFiles);
  3409. }
  3410. }
  3411. }
  3412. return files; //Array
  3413. },
  3414. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3415. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3416. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3417. regExpFilter = regExpFilter || /\w/;
  3418. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3419. copiedFiles = [], i, srcFileName, destFileName;
  3420. for (i = 0; i < fileNames.length; i += 1) {
  3421. srcFileName = fileNames[i];
  3422. destFileName = srcFileName.replace(srcDir, destDir);
  3423. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3424. copiedFiles.push(destFileName);
  3425. }
  3426. }
  3427. return copiedFiles.length ? copiedFiles : null; //Array or null
  3428. },
  3429. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3430. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3431. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3432. var destFile = xpfile(destFileName),
  3433. srcFile = xpfile(srcFileName);
  3434. //logger.trace("Src filename: " + srcFileName);
  3435. //logger.trace("Dest filename: " + destFileName);
  3436. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3437. //than dest.
  3438. if (onlyCopyNew) {
  3439. if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) {
  3440. return false; //Boolean
  3441. }
  3442. }
  3443. srcFile.copyTo(destFile.parent, destFile.leafName);
  3444. return true; //Boolean
  3445. },
  3446. /**
  3447. * Renames a file. May fail if "to" already exists or is on another drive.
  3448. */
  3449. renameFile: function (from, to) {
  3450. var toFile = xpfile(to);
  3451. return xpfile(from).moveTo(toFile.parent, toFile.leafName);
  3452. },
  3453. readFile: xpcUtil.readFile,
  3454. readFileAsync: function (path, encoding) {
  3455. var d = prim();
  3456. try {
  3457. d.resolve(file.readFile(path, encoding));
  3458. } catch (e) {
  3459. d.reject(e);
  3460. }
  3461. return d.promise;
  3462. },
  3463. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3464. //summary: saves a file using UTF-8 encoding.
  3465. file.saveFile(fileName, fileContents, "utf-8");
  3466. },
  3467. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3468. var outStream, convertStream,
  3469. fileObj = xpfile(fileName);
  3470. mkFullDir(fileObj.parent);
  3471. try {
  3472. outStream = Cc['@mozilla.org/network/file-output-stream;1']
  3473. .createInstance(Ci.nsIFileOutputStream);
  3474. //438 is decimal for 0777
  3475. outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0);
  3476. convertStream = Cc['@mozilla.org/intl/converter-output-stream;1']
  3477. .createInstance(Ci.nsIConverterOutputStream);
  3478. convertStream.init(outStream, encoding, 0, 0);
  3479. convertStream.writeString(fileContents);
  3480. } catch (e) {
  3481. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  3482. } finally {
  3483. if (convertStream) {
  3484. convertStream.close();
  3485. }
  3486. if (outStream) {
  3487. outStream.close();
  3488. }
  3489. }
  3490. },
  3491. deleteFile: function (/*String*/fileName) {
  3492. //summary: deletes a file or directory if it exists.
  3493. var fileObj = xpfile(fileName);
  3494. if (fileObj.exists()) {
  3495. fileObj.remove(true);
  3496. }
  3497. },
  3498. /**
  3499. * Deletes any empty directories under the given directory.
  3500. * The startDirIsJavaObject is private to this implementation's
  3501. * recursion needs.
  3502. */
  3503. deleteEmptyDirs: function (startDir, startDirIsObject) {
  3504. var topDir = startDir,
  3505. dirFileArray, fileObj;
  3506. if (!startDirIsObject) {
  3507. topDir = xpfile(startDir);
  3508. }
  3509. if (topDir.exists()) {
  3510. dirFileArray = topDir.directoryEntries;
  3511. while (dirFileArray.hasMoreElements()) {
  3512. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3513. if (fileObj.isDirectory()) {
  3514. file.deleteEmptyDirs(fileObj, true);
  3515. }
  3516. }
  3517. //If the directory is empty now, delete it.
  3518. dirFileArray = topDir.directoryEntries;
  3519. if (!dirFileArray.hasMoreElements()) {
  3520. file.deleteFile(topDir.path);
  3521. }
  3522. }
  3523. }
  3524. };
  3525. return file;
  3526. });
  3527. }
  3528. if(env === 'browser') {
  3529. /*global process */
  3530. define('browser/quit', function () {
  3531. 'use strict';
  3532. return function (code) {
  3533. };
  3534. });
  3535. }
  3536. if(env === 'node') {
  3537. /*global process */
  3538. define('node/quit', function () {
  3539. 'use strict';
  3540. return function (code) {
  3541. return process.exit(code);
  3542. };
  3543. });
  3544. }
  3545. if(env === 'rhino') {
  3546. /*global quit */
  3547. define('rhino/quit', function () {
  3548. 'use strict';
  3549. return function (code) {
  3550. return quit(code);
  3551. };
  3552. });
  3553. }
  3554. if(env === 'xpconnect') {
  3555. /*global quit */
  3556. define('xpconnect/quit', function () {
  3557. 'use strict';
  3558. return function (code) {
  3559. return quit(code);
  3560. };
  3561. });
  3562. }
  3563. if(env === 'browser') {
  3564. /**
  3565. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  3566. * Available via the MIT or new BSD license.
  3567. * see: http://github.com/jrburke/requirejs for details
  3568. */
  3569. /*jslint strict: false */
  3570. /*global define: false, console: false */
  3571. define('browser/print', function () {
  3572. function print(msg) {
  3573. console.log(msg);
  3574. }
  3575. return print;
  3576. });
  3577. }
  3578. if(env === 'node') {
  3579. /**
  3580. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  3581. * Available via the MIT or new BSD license.
  3582. * see: http://github.com/jrburke/requirejs for details
  3583. */
  3584. /*jslint strict: false */
  3585. /*global define: false, console: false */
  3586. define('node/print', function () {
  3587. function print(msg) {
  3588. console.log(msg);
  3589. }
  3590. return print;
  3591. });
  3592. }
  3593. if(env === 'rhino') {
  3594. /**
  3595. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  3596. * Available via the MIT or new BSD license.
  3597. * see: http://github.com/jrburke/requirejs for details
  3598. */
  3599. /*jslint strict: false */
  3600. /*global define: false, print: false */
  3601. define('rhino/print', function () {
  3602. return print;
  3603. });
  3604. }
  3605. if(env === 'xpconnect') {
  3606. /**
  3607. * @license RequireJS Copyright (c) 2013, The Dojo Foundation All Rights Reserved.
  3608. * Available via the MIT or new BSD license.
  3609. * see: http://github.com/jrburke/requirejs for details
  3610. */
  3611. /*jslint strict: false */
  3612. /*global define: false, print: false */
  3613. define('xpconnect/print', function () {
  3614. return print;
  3615. });
  3616. }
  3617. /**
  3618. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  3619. * Available via the MIT or new BSD license.
  3620. * see: http://github.com/jrburke/requirejs for details
  3621. */
  3622. /*jslint nomen: false, strict: false */
  3623. /*global define: false */
  3624. define('logger', ['env!env/print'], function (print) {
  3625. var logger = {
  3626. TRACE: 0,
  3627. INFO: 1,
  3628. WARN: 2,
  3629. ERROR: 3,
  3630. SILENT: 4,
  3631. level: 0,
  3632. logPrefix: "",
  3633. logLevel: function( level ) {
  3634. this.level = level;
  3635. },
  3636. trace: function (message) {
  3637. if (this.level <= this.TRACE) {
  3638. this._print(message);
  3639. }
  3640. },
  3641. info: function (message) {
  3642. if (this.level <= this.INFO) {
  3643. this._print(message);
  3644. }
  3645. },
  3646. warn: function (message) {
  3647. if (this.level <= this.WARN) {
  3648. this._print(message);
  3649. }
  3650. },
  3651. error: function (message) {
  3652. if (this.level <= this.ERROR) {
  3653. this._print(message);
  3654. }
  3655. },
  3656. _print: function (message) {
  3657. this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message);
  3658. },
  3659. _sysPrint: function (message) {
  3660. print(message);
  3661. }
  3662. };
  3663. return logger;
  3664. });
  3665. //Just a blank file to use when building the optimizer with the optimizer,
  3666. //so that the build does not attempt to inline some env modules,
  3667. //like Node's fs and path.
  3668. //Commit 465a4eae86c7bae191b1ee427571543ace777117 on July 19, 2012
  3669. define('esprima', ['exports'], function(exports) {
  3670. /*
  3671. Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  3672. Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
  3673. Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  3674. Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  3675. Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
  3676. Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  3677. Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
  3678. Redistribution and use in source and binary forms, with or without
  3679. modification, are permitted provided that the following conditions are met:
  3680. * Redistributions of source code must retain the above copyright
  3681. notice, this list of conditions and the following disclaimer.
  3682. * Redistributions in binary form must reproduce the above copyright
  3683. notice, this list of conditions and the following disclaimer in the
  3684. documentation and/or other materials provided with the distribution.
  3685. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3686. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3687. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3688. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  3689. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  3690. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  3691. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  3692. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  3693. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  3694. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3695. */
  3696. /*jslint bitwise:true plusplus:true */
  3697. /*global esprima:true, exports:true,
  3698. throwError: true, createLiteral: true, generateStatement: true,
  3699. parseAssignmentExpression: true, parseBlock: true, parseExpression: true,
  3700. parseFunctionDeclaration: true, parseFunctionExpression: true,
  3701. parseFunctionSourceElements: true, parseVariableIdentifier: true,
  3702. parseLeftHandSideExpression: true,
  3703. parseStatement: true, parseSourceElement: true */
  3704. (function (exports) {
  3705. 'use strict';
  3706. var Token,
  3707. TokenName,
  3708. Syntax,
  3709. PropertyKind,
  3710. Messages,
  3711. Regex,
  3712. source,
  3713. strict,
  3714. index,
  3715. lineNumber,
  3716. lineStart,
  3717. length,
  3718. buffer,
  3719. state,
  3720. extra;
  3721. Token = {
  3722. BooleanLiteral: 1,
  3723. EOF: 2,
  3724. Identifier: 3,
  3725. Keyword: 4,
  3726. NullLiteral: 5,
  3727. NumericLiteral: 6,
  3728. Punctuator: 7,
  3729. StringLiteral: 8
  3730. };
  3731. TokenName = {};
  3732. TokenName[Token.BooleanLiteral] = 'Boolean';
  3733. TokenName[Token.EOF] = '<end>';
  3734. TokenName[Token.Identifier] = 'Identifier';
  3735. TokenName[Token.Keyword] = 'Keyword';
  3736. TokenName[Token.NullLiteral] = 'Null';
  3737. TokenName[Token.NumericLiteral] = 'Numeric';
  3738. TokenName[Token.Punctuator] = 'Punctuator';
  3739. TokenName[Token.StringLiteral] = 'String';
  3740. Syntax = {
  3741. AssignmentExpression: 'AssignmentExpression',
  3742. ArrayExpression: 'ArrayExpression',
  3743. BlockStatement: 'BlockStatement',
  3744. BinaryExpression: 'BinaryExpression',
  3745. BreakStatement: 'BreakStatement',
  3746. CallExpression: 'CallExpression',
  3747. CatchClause: 'CatchClause',
  3748. ConditionalExpression: 'ConditionalExpression',
  3749. ContinueStatement: 'ContinueStatement',
  3750. DoWhileStatement: 'DoWhileStatement',
  3751. DebuggerStatement: 'DebuggerStatement',
  3752. EmptyStatement: 'EmptyStatement',
  3753. ExpressionStatement: 'ExpressionStatement',
  3754. ForStatement: 'ForStatement',
  3755. ForInStatement: 'ForInStatement',
  3756. FunctionDeclaration: 'FunctionDeclaration',
  3757. FunctionExpression: 'FunctionExpression',
  3758. Identifier: 'Identifier',
  3759. IfStatement: 'IfStatement',
  3760. Literal: 'Literal',
  3761. LabeledStatement: 'LabeledStatement',
  3762. LogicalExpression: 'LogicalExpression',
  3763. MemberExpression: 'MemberExpression',
  3764. NewExpression: 'NewExpression',
  3765. ObjectExpression: 'ObjectExpression',
  3766. Program: 'Program',
  3767. Property: 'Property',
  3768. ReturnStatement: 'ReturnStatement',
  3769. SequenceExpression: 'SequenceExpression',
  3770. SwitchStatement: 'SwitchStatement',
  3771. SwitchCase: 'SwitchCase',
  3772. ThisExpression: 'ThisExpression',
  3773. ThrowStatement: 'ThrowStatement',
  3774. TryStatement: 'TryStatement',
  3775. UnaryExpression: 'UnaryExpression',
  3776. UpdateExpression: 'UpdateExpression',
  3777. VariableDeclaration: 'VariableDeclaration',
  3778. VariableDeclarator: 'VariableDeclarator',
  3779. WhileStatement: 'WhileStatement',
  3780. WithStatement: 'WithStatement'
  3781. };
  3782. PropertyKind = {
  3783. Data: 1,
  3784. Get: 2,
  3785. Set: 4
  3786. };
  3787. // Error messages should be identical to V8.
  3788. Messages = {
  3789. UnexpectedToken: 'Unexpected token %0',
  3790. UnexpectedNumber: 'Unexpected number',
  3791. UnexpectedString: 'Unexpected string',
  3792. UnexpectedIdentifier: 'Unexpected identifier',
  3793. UnexpectedReserved: 'Unexpected reserved word',
  3794. UnexpectedEOS: 'Unexpected end of input',
  3795. NewlineAfterThrow: 'Illegal newline after throw',
  3796. InvalidRegExp: 'Invalid regular expression',
  3797. UnterminatedRegExp: 'Invalid regular expression: missing /',
  3798. InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  3799. InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  3800. NoCatchOrFinally: 'Missing catch or finally after try',
  3801. UnknownLabel: 'Undefined label \'%0\'',
  3802. Redeclaration: '%0 \'%1\' has already been declared',
  3803. IllegalContinue: 'Illegal continue statement',
  3804. IllegalBreak: 'Illegal break statement',
  3805. IllegalReturn: 'Illegal return statement',
  3806. StrictModeWith: 'Strict mode code may not include a with statement',
  3807. StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  3808. StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  3809. StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  3810. StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  3811. StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  3812. StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  3813. StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  3814. StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
  3815. AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
  3816. AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
  3817. StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  3818. StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  3819. StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  3820. StrictReservedWord: 'Use of future reserved word in strict mode'
  3821. };
  3822. // See also tools/generate-unicode-regex.py.
  3823. Regex = {
  3824. NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
  3825. NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')
  3826. };
  3827. // Ensure the condition is true, otherwise throw an error.
  3828. // This is only to have a better contract semantic, i.e. another safety net
  3829. // to catch a logic error. The condition shall be fulfilled in normal case.
  3830. // Do NOT use this to enforce a certain condition on any user input.
  3831. function assert(condition, message) {
  3832. if (!condition) {
  3833. throw new Error('ASSERT: ' + message);
  3834. }
  3835. }
  3836. function sliceSource(from, to) {
  3837. return source.slice(from, to);
  3838. }
  3839. if (typeof 'esprima'[0] === 'undefined') {
  3840. sliceSource = function sliceArraySource(from, to) {
  3841. return source.slice(from, to).join('');
  3842. };
  3843. }
  3844. function isDecimalDigit(ch) {
  3845. return '0123456789'.indexOf(ch) >= 0;
  3846. }
  3847. function isHexDigit(ch) {
  3848. return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
  3849. }
  3850. function isOctalDigit(ch) {
  3851. return '01234567'.indexOf(ch) >= 0;
  3852. }
  3853. // 7.2 White Space
  3854. function isWhiteSpace(ch) {
  3855. return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') ||
  3856. (ch === '\u000C') || (ch === '\u00A0') ||
  3857. (ch.charCodeAt(0) >= 0x1680 &&
  3858. '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0);
  3859. }
  3860. // 7.3 Line Terminators
  3861. function isLineTerminator(ch) {
  3862. return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
  3863. }
  3864. // 7.6 Identifier Names and Identifiers
  3865. function isIdentifierStart(ch) {
  3866. return (ch === '$') || (ch === '_') || (ch === '\\') ||
  3867. (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
  3868. ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch));
  3869. }
  3870. function isIdentifierPart(ch) {
  3871. return (ch === '$') || (ch === '_') || (ch === '\\') ||
  3872. (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
  3873. ((ch >= '0') && (ch <= '9')) ||
  3874. ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch));
  3875. }
  3876. // 7.6.1.2 Future Reserved Words
  3877. function isFutureReservedWord(id) {
  3878. switch (id) {
  3879. // Future reserved words.
  3880. case 'class':
  3881. case 'enum':
  3882. case 'export':
  3883. case 'extends':
  3884. case 'import':
  3885. case 'super':
  3886. return true;
  3887. }
  3888. return false;
  3889. }
  3890. function isStrictModeReservedWord(id) {
  3891. switch (id) {
  3892. // Strict Mode reserved words.
  3893. case 'implements':
  3894. case 'interface':
  3895. case 'package':
  3896. case 'private':
  3897. case 'protected':
  3898. case 'public':
  3899. case 'static':
  3900. case 'yield':
  3901. case 'let':
  3902. return true;
  3903. }
  3904. return false;
  3905. }
  3906. function isRestrictedWord(id) {
  3907. return id === 'eval' || id === 'arguments';
  3908. }
  3909. // 7.6.1.1 Keywords
  3910. function isKeyword(id) {
  3911. var keyword = false;
  3912. switch (id.length) {
  3913. case 2:
  3914. keyword = (id === 'if') || (id === 'in') || (id === 'do');
  3915. break;
  3916. case 3:
  3917. keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
  3918. break;
  3919. case 4:
  3920. keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with');
  3921. break;
  3922. case 5:
  3923. keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw');
  3924. break;
  3925. case 6:
  3926. keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch');
  3927. break;
  3928. case 7:
  3929. keyword = (id === 'default') || (id === 'finally');
  3930. break;
  3931. case 8:
  3932. keyword = (id === 'function') || (id === 'continue') || (id === 'debugger');
  3933. break;
  3934. case 10:
  3935. keyword = (id === 'instanceof');
  3936. break;
  3937. }
  3938. if (keyword) {
  3939. return true;
  3940. }
  3941. switch (id) {
  3942. // Future reserved words.
  3943. // 'const' is specialized as Keyword in V8.
  3944. case 'const':
  3945. return true;
  3946. // For compatiblity to SpiderMonkey and ES.next
  3947. case 'yield':
  3948. case 'let':
  3949. return true;
  3950. }
  3951. if (strict && isStrictModeReservedWord(id)) {
  3952. return true;
  3953. }
  3954. return isFutureReservedWord(id);
  3955. }
  3956. // Return the next character and move forward.
  3957. function nextChar() {
  3958. return source[index++];
  3959. }
  3960. // 7.4 Comments
  3961. function skipComment() {
  3962. var ch, blockComment, lineComment;
  3963. blockComment = false;
  3964. lineComment = false;
  3965. while (index < length) {
  3966. ch = source[index];
  3967. if (lineComment) {
  3968. ch = nextChar();
  3969. if (isLineTerminator(ch)) {
  3970. lineComment = false;
  3971. if (ch === '\r' && source[index] === '\n') {
  3972. ++index;
  3973. }
  3974. ++lineNumber;
  3975. lineStart = index;
  3976. }
  3977. } else if (blockComment) {
  3978. if (isLineTerminator(ch)) {
  3979. if (ch === '\r' && source[index + 1] === '\n') {
  3980. ++index;
  3981. }
  3982. ++lineNumber;
  3983. ++index;
  3984. lineStart = index;
  3985. if (index >= length) {
  3986. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  3987. }
  3988. } else {
  3989. ch = nextChar();
  3990. if (index >= length) {
  3991. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  3992. }
  3993. if (ch === '*') {
  3994. ch = source[index];
  3995. if (ch === '/') {
  3996. ++index;
  3997. blockComment = false;
  3998. }
  3999. }
  4000. }
  4001. } else if (ch === '/') {
  4002. ch = source[index + 1];
  4003. if (ch === '/') {
  4004. index += 2;
  4005. lineComment = true;
  4006. } else if (ch === '*') {
  4007. index += 2;
  4008. blockComment = true;
  4009. if (index >= length) {
  4010. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4011. }
  4012. } else {
  4013. break;
  4014. }
  4015. } else if (isWhiteSpace(ch)) {
  4016. ++index;
  4017. } else if (isLineTerminator(ch)) {
  4018. ++index;
  4019. if (ch === '\r' && source[index] === '\n') {
  4020. ++index;
  4021. }
  4022. ++lineNumber;
  4023. lineStart = index;
  4024. } else {
  4025. break;
  4026. }
  4027. }
  4028. }
  4029. function scanHexEscape(prefix) {
  4030. var i, len, ch, code = 0;
  4031. len = (prefix === 'u') ? 4 : 2;
  4032. for (i = 0; i < len; ++i) {
  4033. if (index < length && isHexDigit(source[index])) {
  4034. ch = nextChar();
  4035. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  4036. } else {
  4037. return '';
  4038. }
  4039. }
  4040. return String.fromCharCode(code);
  4041. }
  4042. function scanIdentifier() {
  4043. var ch, start, id, restore;
  4044. ch = source[index];
  4045. if (!isIdentifierStart(ch)) {
  4046. return;
  4047. }
  4048. start = index;
  4049. if (ch === '\\') {
  4050. ++index;
  4051. if (source[index] !== 'u') {
  4052. return;
  4053. }
  4054. ++index;
  4055. restore = index;
  4056. ch = scanHexEscape('u');
  4057. if (ch) {
  4058. if (ch === '\\' || !isIdentifierStart(ch)) {
  4059. return;
  4060. }
  4061. id = ch;
  4062. } else {
  4063. index = restore;
  4064. id = 'u';
  4065. }
  4066. } else {
  4067. id = nextChar();
  4068. }
  4069. while (index < length) {
  4070. ch = source[index];
  4071. if (!isIdentifierPart(ch)) {
  4072. break;
  4073. }
  4074. if (ch === '\\') {
  4075. ++index;
  4076. if (source[index] !== 'u') {
  4077. return;
  4078. }
  4079. ++index;
  4080. restore = index;
  4081. ch = scanHexEscape('u');
  4082. if (ch) {
  4083. if (ch === '\\' || !isIdentifierPart(ch)) {
  4084. return;
  4085. }
  4086. id += ch;
  4087. } else {
  4088. index = restore;
  4089. id += 'u';
  4090. }
  4091. } else {
  4092. id += nextChar();
  4093. }
  4094. }
  4095. // There is no keyword or literal with only one character.
  4096. // Thus, it must be an identifier.
  4097. if (id.length === 1) {
  4098. return {
  4099. type: Token.Identifier,
  4100. value: id,
  4101. lineNumber: lineNumber,
  4102. lineStart: lineStart,
  4103. range: [start, index]
  4104. };
  4105. }
  4106. if (isKeyword(id)) {
  4107. return {
  4108. type: Token.Keyword,
  4109. value: id,
  4110. lineNumber: lineNumber,
  4111. lineStart: lineStart,
  4112. range: [start, index]
  4113. };
  4114. }
  4115. // 7.8.1 Null Literals
  4116. if (id === 'null') {
  4117. return {
  4118. type: Token.NullLiteral,
  4119. value: id,
  4120. lineNumber: lineNumber,
  4121. lineStart: lineStart,
  4122. range: [start, index]
  4123. };
  4124. }
  4125. // 7.8.2 Boolean Literals
  4126. if (id === 'true' || id === 'false') {
  4127. return {
  4128. type: Token.BooleanLiteral,
  4129. value: id,
  4130. lineNumber: lineNumber,
  4131. lineStart: lineStart,
  4132. range: [start, index]
  4133. };
  4134. }
  4135. return {
  4136. type: Token.Identifier,
  4137. value: id,
  4138. lineNumber: lineNumber,
  4139. lineStart: lineStart,
  4140. range: [start, index]
  4141. };
  4142. }
  4143. // 7.7 Punctuators
  4144. function scanPunctuator() {
  4145. var start = index,
  4146. ch1 = source[index],
  4147. ch2,
  4148. ch3,
  4149. ch4;
  4150. // Check for most common single-character punctuators.
  4151. if (ch1 === ';' || ch1 === '{' || ch1 === '}') {
  4152. ++index;
  4153. return {
  4154. type: Token.Punctuator,
  4155. value: ch1,
  4156. lineNumber: lineNumber,
  4157. lineStart: lineStart,
  4158. range: [start, index]
  4159. };
  4160. }
  4161. if (ch1 === ',' || ch1 === '(' || ch1 === ')') {
  4162. ++index;
  4163. return {
  4164. type: Token.Punctuator,
  4165. value: ch1,
  4166. lineNumber: lineNumber,
  4167. lineStart: lineStart,
  4168. range: [start, index]
  4169. };
  4170. }
  4171. // Dot (.) can also start a floating-point number, hence the need
  4172. // to check the next character.
  4173. ch2 = source[index + 1];
  4174. if (ch1 === '.' && !isDecimalDigit(ch2)) {
  4175. return {
  4176. type: Token.Punctuator,
  4177. value: nextChar(),
  4178. lineNumber: lineNumber,
  4179. lineStart: lineStart,
  4180. range: [start, index]
  4181. };
  4182. }
  4183. // Peek more characters.
  4184. ch3 = source[index + 2];
  4185. ch4 = source[index + 3];
  4186. // 4-character punctuator: >>>=
  4187. if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
  4188. if (ch4 === '=') {
  4189. index += 4;
  4190. return {
  4191. type: Token.Punctuator,
  4192. value: '>>>=',
  4193. lineNumber: lineNumber,
  4194. lineStart: lineStart,
  4195. range: [start, index]
  4196. };
  4197. }
  4198. }
  4199. // 3-character punctuators: === !== >>> <<= >>=
  4200. if (ch1 === '=' && ch2 === '=' && ch3 === '=') {
  4201. index += 3;
  4202. return {
  4203. type: Token.Punctuator,
  4204. value: '===',
  4205. lineNumber: lineNumber,
  4206. lineStart: lineStart,
  4207. range: [start, index]
  4208. };
  4209. }
  4210. if (ch1 === '!' && ch2 === '=' && ch3 === '=') {
  4211. index += 3;
  4212. return {
  4213. type: Token.Punctuator,
  4214. value: '!==',
  4215. lineNumber: lineNumber,
  4216. lineStart: lineStart,
  4217. range: [start, index]
  4218. };
  4219. }
  4220. if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
  4221. index += 3;
  4222. return {
  4223. type: Token.Punctuator,
  4224. value: '>>>',
  4225. lineNumber: lineNumber,
  4226. lineStart: lineStart,
  4227. range: [start, index]
  4228. };
  4229. }
  4230. if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
  4231. index += 3;
  4232. return {
  4233. type: Token.Punctuator,
  4234. value: '<<=',
  4235. lineNumber: lineNumber,
  4236. lineStart: lineStart,
  4237. range: [start, index]
  4238. };
  4239. }
  4240. if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
  4241. index += 3;
  4242. return {
  4243. type: Token.Punctuator,
  4244. value: '>>=',
  4245. lineNumber: lineNumber,
  4246. lineStart: lineStart,
  4247. range: [start, index]
  4248. };
  4249. }
  4250. // 2-character punctuators: <= >= == != ++ -- << >> && ||
  4251. // += -= *= %= &= |= ^= /=
  4252. if (ch2 === '=') {
  4253. if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
  4254. index += 2;
  4255. return {
  4256. type: Token.Punctuator,
  4257. value: ch1 + ch2,
  4258. lineNumber: lineNumber,
  4259. lineStart: lineStart,
  4260. range: [start, index]
  4261. };
  4262. }
  4263. }
  4264. if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) {
  4265. if ('+-<>&|'.indexOf(ch2) >= 0) {
  4266. index += 2;
  4267. return {
  4268. type: Token.Punctuator,
  4269. value: ch1 + ch2,
  4270. lineNumber: lineNumber,
  4271. lineStart: lineStart,
  4272. range: [start, index]
  4273. };
  4274. }
  4275. }
  4276. // The remaining 1-character punctuators.
  4277. if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) {
  4278. return {
  4279. type: Token.Punctuator,
  4280. value: nextChar(),
  4281. lineNumber: lineNumber,
  4282. lineStart: lineStart,
  4283. range: [start, index]
  4284. };
  4285. }
  4286. }
  4287. // 7.8.3 Numeric Literals
  4288. function scanNumericLiteral() {
  4289. var number, start, ch;
  4290. ch = source[index];
  4291. assert(isDecimalDigit(ch) || (ch === '.'),
  4292. 'Numeric literal must start with a decimal digit or a decimal point');
  4293. start = index;
  4294. number = '';
  4295. if (ch !== '.') {
  4296. number = nextChar();
  4297. ch = source[index];
  4298. // Hex number starts with '0x'.
  4299. // Octal number starts with '0'.
  4300. if (number === '0') {
  4301. if (ch === 'x' || ch === 'X') {
  4302. number += nextChar();
  4303. while (index < length) {
  4304. ch = source[index];
  4305. if (!isHexDigit(ch)) {
  4306. break;
  4307. }
  4308. number += nextChar();
  4309. }
  4310. if (number.length <= 2) {
  4311. // only 0x
  4312. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4313. }
  4314. if (index < length) {
  4315. ch = source[index];
  4316. if (isIdentifierStart(ch)) {
  4317. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4318. }
  4319. }
  4320. return {
  4321. type: Token.NumericLiteral,
  4322. value: parseInt(number, 16),
  4323. lineNumber: lineNumber,
  4324. lineStart: lineStart,
  4325. range: [start, index]
  4326. };
  4327. } else if (isOctalDigit(ch)) {
  4328. number += nextChar();
  4329. while (index < length) {
  4330. ch = source[index];
  4331. if (!isOctalDigit(ch)) {
  4332. break;
  4333. }
  4334. number += nextChar();
  4335. }
  4336. if (index < length) {
  4337. ch = source[index];
  4338. if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
  4339. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4340. }
  4341. }
  4342. return {
  4343. type: Token.NumericLiteral,
  4344. value: parseInt(number, 8),
  4345. octal: true,
  4346. lineNumber: lineNumber,
  4347. lineStart: lineStart,
  4348. range: [start, index]
  4349. };
  4350. }
  4351. // decimal number starts with '0' such as '09' is illegal.
  4352. if (isDecimalDigit(ch)) {
  4353. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4354. }
  4355. }
  4356. while (index < length) {
  4357. ch = source[index];
  4358. if (!isDecimalDigit(ch)) {
  4359. break;
  4360. }
  4361. number += nextChar();
  4362. }
  4363. }
  4364. if (ch === '.') {
  4365. number += nextChar();
  4366. while (index < length) {
  4367. ch = source[index];
  4368. if (!isDecimalDigit(ch)) {
  4369. break;
  4370. }
  4371. number += nextChar();
  4372. }
  4373. }
  4374. if (ch === 'e' || ch === 'E') {
  4375. number += nextChar();
  4376. ch = source[index];
  4377. if (ch === '+' || ch === '-') {
  4378. number += nextChar();
  4379. }
  4380. ch = source[index];
  4381. if (isDecimalDigit(ch)) {
  4382. number += nextChar();
  4383. while (index < length) {
  4384. ch = source[index];
  4385. if (!isDecimalDigit(ch)) {
  4386. break;
  4387. }
  4388. number += nextChar();
  4389. }
  4390. } else {
  4391. ch = 'character ' + ch;
  4392. if (index >= length) {
  4393. ch = '<end>';
  4394. }
  4395. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4396. }
  4397. }
  4398. if (index < length) {
  4399. ch = source[index];
  4400. if (isIdentifierStart(ch)) {
  4401. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4402. }
  4403. }
  4404. return {
  4405. type: Token.NumericLiteral,
  4406. value: parseFloat(number),
  4407. lineNumber: lineNumber,
  4408. lineStart: lineStart,
  4409. range: [start, index]
  4410. };
  4411. }
  4412. // 7.8.4 String Literals
  4413. function scanStringLiteral() {
  4414. var str = '', quote, start, ch, code, unescaped, restore, octal = false;
  4415. quote = source[index];
  4416. assert((quote === '\'' || quote === '"'),
  4417. 'String literal must starts with a quote');
  4418. start = index;
  4419. ++index;
  4420. while (index < length) {
  4421. ch = nextChar();
  4422. if (ch === quote) {
  4423. quote = '';
  4424. break;
  4425. } else if (ch === '\\') {
  4426. ch = nextChar();
  4427. if (!isLineTerminator(ch)) {
  4428. switch (ch) {
  4429. case 'n':
  4430. str += '\n';
  4431. break;
  4432. case 'r':
  4433. str += '\r';
  4434. break;
  4435. case 't':
  4436. str += '\t';
  4437. break;
  4438. case 'u':
  4439. case 'x':
  4440. restore = index;
  4441. unescaped = scanHexEscape(ch);
  4442. if (unescaped) {
  4443. str += unescaped;
  4444. } else {
  4445. index = restore;
  4446. str += ch;
  4447. }
  4448. break;
  4449. case 'b':
  4450. str += '\b';
  4451. break;
  4452. case 'f':
  4453. str += '\f';
  4454. break;
  4455. case 'v':
  4456. str += '\v';
  4457. break;
  4458. default:
  4459. if (isOctalDigit(ch)) {
  4460. code = '01234567'.indexOf(ch);
  4461. // \0 is not octal escape sequence
  4462. if (code !== 0) {
  4463. octal = true;
  4464. }
  4465. if (index < length && isOctalDigit(source[index])) {
  4466. octal = true;
  4467. code = code * 8 + '01234567'.indexOf(nextChar());
  4468. // 3 digits are only allowed when string starts
  4469. // with 0, 1, 2, 3
  4470. if ('0123'.indexOf(ch) >= 0 &&
  4471. index < length &&
  4472. isOctalDigit(source[index])) {
  4473. code = code * 8 + '01234567'.indexOf(nextChar());
  4474. }
  4475. }
  4476. str += String.fromCharCode(code);
  4477. } else {
  4478. str += ch;
  4479. }
  4480. break;
  4481. }
  4482. } else {
  4483. ++lineNumber;
  4484. if (ch === '\r' && source[index] === '\n') {
  4485. ++index;
  4486. }
  4487. }
  4488. } else if (isLineTerminator(ch)) {
  4489. break;
  4490. } else {
  4491. str += ch;
  4492. }
  4493. }
  4494. if (quote !== '') {
  4495. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4496. }
  4497. return {
  4498. type: Token.StringLiteral,
  4499. value: str,
  4500. octal: octal,
  4501. lineNumber: lineNumber,
  4502. lineStart: lineStart,
  4503. range: [start, index]
  4504. };
  4505. }
  4506. function scanRegExp() {
  4507. var str = '', ch, start, pattern, flags, value, classMarker = false, restore;
  4508. buffer = null;
  4509. skipComment();
  4510. start = index;
  4511. ch = source[index];
  4512. assert(ch === '/', 'Regular expression literal must start with a slash');
  4513. str = nextChar();
  4514. while (index < length) {
  4515. ch = nextChar();
  4516. str += ch;
  4517. if (classMarker) {
  4518. if (ch === ']') {
  4519. classMarker = false;
  4520. }
  4521. } else {
  4522. if (ch === '\\') {
  4523. ch = nextChar();
  4524. // ECMA-262 7.8.5
  4525. if (isLineTerminator(ch)) {
  4526. throwError({}, Messages.UnterminatedRegExp);
  4527. }
  4528. str += ch;
  4529. } else if (ch === '/') {
  4530. break;
  4531. } else if (ch === '[') {
  4532. classMarker = true;
  4533. } else if (isLineTerminator(ch)) {
  4534. throwError({}, Messages.UnterminatedRegExp);
  4535. }
  4536. }
  4537. }
  4538. if (str.length === 1) {
  4539. throwError({}, Messages.UnterminatedRegExp);
  4540. }
  4541. // Exclude leading and trailing slash.
  4542. pattern = str.substr(1, str.length - 2);
  4543. flags = '';
  4544. while (index < length) {
  4545. ch = source[index];
  4546. if (!isIdentifierPart(ch)) {
  4547. break;
  4548. }
  4549. ++index;
  4550. if (ch === '\\' && index < length) {
  4551. ch = source[index];
  4552. if (ch === 'u') {
  4553. ++index;
  4554. restore = index;
  4555. ch = scanHexEscape('u');
  4556. if (ch) {
  4557. flags += ch;
  4558. str += '\\u';
  4559. for (; restore < index; ++restore) {
  4560. str += source[restore];
  4561. }
  4562. } else {
  4563. index = restore;
  4564. flags += 'u';
  4565. str += '\\u';
  4566. }
  4567. } else {
  4568. str += '\\';
  4569. }
  4570. } else {
  4571. flags += ch;
  4572. str += ch;
  4573. }
  4574. }
  4575. try {
  4576. value = new RegExp(pattern, flags);
  4577. } catch (e) {
  4578. throwError({}, Messages.InvalidRegExp);
  4579. }
  4580. return {
  4581. literal: str,
  4582. value: value,
  4583. range: [start, index]
  4584. };
  4585. }
  4586. function isIdentifierName(token) {
  4587. return token.type === Token.Identifier ||
  4588. token.type === Token.Keyword ||
  4589. token.type === Token.BooleanLiteral ||
  4590. token.type === Token.NullLiteral;
  4591. }
  4592. function advance() {
  4593. var ch, token;
  4594. skipComment();
  4595. if (index >= length) {
  4596. return {
  4597. type: Token.EOF,
  4598. lineNumber: lineNumber,
  4599. lineStart: lineStart,
  4600. range: [index, index]
  4601. };
  4602. }
  4603. token = scanPunctuator();
  4604. if (typeof token !== 'undefined') {
  4605. return token;
  4606. }
  4607. ch = source[index];
  4608. if (ch === '\'' || ch === '"') {
  4609. return scanStringLiteral();
  4610. }
  4611. if (ch === '.' || isDecimalDigit(ch)) {
  4612. return scanNumericLiteral();
  4613. }
  4614. token = scanIdentifier();
  4615. if (typeof token !== 'undefined') {
  4616. return token;
  4617. }
  4618. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  4619. }
  4620. function lex() {
  4621. var token;
  4622. if (buffer) {
  4623. index = buffer.range[1];
  4624. lineNumber = buffer.lineNumber;
  4625. lineStart = buffer.lineStart;
  4626. token = buffer;
  4627. buffer = null;
  4628. return token;
  4629. }
  4630. buffer = null;
  4631. return advance();
  4632. }
  4633. function lookahead() {
  4634. var pos, line, start;
  4635. if (buffer !== null) {
  4636. return buffer;
  4637. }
  4638. pos = index;
  4639. line = lineNumber;
  4640. start = lineStart;
  4641. buffer = advance();
  4642. index = pos;
  4643. lineNumber = line;
  4644. lineStart = start;
  4645. return buffer;
  4646. }
  4647. // Return true if there is a line terminator before the next token.
  4648. function peekLineTerminator() {
  4649. var pos, line, start, found;
  4650. pos = index;
  4651. line = lineNumber;
  4652. start = lineStart;
  4653. skipComment();
  4654. found = lineNumber !== line;
  4655. index = pos;
  4656. lineNumber = line;
  4657. lineStart = start;
  4658. return found;
  4659. }
  4660. // Throw an exception
  4661. function throwError(token, messageFormat) {
  4662. var error,
  4663. args = Array.prototype.slice.call(arguments, 2),
  4664. msg = messageFormat.replace(
  4665. /%(\d)/g,
  4666. function (whole, index) {
  4667. return args[index] || '';
  4668. }
  4669. );
  4670. if (typeof token.lineNumber === 'number') {
  4671. error = new Error('Line ' + token.lineNumber + ': ' + msg);
  4672. error.index = token.range[0];
  4673. error.lineNumber = token.lineNumber;
  4674. error.column = token.range[0] - lineStart + 1;
  4675. } else {
  4676. error = new Error('Line ' + lineNumber + ': ' + msg);
  4677. error.index = index;
  4678. error.lineNumber = lineNumber;
  4679. error.column = index - lineStart + 1;
  4680. }
  4681. throw error;
  4682. }
  4683. function throwErrorTolerant() {
  4684. var error;
  4685. try {
  4686. throwError.apply(null, arguments);
  4687. } catch (e) {
  4688. if (extra.errors) {
  4689. extra.errors.push(e);
  4690. } else {
  4691. throw e;
  4692. }
  4693. }
  4694. }
  4695. // Throw an exception because of the token.
  4696. function throwUnexpected(token) {
  4697. var s;
  4698. if (token.type === Token.EOF) {
  4699. throwError(token, Messages.UnexpectedEOS);
  4700. }
  4701. if (token.type === Token.NumericLiteral) {
  4702. throwError(token, Messages.UnexpectedNumber);
  4703. }
  4704. if (token.type === Token.StringLiteral) {
  4705. throwError(token, Messages.UnexpectedString);
  4706. }
  4707. if (token.type === Token.Identifier) {
  4708. throwError(token, Messages.UnexpectedIdentifier);
  4709. }
  4710. if (token.type === Token.Keyword) {
  4711. if (isFutureReservedWord(token.value)) {
  4712. throwError(token, Messages.UnexpectedReserved);
  4713. } else if (strict && isStrictModeReservedWord(token.value)) {
  4714. throwError(token, Messages.StrictReservedWord);
  4715. }
  4716. throwError(token, Messages.UnexpectedToken, token.value);
  4717. }
  4718. // BooleanLiteral, NullLiteral, or Punctuator.
  4719. throwError(token, Messages.UnexpectedToken, token.value);
  4720. }
  4721. // Expect the next token to match the specified punctuator.
  4722. // If not, an exception will be thrown.
  4723. function expect(value) {
  4724. var token = lex();
  4725. if (token.type !== Token.Punctuator || token.value !== value) {
  4726. throwUnexpected(token);
  4727. }
  4728. }
  4729. // Expect the next token to match the specified keyword.
  4730. // If not, an exception will be thrown.
  4731. function expectKeyword(keyword) {
  4732. var token = lex();
  4733. if (token.type !== Token.Keyword || token.value !== keyword) {
  4734. throwUnexpected(token);
  4735. }
  4736. }
  4737. // Return true if the next token matches the specified punctuator.
  4738. function match(value) {
  4739. var token = lookahead();
  4740. return token.type === Token.Punctuator && token.value === value;
  4741. }
  4742. // Return true if the next token matches the specified keyword
  4743. function matchKeyword(keyword) {
  4744. var token = lookahead();
  4745. return token.type === Token.Keyword && token.value === keyword;
  4746. }
  4747. // Return true if the next token is an assignment operator
  4748. function matchAssign() {
  4749. var token = lookahead(),
  4750. op = token.value;
  4751. if (token.type !== Token.Punctuator) {
  4752. return false;
  4753. }
  4754. return op === '=' ||
  4755. op === '*=' ||
  4756. op === '/=' ||
  4757. op === '%=' ||
  4758. op === '+=' ||
  4759. op === '-=' ||
  4760. op === '<<=' ||
  4761. op === '>>=' ||
  4762. op === '>>>=' ||
  4763. op === '&=' ||
  4764. op === '^=' ||
  4765. op === '|=';
  4766. }
  4767. function consumeSemicolon() {
  4768. var token, line;
  4769. // Catch the very common case first.
  4770. if (source[index] === ';') {
  4771. lex();
  4772. return;
  4773. }
  4774. line = lineNumber;
  4775. skipComment();
  4776. if (lineNumber !== line) {
  4777. return;
  4778. }
  4779. if (match(';')) {
  4780. lex();
  4781. return;
  4782. }
  4783. token = lookahead();
  4784. if (token.type !== Token.EOF && !match('}')) {
  4785. throwUnexpected(token);
  4786. }
  4787. return;
  4788. }
  4789. // Return true if provided expression is LeftHandSideExpression
  4790. function isLeftHandSide(expr) {
  4791. return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
  4792. }
  4793. // 11.1.4 Array Initialiser
  4794. function parseArrayInitialiser() {
  4795. var elements = [],
  4796. undef;
  4797. expect('[');
  4798. while (!match(']')) {
  4799. if (match(',')) {
  4800. lex();
  4801. elements.push(undef);
  4802. } else {
  4803. elements.push(parseAssignmentExpression());
  4804. if (!match(']')) {
  4805. expect(',');
  4806. }
  4807. }
  4808. }
  4809. expect(']');
  4810. return {
  4811. type: Syntax.ArrayExpression,
  4812. elements: elements
  4813. };
  4814. }
  4815. // 11.1.5 Object Initialiser
  4816. function parsePropertyFunction(param, first) {
  4817. var previousStrict, body;
  4818. previousStrict = strict;
  4819. body = parseFunctionSourceElements();
  4820. if (first && strict && isRestrictedWord(param[0].name)) {
  4821. throwError(first, Messages.StrictParamName);
  4822. }
  4823. strict = previousStrict;
  4824. return {
  4825. type: Syntax.FunctionExpression,
  4826. id: null,
  4827. params: param,
  4828. body: body
  4829. };
  4830. }
  4831. function parseObjectPropertyKey() {
  4832. var token = lex();
  4833. // Note: This function is called only from parseObjectProperty(), where
  4834. // EOF and Punctuator tokens are already filtered out.
  4835. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
  4836. if (strict && token.octal) {
  4837. throwError(token, Messages.StrictOctalLiteral);
  4838. }
  4839. return createLiteral(token);
  4840. }
  4841. return {
  4842. type: Syntax.Identifier,
  4843. name: token.value
  4844. };
  4845. }
  4846. function parseObjectProperty() {
  4847. var token, key, id, param;
  4848. token = lookahead();
  4849. if (token.type === Token.Identifier) {
  4850. id = parseObjectPropertyKey();
  4851. // Property Assignment: Getter and Setter.
  4852. if (token.value === 'get' && !match(':')) {
  4853. key = parseObjectPropertyKey();
  4854. expect('(');
  4855. expect(')');
  4856. return {
  4857. type: Syntax.Property,
  4858. key: key,
  4859. value: parsePropertyFunction([]),
  4860. kind: 'get'
  4861. };
  4862. } else if (token.value === 'set' && !match(':')) {
  4863. key = parseObjectPropertyKey();
  4864. expect('(');
  4865. token = lookahead();
  4866. if (token.type !== Token.Identifier) {
  4867. throwUnexpected(lex());
  4868. }
  4869. param = [ parseVariableIdentifier() ];
  4870. expect(')');
  4871. return {
  4872. type: Syntax.Property,
  4873. key: key,
  4874. value: parsePropertyFunction(param, token),
  4875. kind: 'set'
  4876. };
  4877. } else {
  4878. expect(':');
  4879. return {
  4880. type: Syntax.Property,
  4881. key: id,
  4882. value: parseAssignmentExpression(),
  4883. kind: 'init'
  4884. };
  4885. }
  4886. } else if (token.type === Token.EOF || token.type === Token.Punctuator) {
  4887. throwUnexpected(token);
  4888. } else {
  4889. key = parseObjectPropertyKey();
  4890. expect(':');
  4891. return {
  4892. type: Syntax.Property,
  4893. key: key,
  4894. value: parseAssignmentExpression(),
  4895. kind: 'init'
  4896. };
  4897. }
  4898. }
  4899. function parseObjectInitialiser() {
  4900. var token, properties = [], property, name, kind, map = {}, toString = String;
  4901. expect('{');
  4902. while (!match('}')) {
  4903. property = parseObjectProperty();
  4904. if (property.key.type === Syntax.Identifier) {
  4905. name = property.key.name;
  4906. } else {
  4907. name = toString(property.key.value);
  4908. }
  4909. kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
  4910. if (Object.prototype.hasOwnProperty.call(map, name)) {
  4911. if (map[name] === PropertyKind.Data) {
  4912. if (strict && kind === PropertyKind.Data) {
  4913. throwErrorTolerant({}, Messages.StrictDuplicateProperty);
  4914. } else if (kind !== PropertyKind.Data) {
  4915. throwError({}, Messages.AccessorDataProperty);
  4916. }
  4917. } else {
  4918. if (kind === PropertyKind.Data) {
  4919. throwError({}, Messages.AccessorDataProperty);
  4920. } else if (map[name] & kind) {
  4921. throwError({}, Messages.AccessorGetSet);
  4922. }
  4923. }
  4924. map[name] |= kind;
  4925. } else {
  4926. map[name] = kind;
  4927. }
  4928. properties.push(property);
  4929. if (!match('}')) {
  4930. expect(',');
  4931. }
  4932. }
  4933. expect('}');
  4934. return {
  4935. type: Syntax.ObjectExpression,
  4936. properties: properties
  4937. };
  4938. }
  4939. // 11.1 Primary Expressions
  4940. function parsePrimaryExpression() {
  4941. var expr,
  4942. token = lookahead(),
  4943. type = token.type;
  4944. if (type === Token.Identifier) {
  4945. return {
  4946. type: Syntax.Identifier,
  4947. name: lex().value
  4948. };
  4949. }
  4950. if (type === Token.StringLiteral || type === Token.NumericLiteral) {
  4951. if (strict && token.octal) {
  4952. throwErrorTolerant(token, Messages.StrictOctalLiteral);
  4953. }
  4954. return createLiteral(lex());
  4955. }
  4956. if (type === Token.Keyword) {
  4957. if (matchKeyword('this')) {
  4958. lex();
  4959. return {
  4960. type: Syntax.ThisExpression
  4961. };
  4962. }
  4963. if (matchKeyword('function')) {
  4964. return parseFunctionExpression();
  4965. }
  4966. }
  4967. if (type === Token.BooleanLiteral) {
  4968. lex();
  4969. token.value = (token.value === 'true');
  4970. return createLiteral(token);
  4971. }
  4972. if (type === Token.NullLiteral) {
  4973. lex();
  4974. token.value = null;
  4975. return createLiteral(token);
  4976. }
  4977. if (match('[')) {
  4978. return parseArrayInitialiser();
  4979. }
  4980. if (match('{')) {
  4981. return parseObjectInitialiser();
  4982. }
  4983. if (match('(')) {
  4984. lex();
  4985. state.lastParenthesized = expr = parseExpression();
  4986. expect(')');
  4987. return expr;
  4988. }
  4989. if (match('/') || match('/=')) {
  4990. return createLiteral(scanRegExp());
  4991. }
  4992. return throwUnexpected(lex());
  4993. }
  4994. // 11.2 Left-Hand-Side Expressions
  4995. function parseArguments() {
  4996. var args = [];
  4997. expect('(');
  4998. if (!match(')')) {
  4999. while (index < length) {
  5000. args.push(parseAssignmentExpression());
  5001. if (match(')')) {
  5002. break;
  5003. }
  5004. expect(',');
  5005. }
  5006. }
  5007. expect(')');
  5008. return args;
  5009. }
  5010. function parseNonComputedProperty() {
  5011. var token = lex();
  5012. if (!isIdentifierName(token)) {
  5013. throwUnexpected(token);
  5014. }
  5015. return {
  5016. type: Syntax.Identifier,
  5017. name: token.value
  5018. };
  5019. }
  5020. function parseNonComputedMember(object) {
  5021. return {
  5022. type: Syntax.MemberExpression,
  5023. computed: false,
  5024. object: object,
  5025. property: parseNonComputedProperty()
  5026. };
  5027. }
  5028. function parseComputedMember(object) {
  5029. var property, expr;
  5030. expect('[');
  5031. property = parseExpression();
  5032. expr = {
  5033. type: Syntax.MemberExpression,
  5034. computed: true,
  5035. object: object,
  5036. property: property
  5037. };
  5038. expect(']');
  5039. return expr;
  5040. }
  5041. function parseCallMember(object) {
  5042. return {
  5043. type: Syntax.CallExpression,
  5044. callee: object,
  5045. 'arguments': parseArguments()
  5046. };
  5047. }
  5048. function parseNewExpression() {
  5049. var expr;
  5050. expectKeyword('new');
  5051. expr = {
  5052. type: Syntax.NewExpression,
  5053. callee: parseLeftHandSideExpression(),
  5054. 'arguments': []
  5055. };
  5056. if (match('(')) {
  5057. expr['arguments'] = parseArguments();
  5058. }
  5059. return expr;
  5060. }
  5061. function parseLeftHandSideExpressionAllowCall() {
  5062. var useNew, expr;
  5063. useNew = matchKeyword('new');
  5064. expr = useNew ? parseNewExpression() : parsePrimaryExpression();
  5065. while (index < length) {
  5066. if (match('.')) {
  5067. lex();
  5068. expr = parseNonComputedMember(expr);
  5069. } else if (match('[')) {
  5070. expr = parseComputedMember(expr);
  5071. } else if (match('(')) {
  5072. expr = parseCallMember(expr);
  5073. } else {
  5074. break;
  5075. }
  5076. }
  5077. return expr;
  5078. }
  5079. function parseLeftHandSideExpression() {
  5080. var useNew, expr;
  5081. useNew = matchKeyword('new');
  5082. expr = useNew ? parseNewExpression() : parsePrimaryExpression();
  5083. while (index < length) {
  5084. if (match('.')) {
  5085. lex();
  5086. expr = parseNonComputedMember(expr);
  5087. } else if (match('[')) {
  5088. expr = parseComputedMember(expr);
  5089. } else {
  5090. break;
  5091. }
  5092. }
  5093. return expr;
  5094. }
  5095. // 11.3 Postfix Expressions
  5096. function parsePostfixExpression() {
  5097. var expr = parseLeftHandSideExpressionAllowCall();
  5098. if ((match('++') || match('--')) && !peekLineTerminator()) {
  5099. // 11.3.1, 11.3.2
  5100. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  5101. throwError({}, Messages.StrictLHSPostfix);
  5102. }
  5103. if (!isLeftHandSide(expr)) {
  5104. throwError({}, Messages.InvalidLHSInAssignment);
  5105. }
  5106. expr = {
  5107. type: Syntax.UpdateExpression,
  5108. operator: lex().value,
  5109. argument: expr,
  5110. prefix: false
  5111. };
  5112. }
  5113. return expr;
  5114. }
  5115. // 11.4 Unary Operators
  5116. function parseUnaryExpression() {
  5117. var token, expr;
  5118. if (match('++') || match('--')) {
  5119. token = lex();
  5120. expr = parseUnaryExpression();
  5121. // 11.4.4, 11.4.5
  5122. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  5123. throwError({}, Messages.StrictLHSPrefix);
  5124. }
  5125. if (!isLeftHandSide(expr)) {
  5126. throwError({}, Messages.InvalidLHSInAssignment);
  5127. }
  5128. expr = {
  5129. type: Syntax.UpdateExpression,
  5130. operator: token.value,
  5131. argument: expr,
  5132. prefix: true
  5133. };
  5134. return expr;
  5135. }
  5136. if (match('+') || match('-') || match('~') || match('!')) {
  5137. expr = {
  5138. type: Syntax.UnaryExpression,
  5139. operator: lex().value,
  5140. argument: parseUnaryExpression()
  5141. };
  5142. return expr;
  5143. }
  5144. if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
  5145. expr = {
  5146. type: Syntax.UnaryExpression,
  5147. operator: lex().value,
  5148. argument: parseUnaryExpression()
  5149. };
  5150. if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
  5151. throwErrorTolerant({}, Messages.StrictDelete);
  5152. }
  5153. return expr;
  5154. }
  5155. return parsePostfixExpression();
  5156. }
  5157. // 11.5 Multiplicative Operators
  5158. function parseMultiplicativeExpression() {
  5159. var expr = parseUnaryExpression();
  5160. while (match('*') || match('/') || match('%')) {
  5161. expr = {
  5162. type: Syntax.BinaryExpression,
  5163. operator: lex().value,
  5164. left: expr,
  5165. right: parseUnaryExpression()
  5166. };
  5167. }
  5168. return expr;
  5169. }
  5170. // 11.6 Additive Operators
  5171. function parseAdditiveExpression() {
  5172. var expr = parseMultiplicativeExpression();
  5173. while (match('+') || match('-')) {
  5174. expr = {
  5175. type: Syntax.BinaryExpression,
  5176. operator: lex().value,
  5177. left: expr,
  5178. right: parseMultiplicativeExpression()
  5179. };
  5180. }
  5181. return expr;
  5182. }
  5183. // 11.7 Bitwise Shift Operators
  5184. function parseShiftExpression() {
  5185. var expr = parseAdditiveExpression();
  5186. while (match('<<') || match('>>') || match('>>>')) {
  5187. expr = {
  5188. type: Syntax.BinaryExpression,
  5189. operator: lex().value,
  5190. left: expr,
  5191. right: parseAdditiveExpression()
  5192. };
  5193. }
  5194. return expr;
  5195. }
  5196. // 11.8 Relational Operators
  5197. function parseRelationalExpression() {
  5198. var expr, previousAllowIn;
  5199. previousAllowIn = state.allowIn;
  5200. state.allowIn = true;
  5201. expr = parseShiftExpression();
  5202. while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) {
  5203. expr = {
  5204. type: Syntax.BinaryExpression,
  5205. operator: lex().value,
  5206. left: expr,
  5207. right: parseShiftExpression()
  5208. };
  5209. }
  5210. state.allowIn = previousAllowIn;
  5211. return expr;
  5212. }
  5213. // 11.9 Equality Operators
  5214. function parseEqualityExpression() {
  5215. var expr = parseRelationalExpression();
  5216. while (match('==') || match('!=') || match('===') || match('!==')) {
  5217. expr = {
  5218. type: Syntax.BinaryExpression,
  5219. operator: lex().value,
  5220. left: expr,
  5221. right: parseRelationalExpression()
  5222. };
  5223. }
  5224. return expr;
  5225. }
  5226. // 11.10 Binary Bitwise Operators
  5227. function parseBitwiseANDExpression() {
  5228. var expr = parseEqualityExpression();
  5229. while (match('&')) {
  5230. lex();
  5231. expr = {
  5232. type: Syntax.BinaryExpression,
  5233. operator: '&',
  5234. left: expr,
  5235. right: parseEqualityExpression()
  5236. };
  5237. }
  5238. return expr;
  5239. }
  5240. function parseBitwiseXORExpression() {
  5241. var expr = parseBitwiseANDExpression();
  5242. while (match('^')) {
  5243. lex();
  5244. expr = {
  5245. type: Syntax.BinaryExpression,
  5246. operator: '^',
  5247. left: expr,
  5248. right: parseBitwiseANDExpression()
  5249. };
  5250. }
  5251. return expr;
  5252. }
  5253. function parseBitwiseORExpression() {
  5254. var expr = parseBitwiseXORExpression();
  5255. while (match('|')) {
  5256. lex();
  5257. expr = {
  5258. type: Syntax.BinaryExpression,
  5259. operator: '|',
  5260. left: expr,
  5261. right: parseBitwiseXORExpression()
  5262. };
  5263. }
  5264. return expr;
  5265. }
  5266. // 11.11 Binary Logical Operators
  5267. function parseLogicalANDExpression() {
  5268. var expr = parseBitwiseORExpression();
  5269. while (match('&&')) {
  5270. lex();
  5271. expr = {
  5272. type: Syntax.LogicalExpression,
  5273. operator: '&&',
  5274. left: expr,
  5275. right: parseBitwiseORExpression()
  5276. };
  5277. }
  5278. return expr;
  5279. }
  5280. function parseLogicalORExpression() {
  5281. var expr = parseLogicalANDExpression();
  5282. while (match('||')) {
  5283. lex();
  5284. expr = {
  5285. type: Syntax.LogicalExpression,
  5286. operator: '||',
  5287. left: expr,
  5288. right: parseLogicalANDExpression()
  5289. };
  5290. }
  5291. return expr;
  5292. }
  5293. // 11.12 Conditional Operator
  5294. function parseConditionalExpression() {
  5295. var expr, previousAllowIn, consequent;
  5296. expr = parseLogicalORExpression();
  5297. if (match('?')) {
  5298. lex();
  5299. previousAllowIn = state.allowIn;
  5300. state.allowIn = true;
  5301. consequent = parseAssignmentExpression();
  5302. state.allowIn = previousAllowIn;
  5303. expect(':');
  5304. expr = {
  5305. type: Syntax.ConditionalExpression,
  5306. test: expr,
  5307. consequent: consequent,
  5308. alternate: parseAssignmentExpression()
  5309. };
  5310. }
  5311. return expr;
  5312. }
  5313. // 11.13 Assignment Operators
  5314. function parseAssignmentExpression() {
  5315. var expr;
  5316. expr = parseConditionalExpression();
  5317. if (matchAssign()) {
  5318. // LeftHandSideExpression
  5319. if (!isLeftHandSide(expr)) {
  5320. throwError({}, Messages.InvalidLHSInAssignment);
  5321. }
  5322. // 11.13.1
  5323. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  5324. throwError({}, Messages.StrictLHSAssignment);
  5325. }
  5326. expr = {
  5327. type: Syntax.AssignmentExpression,
  5328. operator: lex().value,
  5329. left: expr,
  5330. right: parseAssignmentExpression()
  5331. };
  5332. }
  5333. return expr;
  5334. }
  5335. // 11.14 Comma Operator
  5336. function parseExpression() {
  5337. var expr = parseAssignmentExpression();
  5338. if (match(',')) {
  5339. expr = {
  5340. type: Syntax.SequenceExpression,
  5341. expressions: [ expr ]
  5342. };
  5343. while (index < length) {
  5344. if (!match(',')) {
  5345. break;
  5346. }
  5347. lex();
  5348. expr.expressions.push(parseAssignmentExpression());
  5349. }
  5350. }
  5351. return expr;
  5352. }
  5353. // 12.1 Block
  5354. function parseStatementList() {
  5355. var list = [],
  5356. statement;
  5357. while (index < length) {
  5358. if (match('}')) {
  5359. break;
  5360. }
  5361. statement = parseSourceElement();
  5362. if (typeof statement === 'undefined') {
  5363. break;
  5364. }
  5365. list.push(statement);
  5366. }
  5367. return list;
  5368. }
  5369. function parseBlock() {
  5370. var block;
  5371. expect('{');
  5372. block = parseStatementList();
  5373. expect('}');
  5374. return {
  5375. type: Syntax.BlockStatement,
  5376. body: block
  5377. };
  5378. }
  5379. // 12.2 Variable Statement
  5380. function parseVariableIdentifier() {
  5381. var token = lex();
  5382. if (token.type !== Token.Identifier) {
  5383. throwUnexpected(token);
  5384. }
  5385. return {
  5386. type: Syntax.Identifier,
  5387. name: token.value
  5388. };
  5389. }
  5390. function parseVariableDeclaration(kind) {
  5391. var id = parseVariableIdentifier(),
  5392. init = null;
  5393. // 12.2.1
  5394. if (strict && isRestrictedWord(id.name)) {
  5395. throwErrorTolerant({}, Messages.StrictVarName);
  5396. }
  5397. if (kind === 'const') {
  5398. expect('=');
  5399. init = parseAssignmentExpression();
  5400. } else if (match('=')) {
  5401. lex();
  5402. init = parseAssignmentExpression();
  5403. }
  5404. return {
  5405. type: Syntax.VariableDeclarator,
  5406. id: id,
  5407. init: init
  5408. };
  5409. }
  5410. function parseVariableDeclarationList(kind) {
  5411. var list = [];
  5412. while (index < length) {
  5413. list.push(parseVariableDeclaration(kind));
  5414. if (!match(',')) {
  5415. break;
  5416. }
  5417. lex();
  5418. }
  5419. return list;
  5420. }
  5421. function parseVariableStatement() {
  5422. var declarations;
  5423. expectKeyword('var');
  5424. declarations = parseVariableDeclarationList();
  5425. consumeSemicolon();
  5426. return {
  5427. type: Syntax.VariableDeclaration,
  5428. declarations: declarations,
  5429. kind: 'var'
  5430. };
  5431. }
  5432. // kind may be `const` or `let`
  5433. // Both are experimental and not in the specification yet.
  5434. // see http://wiki.ecmascript.org/doku.php?id=harmony:const
  5435. // and http://wiki.ecmascript.org/doku.php?id=harmony:let
  5436. function parseConstLetDeclaration(kind) {
  5437. var declarations;
  5438. expectKeyword(kind);
  5439. declarations = parseVariableDeclarationList(kind);
  5440. consumeSemicolon();
  5441. return {
  5442. type: Syntax.VariableDeclaration,
  5443. declarations: declarations,
  5444. kind: kind
  5445. };
  5446. }
  5447. // 12.3 Empty Statement
  5448. function parseEmptyStatement() {
  5449. expect(';');
  5450. return {
  5451. type: Syntax.EmptyStatement
  5452. };
  5453. }
  5454. // 12.4 Expression Statement
  5455. function parseExpressionStatement() {
  5456. var expr = parseExpression();
  5457. consumeSemicolon();
  5458. return {
  5459. type: Syntax.ExpressionStatement,
  5460. expression: expr
  5461. };
  5462. }
  5463. // 12.5 If statement
  5464. function parseIfStatement() {
  5465. var test, consequent, alternate;
  5466. expectKeyword('if');
  5467. expect('(');
  5468. test = parseExpression();
  5469. expect(')');
  5470. consequent = parseStatement();
  5471. if (matchKeyword('else')) {
  5472. lex();
  5473. alternate = parseStatement();
  5474. } else {
  5475. alternate = null;
  5476. }
  5477. return {
  5478. type: Syntax.IfStatement,
  5479. test: test,
  5480. consequent: consequent,
  5481. alternate: alternate
  5482. };
  5483. }
  5484. // 12.6 Iteration Statements
  5485. function parseDoWhileStatement() {
  5486. var body, test, oldInIteration;
  5487. expectKeyword('do');
  5488. oldInIteration = state.inIteration;
  5489. state.inIteration = true;
  5490. body = parseStatement();
  5491. state.inIteration = oldInIteration;
  5492. expectKeyword('while');
  5493. expect('(');
  5494. test = parseExpression();
  5495. expect(')');
  5496. if (match(';')) {
  5497. lex();
  5498. }
  5499. return {
  5500. type: Syntax.DoWhileStatement,
  5501. body: body,
  5502. test: test
  5503. };
  5504. }
  5505. function parseWhileStatement() {
  5506. var test, body, oldInIteration;
  5507. expectKeyword('while');
  5508. expect('(');
  5509. test = parseExpression();
  5510. expect(')');
  5511. oldInIteration = state.inIteration;
  5512. state.inIteration = true;
  5513. body = parseStatement();
  5514. state.inIteration = oldInIteration;
  5515. return {
  5516. type: Syntax.WhileStatement,
  5517. test: test,
  5518. body: body
  5519. };
  5520. }
  5521. function parseForVariableDeclaration() {
  5522. var token = lex();
  5523. return {
  5524. type: Syntax.VariableDeclaration,
  5525. declarations: parseVariableDeclarationList(),
  5526. kind: token.value
  5527. };
  5528. }
  5529. function parseForStatement() {
  5530. var init, test, update, left, right, body, oldInIteration;
  5531. init = test = update = null;
  5532. expectKeyword('for');
  5533. expect('(');
  5534. if (match(';')) {
  5535. lex();
  5536. } else {
  5537. if (matchKeyword('var') || matchKeyword('let')) {
  5538. state.allowIn = false;
  5539. init = parseForVariableDeclaration();
  5540. state.allowIn = true;
  5541. if (init.declarations.length === 1 && matchKeyword('in')) {
  5542. lex();
  5543. left = init;
  5544. right = parseExpression();
  5545. init = null;
  5546. }
  5547. } else {
  5548. state.allowIn = false;
  5549. init = parseExpression();
  5550. state.allowIn = true;
  5551. if (matchKeyword('in')) {
  5552. // LeftHandSideExpression
  5553. if (!isLeftHandSide(init)) {
  5554. throwError({}, Messages.InvalidLHSInForIn);
  5555. }
  5556. lex();
  5557. left = init;
  5558. right = parseExpression();
  5559. init = null;
  5560. }
  5561. }
  5562. if (typeof left === 'undefined') {
  5563. expect(';');
  5564. }
  5565. }
  5566. if (typeof left === 'undefined') {
  5567. if (!match(';')) {
  5568. test = parseExpression();
  5569. }
  5570. expect(';');
  5571. if (!match(')')) {
  5572. update = parseExpression();
  5573. }
  5574. }
  5575. expect(')');
  5576. oldInIteration = state.inIteration;
  5577. state.inIteration = true;
  5578. body = parseStatement();
  5579. state.inIteration = oldInIteration;
  5580. if (typeof left === 'undefined') {
  5581. return {
  5582. type: Syntax.ForStatement,
  5583. init: init,
  5584. test: test,
  5585. update: update,
  5586. body: body
  5587. };
  5588. }
  5589. return {
  5590. type: Syntax.ForInStatement,
  5591. left: left,
  5592. right: right,
  5593. body: body,
  5594. each: false
  5595. };
  5596. }
  5597. // 12.7 The continue statement
  5598. function parseContinueStatement() {
  5599. var token, label = null;
  5600. expectKeyword('continue');
  5601. // Optimize the most common form: 'continue;'.
  5602. if (source[index] === ';') {
  5603. lex();
  5604. if (!state.inIteration) {
  5605. throwError({}, Messages.IllegalContinue);
  5606. }
  5607. return {
  5608. type: Syntax.ContinueStatement,
  5609. label: null
  5610. };
  5611. }
  5612. if (peekLineTerminator()) {
  5613. if (!state.inIteration) {
  5614. throwError({}, Messages.IllegalContinue);
  5615. }
  5616. return {
  5617. type: Syntax.ContinueStatement,
  5618. label: null
  5619. };
  5620. }
  5621. token = lookahead();
  5622. if (token.type === Token.Identifier) {
  5623. label = parseVariableIdentifier();
  5624. if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
  5625. throwError({}, Messages.UnknownLabel, label.name);
  5626. }
  5627. }
  5628. consumeSemicolon();
  5629. if (label === null && !state.inIteration) {
  5630. throwError({}, Messages.IllegalContinue);
  5631. }
  5632. return {
  5633. type: Syntax.ContinueStatement,
  5634. label: label
  5635. };
  5636. }
  5637. // 12.8 The break statement
  5638. function parseBreakStatement() {
  5639. var token, label = null;
  5640. expectKeyword('break');
  5641. // Optimize the most common form: 'break;'.
  5642. if (source[index] === ';') {
  5643. lex();
  5644. if (!(state.inIteration || state.inSwitch)) {
  5645. throwError({}, Messages.IllegalBreak);
  5646. }
  5647. return {
  5648. type: Syntax.BreakStatement,
  5649. label: null
  5650. };
  5651. }
  5652. if (peekLineTerminator()) {
  5653. if (!(state.inIteration || state.inSwitch)) {
  5654. throwError({}, Messages.IllegalBreak);
  5655. }
  5656. return {
  5657. type: Syntax.BreakStatement,
  5658. label: null
  5659. };
  5660. }
  5661. token = lookahead();
  5662. if (token.type === Token.Identifier) {
  5663. label = parseVariableIdentifier();
  5664. if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
  5665. throwError({}, Messages.UnknownLabel, label.name);
  5666. }
  5667. }
  5668. consumeSemicolon();
  5669. if (label === null && !(state.inIteration || state.inSwitch)) {
  5670. throwError({}, Messages.IllegalBreak);
  5671. }
  5672. return {
  5673. type: Syntax.BreakStatement,
  5674. label: label
  5675. };
  5676. }
  5677. // 12.9 The return statement
  5678. function parseReturnStatement() {
  5679. var token, argument = null;
  5680. expectKeyword('return');
  5681. if (!state.inFunctionBody) {
  5682. throwErrorTolerant({}, Messages.IllegalReturn);
  5683. }
  5684. // 'return' followed by a space and an identifier is very common.
  5685. if (source[index] === ' ') {
  5686. if (isIdentifierStart(source[index + 1])) {
  5687. argument = parseExpression();
  5688. consumeSemicolon();
  5689. return {
  5690. type: Syntax.ReturnStatement,
  5691. argument: argument
  5692. };
  5693. }
  5694. }
  5695. if (peekLineTerminator()) {
  5696. return {
  5697. type: Syntax.ReturnStatement,
  5698. argument: null
  5699. };
  5700. }
  5701. if (!match(';')) {
  5702. token = lookahead();
  5703. if (!match('}') && token.type !== Token.EOF) {
  5704. argument = parseExpression();
  5705. }
  5706. }
  5707. consumeSemicolon();
  5708. return {
  5709. type: Syntax.ReturnStatement,
  5710. argument: argument
  5711. };
  5712. }
  5713. // 12.10 The with statement
  5714. function parseWithStatement() {
  5715. var object, body;
  5716. if (strict) {
  5717. throwErrorTolerant({}, Messages.StrictModeWith);
  5718. }
  5719. expectKeyword('with');
  5720. expect('(');
  5721. object = parseExpression();
  5722. expect(')');
  5723. body = parseStatement();
  5724. return {
  5725. type: Syntax.WithStatement,
  5726. object: object,
  5727. body: body
  5728. };
  5729. }
  5730. // 12.10 The swith statement
  5731. function parseSwitchCase() {
  5732. var test,
  5733. consequent = [],
  5734. statement;
  5735. if (matchKeyword('default')) {
  5736. lex();
  5737. test = null;
  5738. } else {
  5739. expectKeyword('case');
  5740. test = parseExpression();
  5741. }
  5742. expect(':');
  5743. while (index < length) {
  5744. if (match('}') || matchKeyword('default') || matchKeyword('case')) {
  5745. break;
  5746. }
  5747. statement = parseStatement();
  5748. if (typeof statement === 'undefined') {
  5749. break;
  5750. }
  5751. consequent.push(statement);
  5752. }
  5753. return {
  5754. type: Syntax.SwitchCase,
  5755. test: test,
  5756. consequent: consequent
  5757. };
  5758. }
  5759. function parseSwitchStatement() {
  5760. var discriminant, cases, oldInSwitch;
  5761. expectKeyword('switch');
  5762. expect('(');
  5763. discriminant = parseExpression();
  5764. expect(')');
  5765. expect('{');
  5766. if (match('}')) {
  5767. lex();
  5768. return {
  5769. type: Syntax.SwitchStatement,
  5770. discriminant: discriminant
  5771. };
  5772. }
  5773. cases = [];
  5774. oldInSwitch = state.inSwitch;
  5775. state.inSwitch = true;
  5776. while (index < length) {
  5777. if (match('}')) {
  5778. break;
  5779. }
  5780. cases.push(parseSwitchCase());
  5781. }
  5782. state.inSwitch = oldInSwitch;
  5783. expect('}');
  5784. return {
  5785. type: Syntax.SwitchStatement,
  5786. discriminant: discriminant,
  5787. cases: cases
  5788. };
  5789. }
  5790. // 12.13 The throw statement
  5791. function parseThrowStatement() {
  5792. var argument;
  5793. expectKeyword('throw');
  5794. if (peekLineTerminator()) {
  5795. throwError({}, Messages.NewlineAfterThrow);
  5796. }
  5797. argument = parseExpression();
  5798. consumeSemicolon();
  5799. return {
  5800. type: Syntax.ThrowStatement,
  5801. argument: argument
  5802. };
  5803. }
  5804. // 12.14 The try statement
  5805. function parseCatchClause() {
  5806. var param;
  5807. expectKeyword('catch');
  5808. expect('(');
  5809. if (!match(')')) {
  5810. param = parseExpression();
  5811. // 12.14.1
  5812. if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
  5813. throwErrorTolerant({}, Messages.StrictCatchVariable);
  5814. }
  5815. }
  5816. expect(')');
  5817. return {
  5818. type: Syntax.CatchClause,
  5819. param: param,
  5820. guard: null,
  5821. body: parseBlock()
  5822. };
  5823. }
  5824. function parseTryStatement() {
  5825. var block, handlers = [], finalizer = null;
  5826. expectKeyword('try');
  5827. block = parseBlock();
  5828. if (matchKeyword('catch')) {
  5829. handlers.push(parseCatchClause());
  5830. }
  5831. if (matchKeyword('finally')) {
  5832. lex();
  5833. finalizer = parseBlock();
  5834. }
  5835. if (handlers.length === 0 && !finalizer) {
  5836. throwError({}, Messages.NoCatchOrFinally);
  5837. }
  5838. return {
  5839. type: Syntax.TryStatement,
  5840. block: block,
  5841. handlers: handlers,
  5842. finalizer: finalizer
  5843. };
  5844. }
  5845. // 12.15 The debugger statement
  5846. function parseDebuggerStatement() {
  5847. expectKeyword('debugger');
  5848. consumeSemicolon();
  5849. return {
  5850. type: Syntax.DebuggerStatement
  5851. };
  5852. }
  5853. // 12 Statements
  5854. function parseStatement() {
  5855. var token = lookahead(),
  5856. expr,
  5857. labeledBody;
  5858. if (token.type === Token.EOF) {
  5859. throwUnexpected(token);
  5860. }
  5861. if (token.type === Token.Punctuator) {
  5862. switch (token.value) {
  5863. case ';':
  5864. return parseEmptyStatement();
  5865. case '{':
  5866. return parseBlock();
  5867. case '(':
  5868. return parseExpressionStatement();
  5869. default:
  5870. break;
  5871. }
  5872. }
  5873. if (token.type === Token.Keyword) {
  5874. switch (token.value) {
  5875. case 'break':
  5876. return parseBreakStatement();
  5877. case 'continue':
  5878. return parseContinueStatement();
  5879. case 'debugger':
  5880. return parseDebuggerStatement();
  5881. case 'do':
  5882. return parseDoWhileStatement();
  5883. case 'for':
  5884. return parseForStatement();
  5885. case 'function':
  5886. return parseFunctionDeclaration();
  5887. case 'if':
  5888. return parseIfStatement();
  5889. case 'return':
  5890. return parseReturnStatement();
  5891. case 'switch':
  5892. return parseSwitchStatement();
  5893. case 'throw':
  5894. return parseThrowStatement();
  5895. case 'try':
  5896. return parseTryStatement();
  5897. case 'var':
  5898. return parseVariableStatement();
  5899. case 'while':
  5900. return parseWhileStatement();
  5901. case 'with':
  5902. return parseWithStatement();
  5903. default:
  5904. break;
  5905. }
  5906. }
  5907. expr = parseExpression();
  5908. // 12.12 Labelled Statements
  5909. if ((expr.type === Syntax.Identifier) && match(':')) {
  5910. lex();
  5911. if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) {
  5912. throwError({}, Messages.Redeclaration, 'Label', expr.name);
  5913. }
  5914. state.labelSet[expr.name] = true;
  5915. labeledBody = parseStatement();
  5916. delete state.labelSet[expr.name];
  5917. return {
  5918. type: Syntax.LabeledStatement,
  5919. label: expr,
  5920. body: labeledBody
  5921. };
  5922. }
  5923. consumeSemicolon();
  5924. return {
  5925. type: Syntax.ExpressionStatement,
  5926. expression: expr
  5927. };
  5928. }
  5929. // 13 Function Definition
  5930. function parseFunctionSourceElements() {
  5931. var sourceElement, sourceElements = [], token, directive, firstRestricted,
  5932. oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody;
  5933. expect('{');
  5934. while (index < length) {
  5935. token = lookahead();
  5936. if (token.type !== Token.StringLiteral) {
  5937. break;
  5938. }
  5939. sourceElement = parseSourceElement();
  5940. sourceElements.push(sourceElement);
  5941. if (sourceElement.expression.type !== Syntax.Literal) {
  5942. // this is not directive
  5943. break;
  5944. }
  5945. directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
  5946. if (directive === 'use strict') {
  5947. strict = true;
  5948. if (firstRestricted) {
  5949. throwError(firstRestricted, Messages.StrictOctalLiteral);
  5950. }
  5951. } else {
  5952. if (!firstRestricted && token.octal) {
  5953. firstRestricted = token;
  5954. }
  5955. }
  5956. }
  5957. oldLabelSet = state.labelSet;
  5958. oldInIteration = state.inIteration;
  5959. oldInSwitch = state.inSwitch;
  5960. oldInFunctionBody = state.inFunctionBody;
  5961. state.labelSet = {};
  5962. state.inIteration = false;
  5963. state.inSwitch = false;
  5964. state.inFunctionBody = true;
  5965. while (index < length) {
  5966. if (match('}')) {
  5967. break;
  5968. }
  5969. sourceElement = parseSourceElement();
  5970. if (typeof sourceElement === 'undefined') {
  5971. break;
  5972. }
  5973. sourceElements.push(sourceElement);
  5974. }
  5975. expect('}');
  5976. state.labelSet = oldLabelSet;
  5977. state.inIteration = oldInIteration;
  5978. state.inSwitch = oldInSwitch;
  5979. state.inFunctionBody = oldInFunctionBody;
  5980. return {
  5981. type: Syntax.BlockStatement,
  5982. body: sourceElements
  5983. };
  5984. }
  5985. function parseFunctionDeclaration() {
  5986. var id, param, params = [], body, token, firstRestricted, message, previousStrict, paramSet;
  5987. expectKeyword('function');
  5988. token = lookahead();
  5989. id = parseVariableIdentifier();
  5990. if (strict) {
  5991. if (isRestrictedWord(token.value)) {
  5992. throwError(token, Messages.StrictFunctionName);
  5993. }
  5994. } else {
  5995. if (isRestrictedWord(token.value)) {
  5996. firstRestricted = token;
  5997. message = Messages.StrictFunctionName;
  5998. } else if (isStrictModeReservedWord(token.value)) {
  5999. firstRestricted = token;
  6000. message = Messages.StrictReservedWord;
  6001. }
  6002. }
  6003. expect('(');
  6004. if (!match(')')) {
  6005. paramSet = {};
  6006. while (index < length) {
  6007. token = lookahead();
  6008. param = parseVariableIdentifier();
  6009. if (strict) {
  6010. if (isRestrictedWord(token.value)) {
  6011. throwError(token, Messages.StrictParamName);
  6012. }
  6013. if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
  6014. throwError(token, Messages.StrictParamDupe);
  6015. }
  6016. } else if (!firstRestricted) {
  6017. if (isRestrictedWord(token.value)) {
  6018. firstRestricted = token;
  6019. message = Messages.StrictParamName;
  6020. } else if (isStrictModeReservedWord(token.value)) {
  6021. firstRestricted = token;
  6022. message = Messages.StrictReservedWord;
  6023. } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
  6024. firstRestricted = token;
  6025. message = Messages.StrictParamDupe;
  6026. }
  6027. }
  6028. params.push(param);
  6029. paramSet[param.name] = true;
  6030. if (match(')')) {
  6031. break;
  6032. }
  6033. expect(',');
  6034. }
  6035. }
  6036. expect(')');
  6037. previousStrict = strict;
  6038. body = parseFunctionSourceElements();
  6039. if (strict && firstRestricted) {
  6040. throwError(firstRestricted, message);
  6041. }
  6042. strict = previousStrict;
  6043. return {
  6044. type: Syntax.FunctionDeclaration,
  6045. id: id,
  6046. params: params,
  6047. body: body
  6048. };
  6049. }
  6050. function parseFunctionExpression() {
  6051. var token, id = null, firstRestricted, message, param, params = [], body, previousStrict, paramSet;
  6052. expectKeyword('function');
  6053. if (!match('(')) {
  6054. token = lookahead();
  6055. id = parseVariableIdentifier();
  6056. if (strict) {
  6057. if (isRestrictedWord(token.value)) {
  6058. throwError(token, Messages.StrictFunctionName);
  6059. }
  6060. } else {
  6061. if (isRestrictedWord(token.value)) {
  6062. firstRestricted = token;
  6063. message = Messages.StrictFunctionName;
  6064. } else if (isStrictModeReservedWord(token.value)) {
  6065. firstRestricted = token;
  6066. message = Messages.StrictReservedWord;
  6067. }
  6068. }
  6069. }
  6070. expect('(');
  6071. if (!match(')')) {
  6072. paramSet = {};
  6073. while (index < length) {
  6074. token = lookahead();
  6075. param = parseVariableIdentifier();
  6076. if (strict) {
  6077. if (isRestrictedWord(token.value)) {
  6078. throwError(token, Messages.StrictParamName);
  6079. }
  6080. if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
  6081. throwError(token, Messages.StrictParamDupe);
  6082. }
  6083. } else if (!firstRestricted) {
  6084. if (isRestrictedWord(token.value)) {
  6085. firstRestricted = token;
  6086. message = Messages.StrictParamName;
  6087. } else if (isStrictModeReservedWord(token.value)) {
  6088. firstRestricted = token;
  6089. message = Messages.StrictReservedWord;
  6090. } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
  6091. firstRestricted = token;
  6092. message = Messages.StrictParamDupe;
  6093. }
  6094. }
  6095. params.push(param);
  6096. paramSet[param.name] = true;
  6097. if (match(')')) {
  6098. break;
  6099. }
  6100. expect(',');
  6101. }
  6102. }
  6103. expect(')');
  6104. previousStrict = strict;
  6105. body = parseFunctionSourceElements();
  6106. if (strict && firstRestricted) {
  6107. throwError(firstRestricted, message);
  6108. }
  6109. strict = previousStrict;
  6110. return {
  6111. type: Syntax.FunctionExpression,
  6112. id: id,
  6113. params: params,
  6114. body: body
  6115. };
  6116. }
  6117. // 14 Program
  6118. function parseSourceElement() {
  6119. var token = lookahead();
  6120. if (token.type === Token.Keyword) {
  6121. switch (token.value) {
  6122. case 'const':
  6123. case 'let':
  6124. return parseConstLetDeclaration(token.value);
  6125. case 'function':
  6126. return parseFunctionDeclaration();
  6127. default:
  6128. return parseStatement();
  6129. }
  6130. }
  6131. if (token.type !== Token.EOF) {
  6132. return parseStatement();
  6133. }
  6134. }
  6135. function parseSourceElements() {
  6136. var sourceElement, sourceElements = [], token, directive, firstRestricted;
  6137. while (index < length) {
  6138. token = lookahead();
  6139. if (token.type !== Token.StringLiteral) {
  6140. break;
  6141. }
  6142. sourceElement = parseSourceElement();
  6143. sourceElements.push(sourceElement);
  6144. if (sourceElement.expression.type !== Syntax.Literal) {
  6145. // this is not directive
  6146. break;
  6147. }
  6148. directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
  6149. if (directive === 'use strict') {
  6150. strict = true;
  6151. if (firstRestricted) {
  6152. throwError(firstRestricted, Messages.StrictOctalLiteral);
  6153. }
  6154. } else {
  6155. if (!firstRestricted && token.octal) {
  6156. firstRestricted = token;
  6157. }
  6158. }
  6159. }
  6160. while (index < length) {
  6161. sourceElement = parseSourceElement();
  6162. if (typeof sourceElement === 'undefined') {
  6163. break;
  6164. }
  6165. sourceElements.push(sourceElement);
  6166. }
  6167. return sourceElements;
  6168. }
  6169. function parseProgram() {
  6170. var program;
  6171. strict = false;
  6172. program = {
  6173. type: Syntax.Program,
  6174. body: parseSourceElements()
  6175. };
  6176. return program;
  6177. }
  6178. // The following functions are needed only when the option to preserve
  6179. // the comments is active.
  6180. function addComment(start, end, type, value) {
  6181. assert(typeof start === 'number', 'Comment must have valid position');
  6182. // Because the way the actual token is scanned, often the comments
  6183. // (if any) are skipped twice during the lexical analysis.
  6184. // Thus, we need to skip adding a comment if the comment array already
  6185. // handled it.
  6186. if (extra.comments.length > 0) {
  6187. if (extra.comments[extra.comments.length - 1].range[1] > start) {
  6188. return;
  6189. }
  6190. }
  6191. extra.comments.push({
  6192. range: [start, end],
  6193. type: type,
  6194. value: value
  6195. });
  6196. }
  6197. function scanComment() {
  6198. var comment, ch, start, blockComment, lineComment;
  6199. comment = '';
  6200. blockComment = false;
  6201. lineComment = false;
  6202. while (index < length) {
  6203. ch = source[index];
  6204. if (lineComment) {
  6205. ch = nextChar();
  6206. if (index >= length) {
  6207. lineComment = false;
  6208. comment += ch;
  6209. addComment(start, index, 'Line', comment);
  6210. } else if (isLineTerminator(ch)) {
  6211. lineComment = false;
  6212. addComment(start, index, 'Line', comment);
  6213. if (ch === '\r' && source[index] === '\n') {
  6214. ++index;
  6215. }
  6216. ++lineNumber;
  6217. lineStart = index;
  6218. comment = '';
  6219. } else {
  6220. comment += ch;
  6221. }
  6222. } else if (blockComment) {
  6223. if (isLineTerminator(ch)) {
  6224. if (ch === '\r' && source[index + 1] === '\n') {
  6225. ++index;
  6226. comment += '\r\n';
  6227. } else {
  6228. comment += ch;
  6229. }
  6230. ++lineNumber;
  6231. ++index;
  6232. lineStart = index;
  6233. if (index >= length) {
  6234. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  6235. }
  6236. } else {
  6237. ch = nextChar();
  6238. if (index >= length) {
  6239. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  6240. }
  6241. comment += ch;
  6242. if (ch === '*') {
  6243. ch = source[index];
  6244. if (ch === '/') {
  6245. comment = comment.substr(0, comment.length - 1);
  6246. blockComment = false;
  6247. ++index;
  6248. addComment(start, index, 'Block', comment);
  6249. comment = '';
  6250. }
  6251. }
  6252. }
  6253. } else if (ch === '/') {
  6254. ch = source[index + 1];
  6255. if (ch === '/') {
  6256. start = index;
  6257. index += 2;
  6258. lineComment = true;
  6259. } else if (ch === '*') {
  6260. start = index;
  6261. index += 2;
  6262. blockComment = true;
  6263. if (index >= length) {
  6264. throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
  6265. }
  6266. } else {
  6267. break;
  6268. }
  6269. } else if (isWhiteSpace(ch)) {
  6270. ++index;
  6271. } else if (isLineTerminator(ch)) {
  6272. ++index;
  6273. if (ch === '\r' && source[index] === '\n') {
  6274. ++index;
  6275. }
  6276. ++lineNumber;
  6277. lineStart = index;
  6278. } else {
  6279. break;
  6280. }
  6281. }
  6282. }
  6283. function collectToken() {
  6284. var token = extra.advance(),
  6285. range,
  6286. value;
  6287. if (token.type !== Token.EOF) {
  6288. range = [token.range[0], token.range[1]];
  6289. value = sliceSource(token.range[0], token.range[1]);
  6290. extra.tokens.push({
  6291. type: TokenName[token.type],
  6292. value: value,
  6293. range: range
  6294. });
  6295. }
  6296. return token;
  6297. }
  6298. function collectRegex() {
  6299. var pos, regex, token;
  6300. skipComment();
  6301. pos = index;
  6302. regex = extra.scanRegExp();
  6303. // Pop the previous token, which is likely '/' or '/='
  6304. if (extra.tokens.length > 0) {
  6305. token = extra.tokens[extra.tokens.length - 1];
  6306. if (token.range[0] === pos && token.type === 'Punctuator') {
  6307. if (token.value === '/' || token.value === '/=') {
  6308. extra.tokens.pop();
  6309. }
  6310. }
  6311. }
  6312. extra.tokens.push({
  6313. type: 'RegularExpression',
  6314. value: regex.literal,
  6315. range: [pos, index]
  6316. });
  6317. return regex;
  6318. }
  6319. function createLiteral(token) {
  6320. return {
  6321. type: Syntax.Literal,
  6322. value: token.value
  6323. };
  6324. }
  6325. function createRawLiteral(token) {
  6326. return {
  6327. type: Syntax.Literal,
  6328. value: token.value,
  6329. raw: sliceSource(token.range[0], token.range[1])
  6330. };
  6331. }
  6332. function wrapTrackingFunction(range, loc) {
  6333. return function (parseFunction) {
  6334. function isBinary(node) {
  6335. return node.type === Syntax.LogicalExpression ||
  6336. node.type === Syntax.BinaryExpression;
  6337. }
  6338. function visit(node) {
  6339. if (isBinary(node.left)) {
  6340. visit(node.left);
  6341. }
  6342. if (isBinary(node.right)) {
  6343. visit(node.right);
  6344. }
  6345. if (range && typeof node.range === 'undefined') {
  6346. node.range = [node.left.range[0], node.right.range[1]];
  6347. }
  6348. if (loc && typeof node.loc === 'undefined') {
  6349. node.loc = {
  6350. start: node.left.loc.start,
  6351. end: node.right.loc.end
  6352. };
  6353. }
  6354. }
  6355. return function () {
  6356. var node, rangeInfo, locInfo;
  6357. skipComment();
  6358. rangeInfo = [index, 0];
  6359. locInfo = {
  6360. start: {
  6361. line: lineNumber,
  6362. column: index - lineStart
  6363. }
  6364. };
  6365. node = parseFunction.apply(null, arguments);
  6366. if (typeof node !== 'undefined') {
  6367. if (range) {
  6368. rangeInfo[1] = index;
  6369. node.range = rangeInfo;
  6370. }
  6371. if (loc) {
  6372. locInfo.end = {
  6373. line: lineNumber,
  6374. column: index - lineStart
  6375. };
  6376. node.loc = locInfo;
  6377. }
  6378. if (isBinary(node)) {
  6379. visit(node);
  6380. }
  6381. if (node.type === Syntax.MemberExpression) {
  6382. if (typeof node.object.range !== 'undefined') {
  6383. node.range[0] = node.object.range[0];
  6384. }
  6385. if (typeof node.object.loc !== 'undefined') {
  6386. node.loc.start = node.object.loc.start;
  6387. }
  6388. }
  6389. if (node.type === Syntax.CallExpression) {
  6390. if (typeof node.callee.range !== 'undefined') {
  6391. node.range[0] = node.callee.range[0];
  6392. }
  6393. if (typeof node.callee.loc !== 'undefined') {
  6394. node.loc.start = node.callee.loc.start;
  6395. }
  6396. }
  6397. return node;
  6398. }
  6399. };
  6400. };
  6401. }
  6402. function patch() {
  6403. var wrapTracking;
  6404. if (extra.comments) {
  6405. extra.skipComment = skipComment;
  6406. skipComment = scanComment;
  6407. }
  6408. if (extra.raw) {
  6409. extra.createLiteral = createLiteral;
  6410. createLiteral = createRawLiteral;
  6411. }
  6412. if (extra.range || extra.loc) {
  6413. wrapTracking = wrapTrackingFunction(extra.range, extra.loc);
  6414. extra.parseAdditiveExpression = parseAdditiveExpression;
  6415. extra.parseAssignmentExpression = parseAssignmentExpression;
  6416. extra.parseBitwiseANDExpression = parseBitwiseANDExpression;
  6417. extra.parseBitwiseORExpression = parseBitwiseORExpression;
  6418. extra.parseBitwiseXORExpression = parseBitwiseXORExpression;
  6419. extra.parseBlock = parseBlock;
  6420. extra.parseFunctionSourceElements = parseFunctionSourceElements;
  6421. extra.parseCallMember = parseCallMember;
  6422. extra.parseCatchClause = parseCatchClause;
  6423. extra.parseComputedMember = parseComputedMember;
  6424. extra.parseConditionalExpression = parseConditionalExpression;
  6425. extra.parseConstLetDeclaration = parseConstLetDeclaration;
  6426. extra.parseEqualityExpression = parseEqualityExpression;
  6427. extra.parseExpression = parseExpression;
  6428. extra.parseForVariableDeclaration = parseForVariableDeclaration;
  6429. extra.parseFunctionDeclaration = parseFunctionDeclaration;
  6430. extra.parseFunctionExpression = parseFunctionExpression;
  6431. extra.parseLogicalANDExpression = parseLogicalANDExpression;
  6432. extra.parseLogicalORExpression = parseLogicalORExpression;
  6433. extra.parseMultiplicativeExpression = parseMultiplicativeExpression;
  6434. extra.parseNewExpression = parseNewExpression;
  6435. extra.parseNonComputedMember = parseNonComputedMember;
  6436. extra.parseNonComputedProperty = parseNonComputedProperty;
  6437. extra.parseObjectProperty = parseObjectProperty;
  6438. extra.parseObjectPropertyKey = parseObjectPropertyKey;
  6439. extra.parsePostfixExpression = parsePostfixExpression;
  6440. extra.parsePrimaryExpression = parsePrimaryExpression;
  6441. extra.parseProgram = parseProgram;
  6442. extra.parsePropertyFunction = parsePropertyFunction;
  6443. extra.parseRelationalExpression = parseRelationalExpression;
  6444. extra.parseStatement = parseStatement;
  6445. extra.parseShiftExpression = parseShiftExpression;
  6446. extra.parseSwitchCase = parseSwitchCase;
  6447. extra.parseUnaryExpression = parseUnaryExpression;
  6448. extra.parseVariableDeclaration = parseVariableDeclaration;
  6449. extra.parseVariableIdentifier = parseVariableIdentifier;
  6450. parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression);
  6451. parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression);
  6452. parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression);
  6453. parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression);
  6454. parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression);
  6455. parseBlock = wrapTracking(extra.parseBlock);
  6456. parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements);
  6457. parseCallMember = wrapTracking(extra.parseCallMember);
  6458. parseCatchClause = wrapTracking(extra.parseCatchClause);
  6459. parseComputedMember = wrapTracking(extra.parseComputedMember);
  6460. parseConditionalExpression = wrapTracking(extra.parseConditionalExpression);
  6461. parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration);
  6462. parseEqualityExpression = wrapTracking(extra.parseEqualityExpression);
  6463. parseExpression = wrapTracking(extra.parseExpression);
  6464. parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration);
  6465. parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration);
  6466. parseFunctionExpression = wrapTracking(extra.parseFunctionExpression);
  6467. parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression);
  6468. parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression);
  6469. parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression);
  6470. parseNewExpression = wrapTracking(extra.parseNewExpression);
  6471. parseNonComputedMember = wrapTracking(extra.parseNonComputedMember);
  6472. parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty);
  6473. parseObjectProperty = wrapTracking(extra.parseObjectProperty);
  6474. parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey);
  6475. parsePostfixExpression = wrapTracking(extra.parsePostfixExpression);
  6476. parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression);
  6477. parseProgram = wrapTracking(extra.parseProgram);
  6478. parsePropertyFunction = wrapTracking(extra.parsePropertyFunction);
  6479. parseRelationalExpression = wrapTracking(extra.parseRelationalExpression);
  6480. parseStatement = wrapTracking(extra.parseStatement);
  6481. parseShiftExpression = wrapTracking(extra.parseShiftExpression);
  6482. parseSwitchCase = wrapTracking(extra.parseSwitchCase);
  6483. parseUnaryExpression = wrapTracking(extra.parseUnaryExpression);
  6484. parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration);
  6485. parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier);
  6486. }
  6487. if (typeof extra.tokens !== 'undefined') {
  6488. extra.advance = advance;
  6489. extra.scanRegExp = scanRegExp;
  6490. advance = collectToken;
  6491. scanRegExp = collectRegex;
  6492. }
  6493. }
  6494. function unpatch() {
  6495. if (typeof extra.skipComment === 'function') {
  6496. skipComment = extra.skipComment;
  6497. }
  6498. if (extra.raw) {
  6499. createLiteral = extra.createLiteral;
  6500. }
  6501. if (extra.range || extra.loc) {
  6502. parseAdditiveExpression = extra.parseAdditiveExpression;
  6503. parseAssignmentExpression = extra.parseAssignmentExpression;
  6504. parseBitwiseANDExpression = extra.parseBitwiseANDExpression;
  6505. parseBitwiseORExpression = extra.parseBitwiseORExpression;
  6506. parseBitwiseXORExpression = extra.parseBitwiseXORExpression;
  6507. parseBlock = extra.parseBlock;
  6508. parseFunctionSourceElements = extra.parseFunctionSourceElements;
  6509. parseCallMember = extra.parseCallMember;
  6510. parseCatchClause = extra.parseCatchClause;
  6511. parseComputedMember = extra.parseComputedMember;
  6512. parseConditionalExpression = extra.parseConditionalExpression;
  6513. parseConstLetDeclaration = extra.parseConstLetDeclaration;
  6514. parseEqualityExpression = extra.parseEqualityExpression;
  6515. parseExpression = extra.parseExpression;
  6516. parseForVariableDeclaration = extra.parseForVariableDeclaration;
  6517. parseFunctionDeclaration = extra.parseFunctionDeclaration;
  6518. parseFunctionExpression = extra.parseFunctionExpression;
  6519. parseLogicalANDExpression = extra.parseLogicalANDExpression;
  6520. parseLogicalORExpression = extra.parseLogicalORExpression;
  6521. parseMultiplicativeExpression = extra.parseMultiplicativeExpression;
  6522. parseNewExpression = extra.parseNewExpression;
  6523. parseNonComputedMember = extra.parseNonComputedMember;
  6524. parseNonComputedProperty = extra.parseNonComputedProperty;
  6525. parseObjectProperty = extra.parseObjectProperty;
  6526. parseObjectPropertyKey = extra.parseObjectPropertyKey;
  6527. parsePrimaryExpression = extra.parsePrimaryExpression;
  6528. parsePostfixExpression = extra.parsePostfixExpression;
  6529. parseProgram = extra.parseProgram;
  6530. parsePropertyFunction = extra.parsePropertyFunction;
  6531. parseRelationalExpression = extra.parseRelationalExpression;
  6532. parseStatement = extra.parseStatement;
  6533. parseShiftExpression = extra.parseShiftExpression;
  6534. parseSwitchCase = extra.parseSwitchCase;
  6535. parseUnaryExpression = extra.parseUnaryExpression;
  6536. parseVariableDeclaration = extra.parseVariableDeclaration;
  6537. parseVariableIdentifier = extra.parseVariableIdentifier;
  6538. }
  6539. if (typeof extra.scanRegExp === 'function') {
  6540. advance = extra.advance;
  6541. scanRegExp = extra.scanRegExp;
  6542. }
  6543. }
  6544. function stringToArray(str) {
  6545. var length = str.length,
  6546. result = [],
  6547. i;
  6548. for (i = 0; i < length; ++i) {
  6549. result[i] = str.charAt(i);
  6550. }
  6551. return result;
  6552. }
  6553. function parse(code, options) {
  6554. var program, toString;
  6555. toString = String;
  6556. if (typeof code !== 'string' && !(code instanceof String)) {
  6557. code = toString(code);
  6558. }
  6559. source = code;
  6560. index = 0;
  6561. lineNumber = (source.length > 0) ? 1 : 0;
  6562. lineStart = 0;
  6563. length = source.length;
  6564. buffer = null;
  6565. state = {
  6566. allowIn: true,
  6567. labelSet: {},
  6568. lastParenthesized: null,
  6569. inFunctionBody: false,
  6570. inIteration: false,
  6571. inSwitch: false
  6572. };
  6573. extra = {};
  6574. if (typeof options !== 'undefined') {
  6575. extra.range = (typeof options.range === 'boolean') && options.range;
  6576. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  6577. extra.raw = (typeof options.raw === 'boolean') && options.raw;
  6578. if (typeof options.tokens === 'boolean' && options.tokens) {
  6579. extra.tokens = [];
  6580. }
  6581. if (typeof options.comment === 'boolean' && options.comment) {
  6582. extra.comments = [];
  6583. }
  6584. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  6585. extra.errors = [];
  6586. }
  6587. }
  6588. if (length > 0) {
  6589. if (typeof source[0] === 'undefined') {
  6590. // Try first to convert to a string. This is good as fast path
  6591. // for old IE which understands string indexing for string
  6592. // literals only and not for string object.
  6593. if (code instanceof String) {
  6594. source = code.valueOf();
  6595. }
  6596. // Force accessing the characters via an array.
  6597. if (typeof source[0] === 'undefined') {
  6598. source = stringToArray(code);
  6599. }
  6600. }
  6601. }
  6602. patch();
  6603. try {
  6604. program = parseProgram();
  6605. if (typeof extra.comments !== 'undefined') {
  6606. program.comments = extra.comments;
  6607. }
  6608. if (typeof extra.tokens !== 'undefined') {
  6609. program.tokens = extra.tokens;
  6610. }
  6611. if (typeof extra.errors !== 'undefined') {
  6612. program.errors = extra.errors;
  6613. }
  6614. } catch (e) {
  6615. throw e;
  6616. } finally {
  6617. unpatch();
  6618. extra = {};
  6619. }
  6620. return program;
  6621. }
  6622. // Sync with package.json.
  6623. exports.version = '1.0.0-dev';
  6624. exports.parse = parse;
  6625. // Deep copy.
  6626. exports.Syntax = (function () {
  6627. var name, types = {};
  6628. if (typeof Object.create === 'function') {
  6629. types = Object.create(null);
  6630. }
  6631. for (name in Syntax) {
  6632. if (Syntax.hasOwnProperty(name)) {
  6633. types[name] = Syntax[name];
  6634. }
  6635. }
  6636. if (typeof Object.freeze === 'function') {
  6637. Object.freeze(types);
  6638. }
  6639. return types;
  6640. }());
  6641. }(typeof exports === 'undefined' ? (esprima = {}) : exports));
  6642. /* vim: set sw=4 ts=4 et tw=80 : */
  6643. });define('uglifyjs/consolidator', ["require", "exports", "module", "./parse-js", "./process"], function(require, exports, module) {
  6644. /**
  6645. * @preserve Copyright 2012 Robert Gust-Bardon <http://robert.gust-bardon.org/>.
  6646. * All rights reserved.
  6647. *
  6648. * Redistribution and use in source and binary forms, with or without
  6649. * modification, are permitted provided that the following conditions
  6650. * are met:
  6651. *
  6652. * * Redistributions of source code must retain the above
  6653. * copyright notice, this list of conditions and the following
  6654. * disclaimer.
  6655. *
  6656. * * Redistributions in binary form must reproduce the above
  6657. * copyright notice, this list of conditions and the following
  6658. * disclaimer in the documentation and/or other materials
  6659. * provided with the distribution.
  6660. *
  6661. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
  6662. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  6663. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  6664. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  6665. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  6666. * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  6667. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  6668. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  6669. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  6670. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  6671. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  6672. * SUCH DAMAGE.
  6673. */
  6674. /**
  6675. * @fileoverview Enhances <a href="https://github.com/mishoo/UglifyJS/"
  6676. * >UglifyJS</a> with consolidation of null, Boolean, and String values.
  6677. * <p>Also known as aliasing, this feature has been deprecated in <a href=
  6678. * "http://closure-compiler.googlecode.com/">the Closure Compiler</a> since its
  6679. * initial release, where it is unavailable from the <abbr title=
  6680. * "command line interface">CLI</a>. The Closure Compiler allows one to log and
  6681. * influence this process. In contrast, this implementation does not introduce
  6682. * any variable declarations in global code and derives String values from
  6683. * identifier names used as property accessors.</p>
  6684. * <p>Consolidating literals may worsen the data compression ratio when an <a
  6685. * href="http://tools.ietf.org/html/rfc2616#section-3.5">encoding
  6686. * transformation</a> is applied. For instance, <a href=
  6687. * "http://code.jquery.com/jquery-1.7.1.js">jQuery 1.7.1</a> takes 248235 bytes.
  6688. * Building it with <a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">
  6689. * UglifyJS v1.2.5</a> results in 93647 bytes (37.73% of the original) which are
  6690. * then compressed to 33154 bytes (13.36% of the original) using <a href=
  6691. * "http://linux.die.net/man/1/gzip">gzip(1)</a>. Building it with the same
  6692. * version of UglifyJS 1.2.5 patched with the implementation of consolidation
  6693. * results in 80784 bytes (a decrease of 12863 bytes, i.e. 13.74%, in comparison
  6694. * to the aforementioned 93647 bytes) which are then compressed to 34013 bytes
  6695. * (an increase of 859 bytes, i.e. 2.59%, in comparison to the aforementioned
  6696. * 33154 bytes).</p>
  6697. * <p>Written in <a href="http://es5.github.com/#x4.2.2">the strict variant</a>
  6698. * of <a href="http://es5.github.com/">ECMA-262 5.1 Edition</a>. Encoded in <a
  6699. * href="http://tools.ietf.org/html/rfc3629">UTF-8</a>. Follows <a href=
  6700. * "http://google-styleguide.googlecode.com/svn-history/r76/trunk/javascriptguide.xml"
  6701. * >Revision 2.28 of the Google JavaScript Style Guide</a> (except for the
  6702. * discouraged use of the {@code function} tag and the {@code namespace} tag).
  6703. * 100% typed for the <a href=
  6704. * "http://closure-compiler.googlecode.com/files/compiler-20120123.tar.gz"
  6705. * >Closure Compiler Version 1741</a>.</p>
  6706. * <p>Should you find this software useful, please consider <a href=
  6707. * "https://paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JZLW72X8FD4WG"
  6708. * >a donation</a>.</p>
  6709. * @author follow.me@RGustBardon (Robert Gust-Bardon)
  6710. * @supported Tested with:
  6711. * <ul>
  6712. * <li><a href="http://nodejs.org/dist/v0.6.10/">Node v0.6.10</a>,</li>
  6713. * <li><a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">UglifyJS
  6714. * v1.2.5</a>.</li>
  6715. * </ul>
  6716. */
  6717. /*global console:false, exports:true, module:false, require:false */
  6718. /*jshint sub:true */
  6719. /**
  6720. * Consolidates null, Boolean, and String values found inside an <abbr title=
  6721. * "abstract syntax tree">AST</abbr>.
  6722. * @param {!TSyntacticCodeUnit} oAbstractSyntaxTree An array-like object
  6723. * representing an <abbr title="abstract syntax tree">AST</abbr>.
  6724. * @return {!TSyntacticCodeUnit} An array-like object representing an <abbr
  6725. * title="abstract syntax tree">AST</abbr> with its null, Boolean, and
  6726. * String values consolidated.
  6727. */
  6728. // TODO(user) Consolidation of mathematical values found in numeric literals.
  6729. // TODO(user) Unconsolidation.
  6730. // TODO(user) Consolidation of ECMA-262 6th Edition programs.
  6731. // TODO(user) Rewrite in ECMA-262 6th Edition.
  6732. exports['ast_consolidate'] = function(oAbstractSyntaxTree) {
  6733. 'use strict';
  6734. /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,
  6735. latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,
  6736. onevar:true, plusplus:true, regexp:true, undef:true, strict:true,
  6737. sub:false, trailing:true */
  6738. var _,
  6739. /**
  6740. * A record consisting of data about one or more source elements.
  6741. * @constructor
  6742. * @nosideeffects
  6743. */
  6744. TSourceElementsData = function() {
  6745. /**
  6746. * The category of the elements.
  6747. * @type {number}
  6748. * @see ESourceElementCategories
  6749. */
  6750. this.nCategory = ESourceElementCategories.N_OTHER;
  6751. /**
  6752. * The number of occurrences (within the elements) of each primitive
  6753. * value that could be consolidated.
  6754. * @type {!Array.<!Object.<string, number>>}
  6755. */
  6756. this.aCount = [];
  6757. this.aCount[EPrimaryExpressionCategories.N_IDENTIFIER_NAMES] = {};
  6758. this.aCount[EPrimaryExpressionCategories.N_STRING_LITERALS] = {};
  6759. this.aCount[EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS] =
  6760. {};
  6761. /**
  6762. * Identifier names found within the elements.
  6763. * @type {!Array.<string>}
  6764. */
  6765. this.aIdentifiers = [];
  6766. /**
  6767. * Prefixed representation Strings of each primitive value that could be
  6768. * consolidated within the elements.
  6769. * @type {!Array.<string>}
  6770. */
  6771. this.aPrimitiveValues = [];
  6772. },
  6773. /**
  6774. * A record consisting of data about a primitive value that could be
  6775. * consolidated.
  6776. * @constructor
  6777. * @nosideeffects
  6778. */
  6779. TPrimitiveValue = function() {
  6780. /**
  6781. * The difference in the number of terminal symbols between the original
  6782. * source text and the one with the primitive value consolidated. If the
  6783. * difference is positive, the primitive value is considered worthwhile.
  6784. * @type {number}
  6785. */
  6786. this.nSaving = 0;
  6787. /**
  6788. * An identifier name of the variable that will be declared and assigned
  6789. * the primitive value if the primitive value is consolidated.
  6790. * @type {string}
  6791. */
  6792. this.sName = '';
  6793. },
  6794. /**
  6795. * A record consisting of data on what to consolidate within the range of
  6796. * source elements that is currently being considered.
  6797. * @constructor
  6798. * @nosideeffects
  6799. */
  6800. TSolution = function() {
  6801. /**
  6802. * An object whose keys are prefixed representation Strings of each
  6803. * primitive value that could be consolidated within the elements and
  6804. * whose values are corresponding data about those primitive values.
  6805. * @type {!Object.<string, {nSaving: number, sName: string}>}
  6806. * @see TPrimitiveValue
  6807. */
  6808. this.oPrimitiveValues = {};
  6809. /**
  6810. * The difference in the number of terminal symbols between the original
  6811. * source text and the one with all the worthwhile primitive values
  6812. * consolidated.
  6813. * @type {number}
  6814. * @see TPrimitiveValue#nSaving
  6815. */
  6816. this.nSavings = 0;
  6817. },
  6818. /**
  6819. * The processor of <abbr title="abstract syntax tree">AST</abbr>s found
  6820. * in UglifyJS.
  6821. * @namespace
  6822. * @type {!TProcessor}
  6823. */
  6824. oProcessor = (/** @type {!TProcessor} */ require('./process')),
  6825. /**
  6826. * A record consisting of a number of constants that represent the
  6827. * difference in the number of terminal symbols between a source text with
  6828. * a modified syntactic code unit and the original one.
  6829. * @namespace
  6830. * @type {!Object.<string, number>}
  6831. */
  6832. oWeights = {
  6833. /**
  6834. * The difference in the number of punctuators required by the bracket
  6835. * notation and the dot notation.
  6836. * <p><code>'[]'.length - '.'.length</code></p>
  6837. * @const
  6838. * @type {number}
  6839. */
  6840. N_PROPERTY_ACCESSOR: 1,
  6841. /**
  6842. * The number of punctuators required by a variable declaration with an
  6843. * initialiser.
  6844. * <p><code>':'.length + ';'.length</code></p>
  6845. * @const
  6846. * @type {number}
  6847. */
  6848. N_VARIABLE_DECLARATION: 2,
  6849. /**
  6850. * The number of terminal symbols required to introduce a variable
  6851. * statement (excluding its variable declaration list).
  6852. * <p><code>'var '.length</code></p>
  6853. * @const
  6854. * @type {number}
  6855. */
  6856. N_VARIABLE_STATEMENT_AFFIXATION: 4,
  6857. /**
  6858. * The number of terminal symbols needed to enclose source elements
  6859. * within a function call with no argument values to a function with an
  6860. * empty parameter list.
  6861. * <p><code>'(function(){}());'.length</code></p>
  6862. * @const
  6863. * @type {number}
  6864. */
  6865. N_CLOSURE: 17
  6866. },
  6867. /**
  6868. * Categories of primary expressions from which primitive values that
  6869. * could be consolidated are derivable.
  6870. * @namespace
  6871. * @enum {number}
  6872. */
  6873. EPrimaryExpressionCategories = {
  6874. /**
  6875. * Identifier names used as property accessors.
  6876. * @type {number}
  6877. */
  6878. N_IDENTIFIER_NAMES: 0,
  6879. /**
  6880. * String literals.
  6881. * @type {number}
  6882. */
  6883. N_STRING_LITERALS: 1,
  6884. /**
  6885. * Null and Boolean literals.
  6886. * @type {number}
  6887. */
  6888. N_NULL_AND_BOOLEAN_LITERALS: 2
  6889. },
  6890. /**
  6891. * Prefixes of primitive values that could be consolidated.
  6892. * The String values of the prefixes must have same number of characters.
  6893. * The prefixes must not be used in any properties defined in any version
  6894. * of <a href=
  6895. * "http://www.ecma-international.org/publications/standards/Ecma-262.htm"
  6896. * >ECMA-262</a>.
  6897. * @namespace
  6898. * @enum {string}
  6899. */
  6900. EValuePrefixes = {
  6901. /**
  6902. * Identifies String values.
  6903. * @type {string}
  6904. */
  6905. S_STRING: '#S',
  6906. /**
  6907. * Identifies null and Boolean values.
  6908. * @type {string}
  6909. */
  6910. S_SYMBOLIC: '#O'
  6911. },
  6912. /**
  6913. * Categories of source elements in terms of their appropriateness of
  6914. * having their primitive values consolidated.
  6915. * @namespace
  6916. * @enum {number}
  6917. */
  6918. ESourceElementCategories = {
  6919. /**
  6920. * Identifies a source element that includes the <a href=
  6921. * "http://es5.github.com/#x12.10">{@code with}</a> statement.
  6922. * @type {number}
  6923. */
  6924. N_WITH: 0,
  6925. /**
  6926. * Identifies a source element that includes the <a href=
  6927. * "http://es5.github.com/#x15.1.2.1">{@code eval}</a> identifier name.
  6928. * @type {number}
  6929. */
  6930. N_EVAL: 1,
  6931. /**
  6932. * Identifies a source element that must be excluded from the process
  6933. * unless its whole scope is examined.
  6934. * @type {number}
  6935. */
  6936. N_EXCLUDABLE: 2,
  6937. /**
  6938. * Identifies source elements not posing any problems.
  6939. * @type {number}
  6940. */
  6941. N_OTHER: 3
  6942. },
  6943. /**
  6944. * The list of literals (other than the String ones) whose primitive
  6945. * values can be consolidated.
  6946. * @const
  6947. * @type {!Array.<string>}
  6948. */
  6949. A_OTHER_SUBSTITUTABLE_LITERALS = [
  6950. 'null', // The null literal.
  6951. 'false', // The Boolean literal {@code false}.
  6952. 'true' // The Boolean literal {@code true}.
  6953. ];
  6954. (/**
  6955. * Consolidates all worthwhile primitive values in a syntactic code unit.
  6956. * @param {!TSyntacticCodeUnit} oSyntacticCodeUnit An array-like object
  6957. * representing the branch of the abstract syntax tree representing the
  6958. * syntactic code unit along with its scope.
  6959. * @see TPrimitiveValue#nSaving
  6960. */
  6961. function fExamineSyntacticCodeUnit(oSyntacticCodeUnit) {
  6962. var _,
  6963. /**
  6964. * Indicates whether the syntactic code unit represents global code.
  6965. * @type {boolean}
  6966. */
  6967. bIsGlobal = 'toplevel' === oSyntacticCodeUnit[0],
  6968. /**
  6969. * Indicates whether the whole scope is being examined.
  6970. * @type {boolean}
  6971. */
  6972. bIsWhollyExaminable = !bIsGlobal,
  6973. /**
  6974. * An array-like object representing source elements that constitute a
  6975. * syntactic code unit.
  6976. * @type {!TSyntacticCodeUnit}
  6977. */
  6978. oSourceElements,
  6979. /**
  6980. * A record consisting of data about the source element that is
  6981. * currently being examined.
  6982. * @type {!TSourceElementsData}
  6983. */
  6984. oSourceElementData,
  6985. /**
  6986. * The scope of the syntactic code unit.
  6987. * @type {!TScope}
  6988. */
  6989. oScope,
  6990. /**
  6991. * An instance of an object that allows the traversal of an <abbr
  6992. * title="abstract syntax tree">AST</abbr>.
  6993. * @type {!TWalker}
  6994. */
  6995. oWalker,
  6996. /**
  6997. * An object encompassing collections of functions used during the
  6998. * traversal of an <abbr title="abstract syntax tree">AST</abbr>.
  6999. * @namespace
  7000. * @type {!Object.<string, !Object.<string, function(...[*])>>}
  7001. */
  7002. oWalkers = {
  7003. /**
  7004. * A collection of functions used during the surveyance of source
  7005. * elements.
  7006. * @namespace
  7007. * @type {!Object.<string, function(...[*])>}
  7008. */
  7009. oSurveySourceElement: {
  7010. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  7011. /**
  7012. * Classifies the source element as excludable if it does not
  7013. * contain a {@code with} statement or the {@code eval} identifier
  7014. * name. Adds the identifier of the function and its formal
  7015. * parameters to the list of identifier names found.
  7016. * @param {string} sIdentifier The identifier of the function.
  7017. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  7018. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  7019. */
  7020. 'defun': function(
  7021. sIdentifier,
  7022. aFormalParameterList,
  7023. oFunctionBody) {
  7024. fClassifyAsExcludable();
  7025. fAddIdentifier(sIdentifier);
  7026. aFormalParameterList.forEach(fAddIdentifier);
  7027. },
  7028. /**
  7029. * Increments the count of the number of occurrences of the String
  7030. * value that is equivalent to the sequence of terminal symbols
  7031. * that constitute the encountered identifier name.
  7032. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  7033. * MemberExpression.
  7034. * @param {string} sIdentifierName The identifier name used as the
  7035. * property accessor.
  7036. * @return {!Array} The encountered branch of an <abbr title=
  7037. * "abstract syntax tree">AST</abbr> with its nonterminal
  7038. * MemberExpression traversed.
  7039. */
  7040. 'dot': function(oExpression, sIdentifierName) {
  7041. fCountPrimaryExpression(
  7042. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
  7043. EValuePrefixes.S_STRING + sIdentifierName);
  7044. return ['dot', oWalker.walk(oExpression), sIdentifierName];
  7045. },
  7046. /**
  7047. * Adds the optional identifier of the function and its formal
  7048. * parameters to the list of identifier names found.
  7049. * @param {?string} sIdentifier The optional identifier of the
  7050. * function.
  7051. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  7052. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  7053. */
  7054. 'function': function(
  7055. sIdentifier,
  7056. aFormalParameterList,
  7057. oFunctionBody) {
  7058. if ('string' === typeof sIdentifier) {
  7059. fAddIdentifier(sIdentifier);
  7060. }
  7061. aFormalParameterList.forEach(fAddIdentifier);
  7062. },
  7063. /**
  7064. * Either increments the count of the number of occurrences of the
  7065. * encountered null or Boolean value or classifies a source element
  7066. * as containing the {@code eval} identifier name.
  7067. * @param {string} sIdentifier The identifier encountered.
  7068. */
  7069. 'name': function(sIdentifier) {
  7070. if (-1 !== A_OTHER_SUBSTITUTABLE_LITERALS.indexOf(sIdentifier)) {
  7071. fCountPrimaryExpression(
  7072. EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS,
  7073. EValuePrefixes.S_SYMBOLIC + sIdentifier);
  7074. } else {
  7075. if ('eval' === sIdentifier) {
  7076. oSourceElementData.nCategory =
  7077. ESourceElementCategories.N_EVAL;
  7078. }
  7079. fAddIdentifier(sIdentifier);
  7080. }
  7081. },
  7082. /**
  7083. * Classifies the source element as excludable if it does not
  7084. * contain a {@code with} statement or the {@code eval} identifier
  7085. * name.
  7086. * @param {TSyntacticCodeUnit} oExpression The expression whose
  7087. * value is to be returned.
  7088. */
  7089. 'return': function(oExpression) {
  7090. fClassifyAsExcludable();
  7091. },
  7092. /**
  7093. * Increments the count of the number of occurrences of the
  7094. * encountered String value.
  7095. * @param {string} sStringValue The String value of the string
  7096. * literal encountered.
  7097. */
  7098. 'string': function(sStringValue) {
  7099. if (sStringValue.length > 0) {
  7100. fCountPrimaryExpression(
  7101. EPrimaryExpressionCategories.N_STRING_LITERALS,
  7102. EValuePrefixes.S_STRING + sStringValue);
  7103. }
  7104. },
  7105. /**
  7106. * Adds the identifier reserved for an exception to the list of
  7107. * identifier names found.
  7108. * @param {!TSyntacticCodeUnit} oTry A block of code in which an
  7109. * exception can occur.
  7110. * @param {Array} aCatch The identifier reserved for an exception
  7111. * and a block of code to handle the exception.
  7112. * @param {TSyntacticCodeUnit} oFinally An optional block of code
  7113. * to be evaluated regardless of whether an exception occurs.
  7114. */
  7115. 'try': function(oTry, aCatch, oFinally) {
  7116. if (Array.isArray(aCatch)) {
  7117. fAddIdentifier(aCatch[0]);
  7118. }
  7119. },
  7120. /**
  7121. * Classifies the source element as excludable if it does not
  7122. * contain a {@code with} statement or the {@code eval} identifier
  7123. * name. Adds the identifier of each declared variable to the list
  7124. * of identifier names found.
  7125. * @param {!Array.<!Array>} aVariableDeclarationList Variable
  7126. * declarations.
  7127. */
  7128. 'var': function(aVariableDeclarationList) {
  7129. fClassifyAsExcludable();
  7130. aVariableDeclarationList.forEach(fAddVariable);
  7131. },
  7132. /**
  7133. * Classifies a source element as containing the {@code with}
  7134. * statement.
  7135. * @param {!TSyntacticCodeUnit} oExpression An expression whose
  7136. * value is to be converted to a value of type Object and
  7137. * become the binding object of a new object environment
  7138. * record of a new lexical environment in which the statement
  7139. * is to be executed.
  7140. * @param {!TSyntacticCodeUnit} oStatement The statement to be
  7141. * executed in the augmented lexical environment.
  7142. * @return {!Array} An empty array to stop the traversal.
  7143. */
  7144. 'with': function(oExpression, oStatement) {
  7145. oSourceElementData.nCategory = ESourceElementCategories.N_WITH;
  7146. return [];
  7147. }
  7148. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  7149. },
  7150. /**
  7151. * A collection of functions used while looking for nested functions.
  7152. * @namespace
  7153. * @type {!Object.<string, function(...[*])>}
  7154. */
  7155. oExamineFunctions: {
  7156. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  7157. /**
  7158. * Orders an examination of a nested function declaration.
  7159. * @this {!TSyntacticCodeUnit} An array-like object representing
  7160. * the branch of an <abbr title="abstract syntax tree"
  7161. * >AST</abbr> representing the syntactic code unit along with
  7162. * its scope.
  7163. * @return {!Array} An empty array to stop the traversal.
  7164. */
  7165. 'defun': function() {
  7166. fExamineSyntacticCodeUnit(this);
  7167. return [];
  7168. },
  7169. /**
  7170. * Orders an examination of a nested function expression.
  7171. * @this {!TSyntacticCodeUnit} An array-like object representing
  7172. * the branch of an <abbr title="abstract syntax tree"
  7173. * >AST</abbr> representing the syntactic code unit along with
  7174. * its scope.
  7175. * @return {!Array} An empty array to stop the traversal.
  7176. */
  7177. 'function': function() {
  7178. fExamineSyntacticCodeUnit(this);
  7179. return [];
  7180. }
  7181. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  7182. }
  7183. },
  7184. /**
  7185. * Records containing data about source elements.
  7186. * @type {Array.<TSourceElementsData>}
  7187. */
  7188. aSourceElementsData = [],
  7189. /**
  7190. * The index (in the source text order) of the source element
  7191. * immediately following a <a href="http://es5.github.com/#x14.1"
  7192. * >Directive Prologue</a>.
  7193. * @type {number}
  7194. */
  7195. nAfterDirectivePrologue = 0,
  7196. /**
  7197. * The index (in the source text order) of the source element that is
  7198. * currently being considered.
  7199. * @type {number}
  7200. */
  7201. nPosition,
  7202. /**
  7203. * The index (in the source text order) of the source element that is
  7204. * the last element of the range of source elements that is currently
  7205. * being considered.
  7206. * @type {(undefined|number)}
  7207. */
  7208. nTo,
  7209. /**
  7210. * Initiates the traversal of a source element.
  7211. * @param {!TWalker} oWalker An instance of an object that allows the
  7212. * traversal of an abstract syntax tree.
  7213. * @param {!TSyntacticCodeUnit} oSourceElement A source element from
  7214. * which the traversal should commence.
  7215. * @return {function(): !TSyntacticCodeUnit} A function that is able to
  7216. * initiate the traversal from a given source element.
  7217. */
  7218. cContext = function(oWalker, oSourceElement) {
  7219. /**
  7220. * @return {!TSyntacticCodeUnit} A function that is able to
  7221. * initiate the traversal from a given source element.
  7222. */
  7223. var fLambda = function() {
  7224. return oWalker.walk(oSourceElement);
  7225. };
  7226. return fLambda;
  7227. },
  7228. /**
  7229. * Classifies the source element as excludable if it does not
  7230. * contain a {@code with} statement or the {@code eval} identifier
  7231. * name.
  7232. */
  7233. fClassifyAsExcludable = function() {
  7234. if (oSourceElementData.nCategory ===
  7235. ESourceElementCategories.N_OTHER) {
  7236. oSourceElementData.nCategory =
  7237. ESourceElementCategories.N_EXCLUDABLE;
  7238. }
  7239. },
  7240. /**
  7241. * Adds an identifier to the list of identifier names found.
  7242. * @param {string} sIdentifier The identifier to be added.
  7243. */
  7244. fAddIdentifier = function(sIdentifier) {
  7245. if (-1 === oSourceElementData.aIdentifiers.indexOf(sIdentifier)) {
  7246. oSourceElementData.aIdentifiers.push(sIdentifier);
  7247. }
  7248. },
  7249. /**
  7250. * Adds the identifier of a variable to the list of identifier names
  7251. * found.
  7252. * @param {!Array} aVariableDeclaration A variable declaration.
  7253. */
  7254. fAddVariable = function(aVariableDeclaration) {
  7255. fAddIdentifier(/** @type {string} */ aVariableDeclaration[0]);
  7256. },
  7257. /**
  7258. * Increments the count of the number of occurrences of the prefixed
  7259. * String representation attributed to the primary expression.
  7260. * @param {number} nCategory The category of the primary expression.
  7261. * @param {string} sName The prefixed String representation attributed
  7262. * to the primary expression.
  7263. */
  7264. fCountPrimaryExpression = function(nCategory, sName) {
  7265. if (!oSourceElementData.aCount[nCategory].hasOwnProperty(sName)) {
  7266. oSourceElementData.aCount[nCategory][sName] = 0;
  7267. if (-1 === oSourceElementData.aPrimitiveValues.indexOf(sName)) {
  7268. oSourceElementData.aPrimitiveValues.push(sName);
  7269. }
  7270. }
  7271. oSourceElementData.aCount[nCategory][sName] += 1;
  7272. },
  7273. /**
  7274. * Consolidates all worthwhile primitive values in a range of source
  7275. * elements.
  7276. * @param {number} nFrom The index (in the source text order) of the
  7277. * source element that is the first element of the range.
  7278. * @param {number} nTo The index (in the source text order) of the
  7279. * source element that is the last element of the range.
  7280. * @param {boolean} bEnclose Indicates whether the range should be
  7281. * enclosed within a function call with no argument values to a
  7282. * function with an empty parameter list if any primitive values
  7283. * are consolidated.
  7284. * @see TPrimitiveValue#nSaving
  7285. */
  7286. fExamineSourceElements = function(nFrom, nTo, bEnclose) {
  7287. var _,
  7288. /**
  7289. * The index of the last mangled name.
  7290. * @type {number}
  7291. */
  7292. nIndex = oScope.cname,
  7293. /**
  7294. * The index of the source element that is currently being
  7295. * considered.
  7296. * @type {number}
  7297. */
  7298. nPosition,
  7299. /**
  7300. * A collection of functions used during the consolidation of
  7301. * primitive values and identifier names used as property
  7302. * accessors.
  7303. * @namespace
  7304. * @type {!Object.<string, function(...[*])>}
  7305. */
  7306. oWalkersTransformers = {
  7307. /**
  7308. * If the String value that is equivalent to the sequence of
  7309. * terminal symbols that constitute the encountered identifier
  7310. * name is worthwhile, a syntactic conversion from the dot
  7311. * notation to the bracket notation ensues with that sequence
  7312. * being substituted by an identifier name to which the value
  7313. * is assigned.
  7314. * Applies to property accessors that use the dot notation.
  7315. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  7316. * MemberExpression.
  7317. * @param {string} sIdentifierName The identifier name used as
  7318. * the property accessor.
  7319. * @return {!Array} A syntactic code unit that is equivalent to
  7320. * the one encountered.
  7321. * @see TPrimitiveValue#nSaving
  7322. */
  7323. 'dot': function(oExpression, sIdentifierName) {
  7324. /**
  7325. * The prefixed String value that is equivalent to the
  7326. * sequence of terminal symbols that constitute the
  7327. * encountered identifier name.
  7328. * @type {string}
  7329. */
  7330. var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
  7331. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  7332. sPrefixed) &&
  7333. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  7334. ['sub',
  7335. oWalker.walk(oExpression),
  7336. ['name',
  7337. oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
  7338. ['dot', oWalker.walk(oExpression), sIdentifierName];
  7339. },
  7340. /**
  7341. * If the encountered identifier is a null or Boolean literal
  7342. * and its value is worthwhile, the identifier is substituted
  7343. * by an identifier name to which that value is assigned.
  7344. * Applies to identifier names.
  7345. * @param {string} sIdentifier The identifier encountered.
  7346. * @return {!Array} A syntactic code unit that is equivalent to
  7347. * the one encountered.
  7348. * @see TPrimitiveValue#nSaving
  7349. */
  7350. 'name': function(sIdentifier) {
  7351. /**
  7352. * The prefixed representation String of the identifier.
  7353. * @type {string}
  7354. */
  7355. var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
  7356. return [
  7357. 'name',
  7358. oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
  7359. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  7360. oSolutionBest.oPrimitiveValues[sPrefixed].sName :
  7361. sIdentifier
  7362. ];
  7363. },
  7364. /**
  7365. * If the encountered String value is worthwhile, it is
  7366. * substituted by an identifier name to which that value is
  7367. * assigned.
  7368. * Applies to String values.
  7369. * @param {string} sStringValue The String value of the string
  7370. * literal encountered.
  7371. * @return {!Array} A syntactic code unit that is equivalent to
  7372. * the one encountered.
  7373. * @see TPrimitiveValue#nSaving
  7374. */
  7375. 'string': function(sStringValue) {
  7376. /**
  7377. * The prefixed representation String of the primitive value
  7378. * of the literal.
  7379. * @type {string}
  7380. */
  7381. var sPrefixed =
  7382. EValuePrefixes.S_STRING + sStringValue;
  7383. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  7384. sPrefixed) &&
  7385. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  7386. ['name',
  7387. oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
  7388. ['string', sStringValue];
  7389. }
  7390. },
  7391. /**
  7392. * Such data on what to consolidate within the range of source
  7393. * elements that is currently being considered that lead to the
  7394. * greatest known reduction of the number of the terminal symbols
  7395. * in comparison to the original source text.
  7396. * @type {!TSolution}
  7397. */
  7398. oSolutionBest = new TSolution(),
  7399. /**
  7400. * Data representing an ongoing attempt to find a better
  7401. * reduction of the number of the terminal symbols in comparison
  7402. * to the original source text than the best one that is
  7403. * currently known.
  7404. * @type {!TSolution}
  7405. * @see oSolutionBest
  7406. */
  7407. oSolutionCandidate = new TSolution(),
  7408. /**
  7409. * A record consisting of data about the range of source elements
  7410. * that is currently being examined.
  7411. * @type {!TSourceElementsData}
  7412. */
  7413. oSourceElementsData = new TSourceElementsData(),
  7414. /**
  7415. * Variable declarations for each primitive value that is to be
  7416. * consolidated within the elements.
  7417. * @type {!Array.<!Array>}
  7418. */
  7419. aVariableDeclarations = [],
  7420. /**
  7421. * Augments a list with a prefixed representation String.
  7422. * @param {!Array.<string>} aList A list that is to be augmented.
  7423. * @return {function(string)} A function that augments a list
  7424. * with a prefixed representation String.
  7425. */
  7426. cAugmentList = function(aList) {
  7427. /**
  7428. * @param {string} sPrefixed Prefixed representation String of
  7429. * a primitive value that could be consolidated within the
  7430. * elements.
  7431. */
  7432. var fLambda = function(sPrefixed) {
  7433. if (-1 === aList.indexOf(sPrefixed)) {
  7434. aList.push(sPrefixed);
  7435. }
  7436. };
  7437. return fLambda;
  7438. },
  7439. /**
  7440. * Adds the number of occurrences of a primitive value of a given
  7441. * category that could be consolidated in the source element with
  7442. * a given index to the count of occurrences of that primitive
  7443. * value within the range of source elements that is currently
  7444. * being considered.
  7445. * @param {number} nPosition The index (in the source text order)
  7446. * of a source element.
  7447. * @param {number} nCategory The category of the primary
  7448. * expression from which the primitive value is derived.
  7449. * @return {function(string)} A function that performs the
  7450. * addition.
  7451. * @see cAddOccurrencesInCategory
  7452. */
  7453. cAddOccurrences = function(nPosition, nCategory) {
  7454. /**
  7455. * @param {string} sPrefixed The prefixed representation String
  7456. * of a primitive value.
  7457. */
  7458. var fLambda = function(sPrefixed) {
  7459. if (!oSourceElementsData.aCount[nCategory].hasOwnProperty(
  7460. sPrefixed)) {
  7461. oSourceElementsData.aCount[nCategory][sPrefixed] = 0;
  7462. }
  7463. oSourceElementsData.aCount[nCategory][sPrefixed] +=
  7464. aSourceElementsData[nPosition].aCount[nCategory][
  7465. sPrefixed];
  7466. };
  7467. return fLambda;
  7468. },
  7469. /**
  7470. * Adds the number of occurrences of each primitive value of a
  7471. * given category that could be consolidated in the source
  7472. * element with a given index to the count of occurrences of that
  7473. * primitive values within the range of source elements that is
  7474. * currently being considered.
  7475. * @param {number} nPosition The index (in the source text order)
  7476. * of a source element.
  7477. * @return {function(number)} A function that performs the
  7478. * addition.
  7479. * @see fAddOccurrences
  7480. */
  7481. cAddOccurrencesInCategory = function(nPosition) {
  7482. /**
  7483. * @param {number} nCategory The category of the primary
  7484. * expression from which the primitive value is derived.
  7485. */
  7486. var fLambda = function(nCategory) {
  7487. Object.keys(
  7488. aSourceElementsData[nPosition].aCount[nCategory]
  7489. ).forEach(cAddOccurrences(nPosition, nCategory));
  7490. };
  7491. return fLambda;
  7492. },
  7493. /**
  7494. * Adds the number of occurrences of each primitive value that
  7495. * could be consolidated in the source element with a given index
  7496. * to the count of occurrences of that primitive values within
  7497. * the range of source elements that is currently being
  7498. * considered.
  7499. * @param {number} nPosition The index (in the source text order)
  7500. * of a source element.
  7501. */
  7502. fAddOccurrences = function(nPosition) {
  7503. Object.keys(aSourceElementsData[nPosition].aCount).forEach(
  7504. cAddOccurrencesInCategory(nPosition));
  7505. },
  7506. /**
  7507. * Creates a variable declaration for a primitive value if that
  7508. * primitive value is to be consolidated within the elements.
  7509. * @param {string} sPrefixed Prefixed representation String of a
  7510. * primitive value that could be consolidated within the
  7511. * elements.
  7512. * @see aVariableDeclarations
  7513. */
  7514. cAugmentVariableDeclarations = function(sPrefixed) {
  7515. if (oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0) {
  7516. aVariableDeclarations.push([
  7517. oSolutionBest.oPrimitiveValues[sPrefixed].sName,
  7518. [0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC) ?
  7519. 'name' : 'string',
  7520. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length)]
  7521. ]);
  7522. }
  7523. },
  7524. /**
  7525. * Sorts primitive values with regard to the difference in the
  7526. * number of terminal symbols between the original source text
  7527. * and the one with those primitive values consolidated.
  7528. * @param {string} sPrefixed0 The prefixed representation String
  7529. * of the first of the two primitive values that are being
  7530. * compared.
  7531. * @param {string} sPrefixed1 The prefixed representation String
  7532. * of the second of the two primitive values that are being
  7533. * compared.
  7534. * @return {number}
  7535. * <dl>
  7536. * <dt>-1</dt>
  7537. * <dd>if the first primitive value must be placed before
  7538. * the other one,</dd>
  7539. * <dt>0</dt>
  7540. * <dd>if the first primitive value may be placed before
  7541. * the other one,</dd>
  7542. * <dt>1</dt>
  7543. * <dd>if the first primitive value must not be placed
  7544. * before the other one.</dd>
  7545. * </dl>
  7546. * @see TSolution.oPrimitiveValues
  7547. */
  7548. cSortPrimitiveValues = function(sPrefixed0, sPrefixed1) {
  7549. /**
  7550. * The difference between:
  7551. * <ol>
  7552. * <li>the difference in the number of terminal symbols
  7553. * between the original source text and the one with the
  7554. * first primitive value consolidated, and</li>
  7555. * <li>the difference in the number of terminal symbols
  7556. * between the original source text and the one with the
  7557. * second primitive value consolidated.</li>
  7558. * </ol>
  7559. * @type {number}
  7560. */
  7561. var nDifference =
  7562. oSolutionCandidate.oPrimitiveValues[sPrefixed0].nSaving -
  7563. oSolutionCandidate.oPrimitiveValues[sPrefixed1].nSaving;
  7564. return nDifference > 0 ? -1 : nDifference < 0 ? 1 : 0;
  7565. },
  7566. /**
  7567. * Assigns an identifier name to a primitive value and calculates
  7568. * whether instances of that primitive value are worth
  7569. * consolidating.
  7570. * @param {string} sPrefixed The prefixed representation String
  7571. * of a primitive value that is being evaluated.
  7572. */
  7573. fEvaluatePrimitiveValue = function(sPrefixed) {
  7574. var _,
  7575. /**
  7576. * The index of the last mangled name.
  7577. * @type {number}
  7578. */
  7579. nIndex,
  7580. /**
  7581. * The representation String of the primitive value that is
  7582. * being evaluated.
  7583. * @type {string}
  7584. */
  7585. sName =
  7586. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length),
  7587. /**
  7588. * The number of source characters taken up by the
  7589. * representation String of the primitive value that is
  7590. * being evaluated.
  7591. * @type {number}
  7592. */
  7593. nLengthOriginal = sName.length,
  7594. /**
  7595. * The number of source characters taken up by the
  7596. * identifier name that could substitute the primitive
  7597. * value that is being evaluated.
  7598. * substituted.
  7599. * @type {number}
  7600. */
  7601. nLengthSubstitution,
  7602. /**
  7603. * The number of source characters taken up by by the
  7604. * representation String of the primitive value that is
  7605. * being evaluated when it is represented by a string
  7606. * literal.
  7607. * @type {number}
  7608. */
  7609. nLengthString = oProcessor.make_string(sName).length;
  7610. oSolutionCandidate.oPrimitiveValues[sPrefixed] =
  7611. new TPrimitiveValue();
  7612. do { // Find an identifier unused in this or any nested scope.
  7613. nIndex = oScope.cname;
  7614. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName =
  7615. oScope.next_mangled();
  7616. } while (-1 !== oSourceElementsData.aIdentifiers.indexOf(
  7617. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName));
  7618. nLengthSubstitution = oSolutionCandidate.oPrimitiveValues[
  7619. sPrefixed].sName.length;
  7620. if (0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC)) {
  7621. // foo:null, or foo:null;
  7622. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  7623. nLengthSubstitution + nLengthOriginal +
  7624. oWeights.N_VARIABLE_DECLARATION;
  7625. // null vs foo
  7626. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  7627. oSourceElementsData.aCount[
  7628. EPrimaryExpressionCategories.
  7629. N_NULL_AND_BOOLEAN_LITERALS][sPrefixed] *
  7630. (nLengthOriginal - nLengthSubstitution);
  7631. } else {
  7632. // foo:'fromCharCode';
  7633. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  7634. nLengthSubstitution + nLengthString +
  7635. oWeights.N_VARIABLE_DECLARATION;
  7636. // .fromCharCode vs [foo]
  7637. if (oSourceElementsData.aCount[
  7638. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  7639. ].hasOwnProperty(sPrefixed)) {
  7640. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  7641. oSourceElementsData.aCount[
  7642. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  7643. ][sPrefixed] *
  7644. (nLengthOriginal - nLengthSubstitution -
  7645. oWeights.N_PROPERTY_ACCESSOR);
  7646. }
  7647. // 'fromCharCode' vs foo
  7648. if (oSourceElementsData.aCount[
  7649. EPrimaryExpressionCategories.N_STRING_LITERALS
  7650. ].hasOwnProperty(sPrefixed)) {
  7651. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  7652. oSourceElementsData.aCount[
  7653. EPrimaryExpressionCategories.N_STRING_LITERALS
  7654. ][sPrefixed] *
  7655. (nLengthString - nLengthSubstitution);
  7656. }
  7657. }
  7658. if (oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving >
  7659. 0) {
  7660. oSolutionCandidate.nSavings +=
  7661. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving;
  7662. } else {
  7663. oScope.cname = nIndex; // Free the identifier name.
  7664. }
  7665. },
  7666. /**
  7667. * Adds a variable declaration to an existing variable statement.
  7668. * @param {!Array} aVariableDeclaration A variable declaration
  7669. * with an initialiser.
  7670. */
  7671. cAddVariableDeclaration = function(aVariableDeclaration) {
  7672. (/** @type {!Array} */ oSourceElements[nFrom][1]).unshift(
  7673. aVariableDeclaration);
  7674. };
  7675. if (nFrom > nTo) {
  7676. return;
  7677. }
  7678. // If the range is a closure, reuse the closure.
  7679. if (nFrom === nTo &&
  7680. 'stat' === oSourceElements[nFrom][0] &&
  7681. 'call' === oSourceElements[nFrom][1][0] &&
  7682. 'function' === oSourceElements[nFrom][1][1][0]) {
  7683. fExamineSyntacticCodeUnit(oSourceElements[nFrom][1][1]);
  7684. return;
  7685. }
  7686. // Create a list of all derived primitive values within the range.
  7687. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  7688. aSourceElementsData[nPosition].aPrimitiveValues.forEach(
  7689. cAugmentList(oSourceElementsData.aPrimitiveValues));
  7690. }
  7691. if (0 === oSourceElementsData.aPrimitiveValues.length) {
  7692. return;
  7693. }
  7694. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  7695. // Add the number of occurrences to the total count.
  7696. fAddOccurrences(nPosition);
  7697. // Add identifiers of this or any nested scope to the list.
  7698. aSourceElementsData[nPosition].aIdentifiers.forEach(
  7699. cAugmentList(oSourceElementsData.aIdentifiers));
  7700. }
  7701. // Distribute identifier names among derived primitive values.
  7702. do { // If there was any progress, find a better distribution.
  7703. oSolutionBest = oSolutionCandidate;
  7704. if (Object.keys(oSolutionCandidate.oPrimitiveValues).length > 0) {
  7705. // Sort primitive values descending by their worthwhileness.
  7706. oSourceElementsData.aPrimitiveValues.sort(cSortPrimitiveValues);
  7707. }
  7708. oSolutionCandidate = new TSolution();
  7709. oSourceElementsData.aPrimitiveValues.forEach(
  7710. fEvaluatePrimitiveValue);
  7711. oScope.cname = nIndex;
  7712. } while (oSolutionCandidate.nSavings > oSolutionBest.nSavings);
  7713. // Take the necessity of adding a variable statement into account.
  7714. if ('var' !== oSourceElements[nFrom][0]) {
  7715. oSolutionBest.nSavings -= oWeights.N_VARIABLE_STATEMENT_AFFIXATION;
  7716. }
  7717. if (bEnclose) {
  7718. // Take the necessity of forming a closure into account.
  7719. oSolutionBest.nSavings -= oWeights.N_CLOSURE;
  7720. }
  7721. if (oSolutionBest.nSavings > 0) {
  7722. // Create variable declarations suitable for UglifyJS.
  7723. Object.keys(oSolutionBest.oPrimitiveValues).forEach(
  7724. cAugmentVariableDeclarations);
  7725. // Rewrite expressions that contain worthwhile primitive values.
  7726. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  7727. oWalker = oProcessor.ast_walker();
  7728. oSourceElements[nPosition] =
  7729. oWalker.with_walkers(
  7730. oWalkersTransformers,
  7731. cContext(oWalker, oSourceElements[nPosition]));
  7732. }
  7733. if ('var' === oSourceElements[nFrom][0]) { // Reuse the statement.
  7734. (/** @type {!Array.<!Array>} */ aVariableDeclarations.reverse(
  7735. )).forEach(cAddVariableDeclaration);
  7736. } else { // Add a variable statement.
  7737. Array.prototype.splice.call(
  7738. oSourceElements,
  7739. nFrom,
  7740. 0,
  7741. ['var', aVariableDeclarations]);
  7742. nTo += 1;
  7743. }
  7744. if (bEnclose) {
  7745. // Add a closure.
  7746. Array.prototype.splice.call(
  7747. oSourceElements,
  7748. nFrom,
  7749. 0,
  7750. ['stat', ['call', ['function', null, [], []], []]]);
  7751. // Copy source elements into the closure.
  7752. for (nPosition = nTo + 1; nPosition > nFrom; nPosition -= 1) {
  7753. Array.prototype.unshift.call(
  7754. oSourceElements[nFrom][1][1][3],
  7755. oSourceElements[nPosition]);
  7756. }
  7757. // Remove source elements outside the closure.
  7758. Array.prototype.splice.call(
  7759. oSourceElements,
  7760. nFrom + 1,
  7761. nTo - nFrom + 1);
  7762. }
  7763. }
  7764. if (bEnclose) {
  7765. // Restore the availability of identifier names.
  7766. oScope.cname = nIndex;
  7767. }
  7768. };
  7769. oSourceElements = (/** @type {!TSyntacticCodeUnit} */
  7770. oSyntacticCodeUnit[bIsGlobal ? 1 : 3]);
  7771. if (0 === oSourceElements.length) {
  7772. return;
  7773. }
  7774. oScope = bIsGlobal ? oSyntacticCodeUnit.scope : oSourceElements.scope;
  7775. // Skip a Directive Prologue.
  7776. while (nAfterDirectivePrologue < oSourceElements.length &&
  7777. 'directive' === oSourceElements[nAfterDirectivePrologue][0]) {
  7778. nAfterDirectivePrologue += 1;
  7779. aSourceElementsData.push(null);
  7780. }
  7781. if (oSourceElements.length === nAfterDirectivePrologue) {
  7782. return;
  7783. }
  7784. for (nPosition = nAfterDirectivePrologue;
  7785. nPosition < oSourceElements.length;
  7786. nPosition += 1) {
  7787. oSourceElementData = new TSourceElementsData();
  7788. oWalker = oProcessor.ast_walker();
  7789. // Classify a source element.
  7790. // Find its derived primitive values and count their occurrences.
  7791. // Find all identifiers used (including nested scopes).
  7792. oWalker.with_walkers(
  7793. oWalkers.oSurveySourceElement,
  7794. cContext(oWalker, oSourceElements[nPosition]));
  7795. // Establish whether the scope is still wholly examinable.
  7796. bIsWhollyExaminable = bIsWhollyExaminable &&
  7797. ESourceElementCategories.N_WITH !== oSourceElementData.nCategory &&
  7798. ESourceElementCategories.N_EVAL !== oSourceElementData.nCategory;
  7799. aSourceElementsData.push(oSourceElementData);
  7800. }
  7801. if (bIsWhollyExaminable) { // Examine the whole scope.
  7802. fExamineSourceElements(
  7803. nAfterDirectivePrologue,
  7804. oSourceElements.length - 1,
  7805. false);
  7806. } else { // Examine unexcluded ranges of source elements.
  7807. for (nPosition = oSourceElements.length - 1;
  7808. nPosition >= nAfterDirectivePrologue;
  7809. nPosition -= 1) {
  7810. oSourceElementData = (/** @type {!TSourceElementsData} */
  7811. aSourceElementsData[nPosition]);
  7812. if (ESourceElementCategories.N_OTHER ===
  7813. oSourceElementData.nCategory) {
  7814. if ('undefined' === typeof nTo) {
  7815. nTo = nPosition; // Indicate the end of a range.
  7816. }
  7817. // Examine the range if it immediately follows a Directive Prologue.
  7818. if (nPosition === nAfterDirectivePrologue) {
  7819. fExamineSourceElements(nPosition, nTo, true);
  7820. }
  7821. } else {
  7822. if ('undefined' !== typeof nTo) {
  7823. // Examine the range that immediately follows this source element.
  7824. fExamineSourceElements(nPosition + 1, nTo, true);
  7825. nTo = void 0; // Obliterate the range.
  7826. }
  7827. // Examine nested functions.
  7828. oWalker = oProcessor.ast_walker();
  7829. oWalker.with_walkers(
  7830. oWalkers.oExamineFunctions,
  7831. cContext(oWalker, oSourceElements[nPosition]));
  7832. }
  7833. }
  7834. }
  7835. }(oAbstractSyntaxTree = oProcessor.ast_add_scope(oAbstractSyntaxTree)));
  7836. return oAbstractSyntaxTree;
  7837. };
  7838. /*jshint sub:false */
  7839. /* Local Variables: */
  7840. /* mode: js */
  7841. /* coding: utf-8 */
  7842. /* indent-tabs-mode: nil */
  7843. /* tab-width: 2 */
  7844. /* End: */
  7845. /* vim: set ft=javascript fenc=utf-8 et ts=2 sts=2 sw=2: */
  7846. /* :mode=javascript:noTabs=true:tabSize=2:indentSize=2:deepIndent=true: */
  7847. });
  7848. define('uglifyjs/parse-js', ["exports"], function(exports) {
  7849. /***********************************************************************
  7850. A JavaScript tokenizer / parser / beautifier / compressor.
  7851. This version is suitable for Node.js. With minimal changes (the
  7852. exports stuff) it should work on any JS platform.
  7853. This file contains the tokenizer/parser. It is a port to JavaScript
  7854. of parse-js [1], a JavaScript parser library written in Common Lisp
  7855. by Marijn Haverbeke. Thank you Marijn!
  7856. [1] http://marijn.haverbeke.nl/parse-js/
  7857. Exported functions:
  7858. - tokenizer(code) -- returns a function. Call the returned
  7859. function to fetch the next token.
  7860. - parse(code) -- returns an AST of the given JavaScript code.
  7861. -------------------------------- (C) ---------------------------------
  7862. Author: Mihai Bazon
  7863. <mihai.bazon@gmail.com>
  7864. http://mihai.bazon.net/blog
  7865. Distributed under the BSD license:
  7866. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  7867. Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  7868. Redistribution and use in source and binary forms, with or without
  7869. modification, are permitted provided that the following conditions
  7870. are met:
  7871. * Redistributions of source code must retain the above
  7872. copyright notice, this list of conditions and the following
  7873. disclaimer.
  7874. * Redistributions in binary form must reproduce the above
  7875. copyright notice, this list of conditions and the following
  7876. disclaimer in the documentation and/or other materials
  7877. provided with the distribution.
  7878. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  7879. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  7880. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  7881. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  7882. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  7883. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  7884. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  7885. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7886. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  7887. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  7888. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  7889. SUCH DAMAGE.
  7890. ***********************************************************************/
  7891. /* -----[ Tokenizer (constants) ]----- */
  7892. var KEYWORDS = array_to_hash([
  7893. "break",
  7894. "case",
  7895. "catch",
  7896. "const",
  7897. "continue",
  7898. "debugger",
  7899. "default",
  7900. "delete",
  7901. "do",
  7902. "else",
  7903. "finally",
  7904. "for",
  7905. "function",
  7906. "if",
  7907. "in",
  7908. "instanceof",
  7909. "new",
  7910. "return",
  7911. "switch",
  7912. "throw",
  7913. "try",
  7914. "typeof",
  7915. "var",
  7916. "void",
  7917. "while",
  7918. "with"
  7919. ]);
  7920. var RESERVED_WORDS = array_to_hash([
  7921. "abstract",
  7922. "boolean",
  7923. "byte",
  7924. "char",
  7925. "class",
  7926. "double",
  7927. "enum",
  7928. "export",
  7929. "extends",
  7930. "final",
  7931. "float",
  7932. "goto",
  7933. "implements",
  7934. "import",
  7935. "int",
  7936. "interface",
  7937. "long",
  7938. "native",
  7939. "package",
  7940. "private",
  7941. "protected",
  7942. "public",
  7943. "short",
  7944. "static",
  7945. "super",
  7946. "synchronized",
  7947. "throws",
  7948. "transient",
  7949. "volatile"
  7950. ]);
  7951. var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
  7952. "return",
  7953. "new",
  7954. "delete",
  7955. "throw",
  7956. "else",
  7957. "case"
  7958. ]);
  7959. var KEYWORDS_ATOM = array_to_hash([
  7960. "false",
  7961. "null",
  7962. "true",
  7963. "undefined"
  7964. ]);
  7965. var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
  7966. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  7967. var RE_OCT_NUMBER = /^0[0-7]+$/;
  7968. var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
  7969. var OPERATORS = array_to_hash([
  7970. "in",
  7971. "instanceof",
  7972. "typeof",
  7973. "new",
  7974. "void",
  7975. "delete",
  7976. "++",
  7977. "--",
  7978. "+",
  7979. "-",
  7980. "!",
  7981. "~",
  7982. "&",
  7983. "|",
  7984. "^",
  7985. "*",
  7986. "/",
  7987. "%",
  7988. ">>",
  7989. "<<",
  7990. ">>>",
  7991. "<",
  7992. ">",
  7993. "<=",
  7994. ">=",
  7995. "==",
  7996. "===",
  7997. "!=",
  7998. "!==",
  7999. "?",
  8000. "=",
  8001. "+=",
  8002. "-=",
  8003. "/=",
  8004. "*=",
  8005. "%=",
  8006. ">>=",
  8007. "<<=",
  8008. ">>>=",
  8009. "|=",
  8010. "^=",
  8011. "&=",
  8012. "&&",
  8013. "||"
  8014. ]);
  8015. 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"));
  8016. var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:"));
  8017. var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
  8018. var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
  8019. /* -----[ Tokenizer ]----- */
  8020. var UNICODE = { // Unicode 6.1
  8021. 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]"),
  8022. 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]"),
  8023. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"),
  8024. 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]")
  8025. };
  8026. function is_letter(ch) {
  8027. return UNICODE.letter.test(ch);
  8028. };
  8029. function is_digit(ch) {
  8030. ch = ch.charCodeAt(0);
  8031. return ch >= 48 && ch <= 57;
  8032. };
  8033. function is_unicode_digit(ch) {
  8034. return UNICODE.digit.test(ch);
  8035. }
  8036. function is_alphanumeric_char(ch) {
  8037. return is_digit(ch) || is_letter(ch);
  8038. };
  8039. function is_unicode_combining_mark(ch) {
  8040. return UNICODE.combining_mark.test(ch);
  8041. };
  8042. function is_unicode_connector_punctuation(ch) {
  8043. return UNICODE.connector_punctuation.test(ch);
  8044. };
  8045. function is_identifier_start(ch) {
  8046. return ch == "$" || ch == "_" || is_letter(ch);
  8047. };
  8048. function is_identifier_char(ch) {
  8049. return is_identifier_start(ch)
  8050. || is_unicode_combining_mark(ch)
  8051. || is_unicode_digit(ch)
  8052. || is_unicode_connector_punctuation(ch)
  8053. || ch == "\u200c" // zero-width non-joiner <ZWNJ>
  8054. || ch == "\u200d" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  8055. ;
  8056. };
  8057. function parse_js_number(num) {
  8058. if (RE_HEX_NUMBER.test(num)) {
  8059. return parseInt(num.substr(2), 16);
  8060. } else if (RE_OCT_NUMBER.test(num)) {
  8061. return parseInt(num.substr(1), 8);
  8062. } else if (RE_DEC_NUMBER.test(num)) {
  8063. return parseFloat(num);
  8064. }
  8065. };
  8066. function JS_Parse_Error(message, line, col, pos) {
  8067. this.message = message;
  8068. this.line = line + 1;
  8069. this.col = col + 1;
  8070. this.pos = pos + 1;
  8071. this.stack = new Error().stack;
  8072. };
  8073. JS_Parse_Error.prototype.toString = function() {
  8074. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  8075. };
  8076. function js_error(message, line, col, pos) {
  8077. throw new JS_Parse_Error(message, line, col, pos);
  8078. };
  8079. function is_token(token, type, val) {
  8080. return token.type == type && (val == null || token.value == val);
  8081. };
  8082. var EX_EOF = {};
  8083. function tokenizer($TEXT) {
  8084. var S = {
  8085. text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
  8086. pos : 0,
  8087. tokpos : 0,
  8088. line : 0,
  8089. tokline : 0,
  8090. col : 0,
  8091. tokcol : 0,
  8092. newline_before : false,
  8093. regex_allowed : false,
  8094. comments_before : []
  8095. };
  8096. function peek() { return S.text.charAt(S.pos); };
  8097. function next(signal_eof, in_string) {
  8098. var ch = S.text.charAt(S.pos++);
  8099. if (signal_eof && !ch)
  8100. throw EX_EOF;
  8101. if (ch == "\n") {
  8102. S.newline_before = S.newline_before || !in_string;
  8103. ++S.line;
  8104. S.col = 0;
  8105. } else {
  8106. ++S.col;
  8107. }
  8108. return ch;
  8109. };
  8110. function eof() {
  8111. return !S.peek();
  8112. };
  8113. function find(what, signal_eof) {
  8114. var pos = S.text.indexOf(what, S.pos);
  8115. if (signal_eof && pos == -1) throw EX_EOF;
  8116. return pos;
  8117. };
  8118. function start_token() {
  8119. S.tokline = S.line;
  8120. S.tokcol = S.col;
  8121. S.tokpos = S.pos;
  8122. };
  8123. function token(type, value, is_comment) {
  8124. S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
  8125. (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
  8126. (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
  8127. var ret = {
  8128. type : type,
  8129. value : value,
  8130. line : S.tokline,
  8131. col : S.tokcol,
  8132. pos : S.tokpos,
  8133. endpos : S.pos,
  8134. nlb : S.newline_before
  8135. };
  8136. if (!is_comment) {
  8137. ret.comments_before = S.comments_before;
  8138. S.comments_before = [];
  8139. // make note of any newlines in the comments that came before
  8140. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  8141. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  8142. }
  8143. }
  8144. S.newline_before = false;
  8145. return ret;
  8146. };
  8147. function skip_whitespace() {
  8148. while (HOP(WHITESPACE_CHARS, peek()))
  8149. next();
  8150. };
  8151. function read_while(pred) {
  8152. var ret = "", ch = peek(), i = 0;
  8153. while (ch && pred(ch, i++)) {
  8154. ret += next();
  8155. ch = peek();
  8156. }
  8157. return ret;
  8158. };
  8159. function parse_error(err) {
  8160. js_error(err, S.tokline, S.tokcol, S.tokpos);
  8161. };
  8162. function read_num(prefix) {
  8163. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  8164. var num = read_while(function(ch, i){
  8165. if (ch == "x" || ch == "X") {
  8166. if (has_x) return false;
  8167. return has_x = true;
  8168. }
  8169. if (!has_x && (ch == "E" || ch == "e")) {
  8170. if (has_e) return false;
  8171. return has_e = after_e = true;
  8172. }
  8173. if (ch == "-") {
  8174. if (after_e || (i == 0 && !prefix)) return true;
  8175. return false;
  8176. }
  8177. if (ch == "+") return after_e;
  8178. after_e = false;
  8179. if (ch == ".") {
  8180. if (!has_dot && !has_x && !has_e)
  8181. return has_dot = true;
  8182. return false;
  8183. }
  8184. return is_alphanumeric_char(ch);
  8185. });
  8186. if (prefix)
  8187. num = prefix + num;
  8188. var valid = parse_js_number(num);
  8189. if (!isNaN(valid)) {
  8190. return token("num", valid);
  8191. } else {
  8192. parse_error("Invalid syntax: " + num);
  8193. }
  8194. };
  8195. function read_escaped_char(in_string) {
  8196. var ch = next(true, in_string);
  8197. switch (ch) {
  8198. case "n" : return "\n";
  8199. case "r" : return "\r";
  8200. case "t" : return "\t";
  8201. case "b" : return "\b";
  8202. case "v" : return "\u000b";
  8203. case "f" : return "\f";
  8204. case "0" : return "\0";
  8205. case "x" : return String.fromCharCode(hex_bytes(2));
  8206. case "u" : return String.fromCharCode(hex_bytes(4));
  8207. case "\n": return "";
  8208. default : return ch;
  8209. }
  8210. };
  8211. function hex_bytes(n) {
  8212. var num = 0;
  8213. for (; n > 0; --n) {
  8214. var digit = parseInt(next(true), 16);
  8215. if (isNaN(digit))
  8216. parse_error("Invalid hex-character pattern in string");
  8217. num = (num << 4) | digit;
  8218. }
  8219. return num;
  8220. };
  8221. function read_string() {
  8222. return with_eof_error("Unterminated string constant", function(){
  8223. var quote = next(), ret = "";
  8224. for (;;) {
  8225. var ch = next(true);
  8226. if (ch == "\\") {
  8227. // read OctalEscapeSequence (XXX: deprecated if "strict mode")
  8228. // https://github.com/mishoo/UglifyJS/issues/178
  8229. var octal_len = 0, first = null;
  8230. ch = read_while(function(ch){
  8231. if (ch >= "0" && ch <= "7") {
  8232. if (!first) {
  8233. first = ch;
  8234. return ++octal_len;
  8235. }
  8236. else if (first <= "3" && octal_len <= 2) return ++octal_len;
  8237. else if (first >= "4" && octal_len <= 1) return ++octal_len;
  8238. }
  8239. return false;
  8240. });
  8241. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
  8242. else ch = read_escaped_char(true);
  8243. }
  8244. else if (ch == quote) break;
  8245. else if (ch == "\n") throw EX_EOF;
  8246. ret += ch;
  8247. }
  8248. return token("string", ret);
  8249. });
  8250. };
  8251. function read_line_comment() {
  8252. next();
  8253. var i = find("\n"), ret;
  8254. if (i == -1) {
  8255. ret = S.text.substr(S.pos);
  8256. S.pos = S.text.length;
  8257. } else {
  8258. ret = S.text.substring(S.pos, i);
  8259. S.pos = i;
  8260. }
  8261. return token("comment1", ret, true);
  8262. };
  8263. function read_multiline_comment() {
  8264. next();
  8265. return with_eof_error("Unterminated multiline comment", function(){
  8266. var i = find("*/", true),
  8267. text = S.text.substring(S.pos, i);
  8268. S.pos = i + 2;
  8269. S.line += text.split("\n").length - 1;
  8270. S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  8271. // https://github.com/mishoo/UglifyJS/issues/#issue/100
  8272. if (/^@cc_on/i.test(text)) {
  8273. warn("WARNING: at line " + S.line);
  8274. warn("*** Found \"conditional comment\": " + text);
  8275. warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
  8276. }
  8277. return token("comment2", text, true);
  8278. });
  8279. };
  8280. function read_name() {
  8281. var backslash = false, name = "", ch, escaped = false, hex;
  8282. while ((ch = peek()) != null) {
  8283. if (!backslash) {
  8284. if (ch == "\\") escaped = backslash = true, next();
  8285. else if (is_identifier_char(ch)) name += next();
  8286. else break;
  8287. }
  8288. else {
  8289. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  8290. ch = read_escaped_char();
  8291. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  8292. name += ch;
  8293. backslash = false;
  8294. }
  8295. }
  8296. if (HOP(KEYWORDS, name) && escaped) {
  8297. hex = name.charCodeAt(0).toString(16).toUpperCase();
  8298. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  8299. }
  8300. return name;
  8301. };
  8302. function read_regexp(regexp) {
  8303. return with_eof_error("Unterminated regular expression", function(){
  8304. var prev_backslash = false, ch, in_class = false;
  8305. while ((ch = next(true))) if (prev_backslash) {
  8306. regexp += "\\" + ch;
  8307. prev_backslash = false;
  8308. } else if (ch == "[") {
  8309. in_class = true;
  8310. regexp += ch;
  8311. } else if (ch == "]" && in_class) {
  8312. in_class = false;
  8313. regexp += ch;
  8314. } else if (ch == "/" && !in_class) {
  8315. break;
  8316. } else if (ch == "\\") {
  8317. prev_backslash = true;
  8318. } else {
  8319. regexp += ch;
  8320. }
  8321. var mods = read_name();
  8322. return token("regexp", [ regexp, mods ]);
  8323. });
  8324. };
  8325. function read_operator(prefix) {
  8326. function grow(op) {
  8327. if (!peek()) return op;
  8328. var bigger = op + peek();
  8329. if (HOP(OPERATORS, bigger)) {
  8330. next();
  8331. return grow(bigger);
  8332. } else {
  8333. return op;
  8334. }
  8335. };
  8336. return token("operator", grow(prefix || next()));
  8337. };
  8338. function handle_slash() {
  8339. next();
  8340. var regex_allowed = S.regex_allowed;
  8341. switch (peek()) {
  8342. case "/":
  8343. S.comments_before.push(read_line_comment());
  8344. S.regex_allowed = regex_allowed;
  8345. return next_token();
  8346. case "*":
  8347. S.comments_before.push(read_multiline_comment());
  8348. S.regex_allowed = regex_allowed;
  8349. return next_token();
  8350. }
  8351. return S.regex_allowed ? read_regexp("") : read_operator("/");
  8352. };
  8353. function handle_dot() {
  8354. next();
  8355. return is_digit(peek())
  8356. ? read_num(".")
  8357. : token("punc", ".");
  8358. };
  8359. function read_word() {
  8360. var word = read_name();
  8361. return !HOP(KEYWORDS, word)
  8362. ? token("name", word)
  8363. : HOP(OPERATORS, word)
  8364. ? token("operator", word)
  8365. : HOP(KEYWORDS_ATOM, word)
  8366. ? token("atom", word)
  8367. : token("keyword", word);
  8368. };
  8369. function with_eof_error(eof_error, cont) {
  8370. try {
  8371. return cont();
  8372. } catch(ex) {
  8373. if (ex === EX_EOF) parse_error(eof_error);
  8374. else throw ex;
  8375. }
  8376. };
  8377. function next_token(force_regexp) {
  8378. if (force_regexp != null)
  8379. return read_regexp(force_regexp);
  8380. skip_whitespace();
  8381. start_token();
  8382. var ch = peek();
  8383. if (!ch) return token("eof");
  8384. if (is_digit(ch)) return read_num();
  8385. if (ch == '"' || ch == "'") return read_string();
  8386. if (HOP(PUNC_CHARS, ch)) return token("punc", next());
  8387. if (ch == ".") return handle_dot();
  8388. if (ch == "/") return handle_slash();
  8389. if (HOP(OPERATOR_CHARS, ch)) return read_operator();
  8390. if (ch == "\\" || is_identifier_start(ch)) return read_word();
  8391. parse_error("Unexpected character '" + ch + "'");
  8392. };
  8393. next_token.context = function(nc) {
  8394. if (nc) S = nc;
  8395. return S;
  8396. };
  8397. return next_token;
  8398. };
  8399. /* -----[ Parser (constants) ]----- */
  8400. var UNARY_PREFIX = array_to_hash([
  8401. "typeof",
  8402. "void",
  8403. "delete",
  8404. "--",
  8405. "++",
  8406. "!",
  8407. "~",
  8408. "-",
  8409. "+"
  8410. ]);
  8411. var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
  8412. var ASSIGNMENT = (function(a, ret, i){
  8413. while (i < a.length) {
  8414. ret[a[i]] = a[i].substr(0, a[i].length - 1);
  8415. i++;
  8416. }
  8417. return ret;
  8418. })(
  8419. ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
  8420. { "=": true },
  8421. 0
  8422. );
  8423. var PRECEDENCE = (function(a, ret){
  8424. for (var i = 0, n = 1; i < a.length; ++i, ++n) {
  8425. var b = a[i];
  8426. for (var j = 0; j < b.length; ++j) {
  8427. ret[b[j]] = n;
  8428. }
  8429. }
  8430. return ret;
  8431. })(
  8432. [
  8433. ["||"],
  8434. ["&&"],
  8435. ["|"],
  8436. ["^"],
  8437. ["&"],
  8438. ["==", "===", "!=", "!=="],
  8439. ["<", ">", "<=", ">=", "in", "instanceof"],
  8440. [">>", "<<", ">>>"],
  8441. ["+", "-"],
  8442. ["*", "/", "%"]
  8443. ],
  8444. {}
  8445. );
  8446. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  8447. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  8448. /* -----[ Parser ]----- */
  8449. function NodeWithToken(str, start, end) {
  8450. this.name = str;
  8451. this.start = start;
  8452. this.end = end;
  8453. };
  8454. NodeWithToken.prototype.toString = function() { return this.name; };
  8455. function parse($TEXT, exigent_mode, embed_tokens) {
  8456. var S = {
  8457. input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT,
  8458. token : null,
  8459. prev : null,
  8460. peeked : null,
  8461. in_function : 0,
  8462. in_directives : true,
  8463. in_loop : 0,
  8464. labels : []
  8465. };
  8466. S.token = next();
  8467. function is(type, value) {
  8468. return is_token(S.token, type, value);
  8469. };
  8470. function peek() { return S.peeked || (S.peeked = S.input()); };
  8471. function next() {
  8472. S.prev = S.token;
  8473. if (S.peeked) {
  8474. S.token = S.peeked;
  8475. S.peeked = null;
  8476. } else {
  8477. S.token = S.input();
  8478. }
  8479. S.in_directives = S.in_directives && (
  8480. S.token.type == "string" || is("punc", ";")
  8481. );
  8482. return S.token;
  8483. };
  8484. function prev() {
  8485. return S.prev;
  8486. };
  8487. function croak(msg, line, col, pos) {
  8488. var ctx = S.input.context();
  8489. js_error(msg,
  8490. line != null ? line : ctx.tokline,
  8491. col != null ? col : ctx.tokcol,
  8492. pos != null ? pos : ctx.tokpos);
  8493. };
  8494. function token_error(token, msg) {
  8495. croak(msg, token.line, token.col);
  8496. };
  8497. function unexpected(token) {
  8498. if (token == null)
  8499. token = S.token;
  8500. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  8501. };
  8502. function expect_token(type, val) {
  8503. if (is(type, val)) {
  8504. return next();
  8505. }
  8506. token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type);
  8507. };
  8508. function expect(punc) { return expect_token("punc", punc); };
  8509. function can_insert_semicolon() {
  8510. return !exigent_mode && (
  8511. S.token.nlb || is("eof") || is("punc", "}")
  8512. );
  8513. };
  8514. function semicolon() {
  8515. if (is("punc", ";")) next();
  8516. else if (!can_insert_semicolon()) unexpected();
  8517. };
  8518. function as() {
  8519. return slice(arguments);
  8520. };
  8521. function parenthesised() {
  8522. expect("(");
  8523. var ex = expression();
  8524. expect(")");
  8525. return ex;
  8526. };
  8527. function add_tokens(str, start, end) {
  8528. return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
  8529. };
  8530. function maybe_embed_tokens(parser) {
  8531. if (embed_tokens) return function() {
  8532. var start = S.token;
  8533. var ast = parser.apply(this, arguments);
  8534. ast[0] = add_tokens(ast[0], start, prev());
  8535. return ast;
  8536. };
  8537. else return parser;
  8538. };
  8539. var statement = maybe_embed_tokens(function() {
  8540. if (is("operator", "/") || is("operator", "/=")) {
  8541. S.peeked = null;
  8542. S.token = S.input(S.token.value.substr(1)); // force regexp
  8543. }
  8544. switch (S.token.type) {
  8545. case "string":
  8546. var dir = S.in_directives, stat = simple_statement();
  8547. if (dir && stat[1][0] == "string" && !is("punc", ","))
  8548. return as("directive", stat[1][1]);
  8549. return stat;
  8550. case "num":
  8551. case "regexp":
  8552. case "operator":
  8553. case "atom":
  8554. return simple_statement();
  8555. case "name":
  8556. return is_token(peek(), "punc", ":")
  8557. ? labeled_statement(prog1(S.token.value, next, next))
  8558. : simple_statement();
  8559. case "punc":
  8560. switch (S.token.value) {
  8561. case "{":
  8562. return as("block", block_());
  8563. case "[":
  8564. case "(":
  8565. return simple_statement();
  8566. case ";":
  8567. next();
  8568. return as("block");
  8569. default:
  8570. unexpected();
  8571. }
  8572. case "keyword":
  8573. switch (prog1(S.token.value, next)) {
  8574. case "break":
  8575. return break_cont("break");
  8576. case "continue":
  8577. return break_cont("continue");
  8578. case "debugger":
  8579. semicolon();
  8580. return as("debugger");
  8581. case "do":
  8582. return (function(body){
  8583. expect_token("keyword", "while");
  8584. return as("do", prog1(parenthesised, semicolon), body);
  8585. })(in_loop(statement));
  8586. case "for":
  8587. return for_();
  8588. case "function":
  8589. return function_(true);
  8590. case "if":
  8591. return if_();
  8592. case "return":
  8593. if (S.in_function == 0)
  8594. croak("'return' outside of function");
  8595. return as("return",
  8596. is("punc", ";")
  8597. ? (next(), null)
  8598. : can_insert_semicolon()
  8599. ? null
  8600. : prog1(expression, semicolon));
  8601. case "switch":
  8602. return as("switch", parenthesised(), switch_block_());
  8603. case "throw":
  8604. if (S.token.nlb)
  8605. croak("Illegal newline after 'throw'");
  8606. return as("throw", prog1(expression, semicolon));
  8607. case "try":
  8608. return try_();
  8609. case "var":
  8610. return prog1(var_, semicolon);
  8611. case "const":
  8612. return prog1(const_, semicolon);
  8613. case "while":
  8614. return as("while", parenthesised(), in_loop(statement));
  8615. case "with":
  8616. return as("with", parenthesised(), statement());
  8617. default:
  8618. unexpected();
  8619. }
  8620. }
  8621. });
  8622. function labeled_statement(label) {
  8623. S.labels.push(label);
  8624. var start = S.token, stat = statement();
  8625. if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
  8626. unexpected(start);
  8627. S.labels.pop();
  8628. return as("label", label, stat);
  8629. };
  8630. function simple_statement() {
  8631. return as("stat", prog1(expression, semicolon));
  8632. };
  8633. function break_cont(type) {
  8634. var name;
  8635. if (!can_insert_semicolon()) {
  8636. name = is("name") ? S.token.value : null;
  8637. }
  8638. if (name != null) {
  8639. next();
  8640. if (!member(name, S.labels))
  8641. croak("Label " + name + " without matching loop or statement");
  8642. }
  8643. else if (S.in_loop == 0)
  8644. croak(type + " not inside a loop or switch");
  8645. semicolon();
  8646. return as(type, name);
  8647. };
  8648. function for_() {
  8649. expect("(");
  8650. var init = null;
  8651. if (!is("punc", ";")) {
  8652. init = is("keyword", "var")
  8653. ? (next(), var_(true))
  8654. : expression(true, true);
  8655. if (is("operator", "in")) {
  8656. if (init[0] == "var" && init[1].length > 1)
  8657. croak("Only one variable declaration allowed in for..in loop");
  8658. return for_in(init);
  8659. }
  8660. }
  8661. return regular_for(init);
  8662. };
  8663. function regular_for(init) {
  8664. expect(";");
  8665. var test = is("punc", ";") ? null : expression();
  8666. expect(";");
  8667. var step = is("punc", ")") ? null : expression();
  8668. expect(")");
  8669. return as("for", init, test, step, in_loop(statement));
  8670. };
  8671. function for_in(init) {
  8672. var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
  8673. next();
  8674. var obj = expression();
  8675. expect(")");
  8676. return as("for-in", init, lhs, obj, in_loop(statement));
  8677. };
  8678. var function_ = function(in_statement) {
  8679. var name = is("name") ? prog1(S.token.value, next) : null;
  8680. if (in_statement && !name)
  8681. unexpected();
  8682. expect("(");
  8683. return as(in_statement ? "defun" : "function",
  8684. name,
  8685. // arguments
  8686. (function(first, a){
  8687. while (!is("punc", ")")) {
  8688. if (first) first = false; else expect(",");
  8689. if (!is("name")) unexpected();
  8690. a.push(S.token.value);
  8691. next();
  8692. }
  8693. next();
  8694. return a;
  8695. })(true, []),
  8696. // body
  8697. (function(){
  8698. ++S.in_function;
  8699. var loop = S.in_loop;
  8700. S.in_directives = true;
  8701. S.in_loop = 0;
  8702. var a = block_();
  8703. --S.in_function;
  8704. S.in_loop = loop;
  8705. return a;
  8706. })());
  8707. };
  8708. function if_() {
  8709. var cond = parenthesised(), body = statement(), belse;
  8710. if (is("keyword", "else")) {
  8711. next();
  8712. belse = statement();
  8713. }
  8714. return as("if", cond, body, belse);
  8715. };
  8716. function block_() {
  8717. expect("{");
  8718. var a = [];
  8719. while (!is("punc", "}")) {
  8720. if (is("eof")) unexpected();
  8721. a.push(statement());
  8722. }
  8723. next();
  8724. return a;
  8725. };
  8726. var switch_block_ = curry(in_loop, function(){
  8727. expect("{");
  8728. var a = [], cur = null;
  8729. while (!is("punc", "}")) {
  8730. if (is("eof")) unexpected();
  8731. if (is("keyword", "case")) {
  8732. next();
  8733. cur = [];
  8734. a.push([ expression(), cur ]);
  8735. expect(":");
  8736. }
  8737. else if (is("keyword", "default")) {
  8738. next();
  8739. expect(":");
  8740. cur = [];
  8741. a.push([ null, cur ]);
  8742. }
  8743. else {
  8744. if (!cur) unexpected();
  8745. cur.push(statement());
  8746. }
  8747. }
  8748. next();
  8749. return a;
  8750. });
  8751. function try_() {
  8752. var body = block_(), bcatch, bfinally;
  8753. if (is("keyword", "catch")) {
  8754. next();
  8755. expect("(");
  8756. if (!is("name"))
  8757. croak("Name expected");
  8758. var name = S.token.value;
  8759. next();
  8760. expect(")");
  8761. bcatch = [ name, block_() ];
  8762. }
  8763. if (is("keyword", "finally")) {
  8764. next();
  8765. bfinally = block_();
  8766. }
  8767. if (!bcatch && !bfinally)
  8768. croak("Missing catch/finally blocks");
  8769. return as("try", body, bcatch, bfinally);
  8770. };
  8771. function vardefs(no_in) {
  8772. var a = [];
  8773. for (;;) {
  8774. if (!is("name"))
  8775. unexpected();
  8776. var name = S.token.value;
  8777. next();
  8778. if (is("operator", "=")) {
  8779. next();
  8780. a.push([ name, expression(false, no_in) ]);
  8781. } else {
  8782. a.push([ name ]);
  8783. }
  8784. if (!is("punc", ","))
  8785. break;
  8786. next();
  8787. }
  8788. return a;
  8789. };
  8790. function var_(no_in) {
  8791. return as("var", vardefs(no_in));
  8792. };
  8793. function const_() {
  8794. return as("const", vardefs());
  8795. };
  8796. function new_() {
  8797. var newexp = expr_atom(false), args;
  8798. if (is("punc", "(")) {
  8799. next();
  8800. args = expr_list(")");
  8801. } else {
  8802. args = [];
  8803. }
  8804. return subscripts(as("new", newexp, args), true);
  8805. };
  8806. var expr_atom = maybe_embed_tokens(function(allow_calls) {
  8807. if (is("operator", "new")) {
  8808. next();
  8809. return new_();
  8810. }
  8811. if (is("punc")) {
  8812. switch (S.token.value) {
  8813. case "(":
  8814. next();
  8815. return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
  8816. case "[":
  8817. next();
  8818. return subscripts(array_(), allow_calls);
  8819. case "{":
  8820. next();
  8821. return subscripts(object_(), allow_calls);
  8822. }
  8823. unexpected();
  8824. }
  8825. if (is("keyword", "function")) {
  8826. next();
  8827. return subscripts(function_(false), allow_calls);
  8828. }
  8829. if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
  8830. var atom = S.token.type == "regexp"
  8831. ? as("regexp", S.token.value[0], S.token.value[1])
  8832. : as(S.token.type, S.token.value);
  8833. return subscripts(prog1(atom, next), allow_calls);
  8834. }
  8835. unexpected();
  8836. });
  8837. function expr_list(closing, allow_trailing_comma, allow_empty) {
  8838. var first = true, a = [];
  8839. while (!is("punc", closing)) {
  8840. if (first) first = false; else expect(",");
  8841. if (allow_trailing_comma && is("punc", closing)) break;
  8842. if (is("punc", ",") && allow_empty) {
  8843. a.push([ "atom", "undefined" ]);
  8844. } else {
  8845. a.push(expression(false));
  8846. }
  8847. }
  8848. next();
  8849. return a;
  8850. };
  8851. function array_() {
  8852. return as("array", expr_list("]", !exigent_mode, true));
  8853. };
  8854. function object_() {
  8855. var first = true, a = [];
  8856. while (!is("punc", "}")) {
  8857. if (first) first = false; else expect(",");
  8858. if (!exigent_mode && is("punc", "}"))
  8859. // allow trailing comma
  8860. break;
  8861. var type = S.token.type;
  8862. var name = as_property_name();
  8863. if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
  8864. a.push([ as_name(), function_(false), name ]);
  8865. } else {
  8866. expect(":");
  8867. a.push([ name, expression(false) ]);
  8868. }
  8869. }
  8870. next();
  8871. return as("object", a);
  8872. };
  8873. function as_property_name() {
  8874. switch (S.token.type) {
  8875. case "num":
  8876. case "string":
  8877. return prog1(S.token.value, next);
  8878. }
  8879. return as_name();
  8880. };
  8881. function as_name() {
  8882. switch (S.token.type) {
  8883. case "name":
  8884. case "operator":
  8885. case "keyword":
  8886. case "atom":
  8887. return prog1(S.token.value, next);
  8888. default:
  8889. unexpected();
  8890. }
  8891. };
  8892. function subscripts(expr, allow_calls) {
  8893. if (is("punc", ".")) {
  8894. next();
  8895. return subscripts(as("dot", expr, as_name()), allow_calls);
  8896. }
  8897. if (is("punc", "[")) {
  8898. next();
  8899. return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
  8900. }
  8901. if (allow_calls && is("punc", "(")) {
  8902. next();
  8903. return subscripts(as("call", expr, expr_list(")")), true);
  8904. }
  8905. return expr;
  8906. };
  8907. function maybe_unary(allow_calls) {
  8908. if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
  8909. return make_unary("unary-prefix",
  8910. prog1(S.token.value, next),
  8911. maybe_unary(allow_calls));
  8912. }
  8913. var val = expr_atom(allow_calls);
  8914. while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
  8915. val = make_unary("unary-postfix", S.token.value, val);
  8916. next();
  8917. }
  8918. return val;
  8919. };
  8920. function make_unary(tag, op, expr) {
  8921. if ((op == "++" || op == "--") && !is_assignable(expr))
  8922. croak("Invalid use of " + op + " operator");
  8923. return as(tag, op, expr);
  8924. };
  8925. function expr_op(left, min_prec, no_in) {
  8926. var op = is("operator") ? S.token.value : null;
  8927. if (op && op == "in" && no_in) op = null;
  8928. var prec = op != null ? PRECEDENCE[op] : null;
  8929. if (prec != null && prec > min_prec) {
  8930. next();
  8931. var right = expr_op(maybe_unary(true), prec, no_in);
  8932. return expr_op(as("binary", op, left, right), min_prec, no_in);
  8933. }
  8934. return left;
  8935. };
  8936. function expr_ops(no_in) {
  8937. return expr_op(maybe_unary(true), 0, no_in);
  8938. };
  8939. function maybe_conditional(no_in) {
  8940. var expr = expr_ops(no_in);
  8941. if (is("operator", "?")) {
  8942. next();
  8943. var yes = expression(false);
  8944. expect(":");
  8945. return as("conditional", expr, yes, expression(false, no_in));
  8946. }
  8947. return expr;
  8948. };
  8949. function is_assignable(expr) {
  8950. if (!exigent_mode) return true;
  8951. switch (expr[0]+"") {
  8952. case "dot":
  8953. case "sub":
  8954. case "new":
  8955. case "call":
  8956. return true;
  8957. case "name":
  8958. return expr[1] != "this";
  8959. }
  8960. };
  8961. function maybe_assign(no_in) {
  8962. var left = maybe_conditional(no_in), val = S.token.value;
  8963. if (is("operator") && HOP(ASSIGNMENT, val)) {
  8964. if (is_assignable(left)) {
  8965. next();
  8966. return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
  8967. }
  8968. croak("Invalid assignment");
  8969. }
  8970. return left;
  8971. };
  8972. var expression = maybe_embed_tokens(function(commas, no_in) {
  8973. if (arguments.length == 0)
  8974. commas = true;
  8975. var expr = maybe_assign(no_in);
  8976. if (commas && is("punc", ",")) {
  8977. next();
  8978. return as("seq", expr, expression(true, no_in));
  8979. }
  8980. return expr;
  8981. });
  8982. function in_loop(cont) {
  8983. try {
  8984. ++S.in_loop;
  8985. return cont();
  8986. } finally {
  8987. --S.in_loop;
  8988. }
  8989. };
  8990. return as("toplevel", (function(a){
  8991. while (!is("eof"))
  8992. a.push(statement());
  8993. return a;
  8994. })([]));
  8995. };
  8996. /* -----[ Utilities ]----- */
  8997. function curry(f) {
  8998. var args = slice(arguments, 1);
  8999. return function() { return f.apply(this, args.concat(slice(arguments))); };
  9000. };
  9001. function prog1(ret) {
  9002. if (ret instanceof Function)
  9003. ret = ret();
  9004. for (var i = 1, n = arguments.length; --n > 0; ++i)
  9005. arguments[i]();
  9006. return ret;
  9007. };
  9008. function array_to_hash(a) {
  9009. var ret = {};
  9010. for (var i = 0; i < a.length; ++i)
  9011. ret[a[i]] = true;
  9012. return ret;
  9013. };
  9014. function slice(a, start) {
  9015. return Array.prototype.slice.call(a, start || 0);
  9016. };
  9017. function characters(str) {
  9018. return str.split("");
  9019. };
  9020. function member(name, array) {
  9021. for (var i = array.length; --i >= 0;)
  9022. if (array[i] == name)
  9023. return true;
  9024. return false;
  9025. };
  9026. function HOP(obj, prop) {
  9027. return Object.prototype.hasOwnProperty.call(obj, prop);
  9028. };
  9029. var warn = function() {};
  9030. /* -----[ Exports ]----- */
  9031. exports.tokenizer = tokenizer;
  9032. exports.parse = parse;
  9033. exports.slice = slice;
  9034. exports.curry = curry;
  9035. exports.member = member;
  9036. exports.array_to_hash = array_to_hash;
  9037. exports.PRECEDENCE = PRECEDENCE;
  9038. exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
  9039. exports.RESERVED_WORDS = RESERVED_WORDS;
  9040. exports.KEYWORDS = KEYWORDS;
  9041. exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
  9042. exports.OPERATORS = OPERATORS;
  9043. exports.is_alphanumeric_char = is_alphanumeric_char;
  9044. exports.is_identifier_start = is_identifier_start;
  9045. exports.is_identifier_char = is_identifier_char;
  9046. exports.set_logger = function(logger) {
  9047. warn = logger;
  9048. };
  9049. // Local variables:
  9050. // js-indent-level: 4
  9051. // End:
  9052. });define('uglifyjs/squeeze-more', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
  9053. var jsp = require("./parse-js"),
  9054. pro = require("./process"),
  9055. slice = jsp.slice,
  9056. member = jsp.member,
  9057. curry = jsp.curry,
  9058. MAP = pro.MAP,
  9059. PRECEDENCE = jsp.PRECEDENCE,
  9060. OPERATORS = jsp.OPERATORS;
  9061. function ast_squeeze_more(ast) {
  9062. var w = pro.ast_walker(), walk = w.walk, scope;
  9063. function with_scope(s, cont) {
  9064. var save = scope, ret;
  9065. scope = s;
  9066. ret = cont();
  9067. scope = save;
  9068. return ret;
  9069. };
  9070. function _lambda(name, args, body) {
  9071. return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  9072. };
  9073. return w.with_walkers({
  9074. "toplevel": function(body) {
  9075. return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
  9076. },
  9077. "function": _lambda,
  9078. "defun": _lambda,
  9079. "new": function(ctor, args) {
  9080. if (ctor[0] == "name") {
  9081. if (ctor[1] == "Array" && !scope.has("Array")) {
  9082. if (args.length != 1) {
  9083. return [ "array", args ];
  9084. } else {
  9085. return walk([ "call", [ "name", "Array" ], args ]);
  9086. }
  9087. } else if (ctor[1] == "Object" && !scope.has("Object")) {
  9088. if (!args.length) {
  9089. return [ "object", [] ];
  9090. } else {
  9091. return walk([ "call", [ "name", "Object" ], args ]);
  9092. }
  9093. } else if ((ctor[1] == "RegExp" || ctor[1] == "Function" || ctor[1] == "Error") && !scope.has(ctor[1])) {
  9094. return walk([ "call", [ "name", ctor[1] ], args]);
  9095. }
  9096. }
  9097. },
  9098. "call": function(expr, args) {
  9099. if (expr[0] == "dot" && expr[1][0] == "string" && args.length == 1
  9100. && (args[0][1] > 0 && expr[2] == "substring" || expr[2] == "substr")) {
  9101. return [ "call", [ "dot", expr[1], "slice"], args];
  9102. }
  9103. if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) {
  9104. // foo.toString() ==> foo+""
  9105. if (expr[1][0] == "string") return expr[1];
  9106. return [ "binary", "+", expr[1], [ "string", "" ]];
  9107. }
  9108. if (expr[0] == "name") {
  9109. if (expr[1] == "Array" && args.length != 1 && !scope.has("Array")) {
  9110. return [ "array", args ];
  9111. }
  9112. if (expr[1] == "Object" && !args.length && !scope.has("Object")) {
  9113. return [ "object", [] ];
  9114. }
  9115. if (expr[1] == "String" && !scope.has("String")) {
  9116. return [ "binary", "+", args[0], [ "string", "" ]];
  9117. }
  9118. }
  9119. }
  9120. }, function() {
  9121. return walk(pro.ast_add_scope(ast));
  9122. });
  9123. };
  9124. exports.ast_squeeze_more = ast_squeeze_more;
  9125. // Local variables:
  9126. // js-indent-level: 4
  9127. // End:
  9128. });
  9129. define('uglifyjs/process', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
  9130. /***********************************************************************
  9131. A JavaScript tokenizer / parser / beautifier / compressor.
  9132. This version is suitable for Node.js. With minimal changes (the
  9133. exports stuff) it should work on any JS platform.
  9134. This file implements some AST processors. They work on data built
  9135. by parse-js.
  9136. Exported functions:
  9137. - ast_mangle(ast, options) -- mangles the variable/function names
  9138. in the AST. Returns an AST.
  9139. - ast_squeeze(ast) -- employs various optimizations to make the
  9140. final generated code even smaller. Returns an AST.
  9141. - gen_code(ast, options) -- generates JS code from the AST. Pass
  9142. true (or an object, see the code for some options) as second
  9143. argument to get "pretty" (indented) code.
  9144. -------------------------------- (C) ---------------------------------
  9145. Author: Mihai Bazon
  9146. <mihai.bazon@gmail.com>
  9147. http://mihai.bazon.net/blog
  9148. Distributed under the BSD license:
  9149. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  9150. Redistribution and use in source and binary forms, with or without
  9151. modification, are permitted provided that the following conditions
  9152. are met:
  9153. * Redistributions of source code must retain the above
  9154. copyright notice, this list of conditions and the following
  9155. disclaimer.
  9156. * Redistributions in binary form must reproduce the above
  9157. copyright notice, this list of conditions and the following
  9158. disclaimer in the documentation and/or other materials
  9159. provided with the distribution.
  9160. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  9161. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  9162. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  9163. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  9164. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  9165. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  9166. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  9167. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9168. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  9169. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  9170. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  9171. SUCH DAMAGE.
  9172. ***********************************************************************/
  9173. var jsp = require("./parse-js"),
  9174. curry = jsp.curry,
  9175. slice = jsp.slice,
  9176. member = jsp.member,
  9177. is_identifier_char = jsp.is_identifier_char,
  9178. PRECEDENCE = jsp.PRECEDENCE,
  9179. OPERATORS = jsp.OPERATORS;
  9180. /* -----[ helper for AST traversal ]----- */
  9181. function ast_walker() {
  9182. function _vardefs(defs) {
  9183. return [ this[0], MAP(defs, function(def){
  9184. var a = [ def[0] ];
  9185. if (def.length > 1)
  9186. a[1] = walk(def[1]);
  9187. return a;
  9188. }) ];
  9189. };
  9190. function _block(statements) {
  9191. var out = [ this[0] ];
  9192. if (statements != null)
  9193. out.push(MAP(statements, walk));
  9194. return out;
  9195. };
  9196. var walkers = {
  9197. "string": function(str) {
  9198. return [ this[0], str ];
  9199. },
  9200. "num": function(num) {
  9201. return [ this[0], num ];
  9202. },
  9203. "name": function(name) {
  9204. return [ this[0], name ];
  9205. },
  9206. "toplevel": function(statements) {
  9207. return [ this[0], MAP(statements, walk) ];
  9208. },
  9209. "block": _block,
  9210. "splice": _block,
  9211. "var": _vardefs,
  9212. "const": _vardefs,
  9213. "try": function(t, c, f) {
  9214. return [
  9215. this[0],
  9216. MAP(t, walk),
  9217. c != null ? [ c[0], MAP(c[1], walk) ] : null,
  9218. f != null ? MAP(f, walk) : null
  9219. ];
  9220. },
  9221. "throw": function(expr) {
  9222. return [ this[0], walk(expr) ];
  9223. },
  9224. "new": function(ctor, args) {
  9225. return [ this[0], walk(ctor), MAP(args, walk) ];
  9226. },
  9227. "switch": function(expr, body) {
  9228. return [ this[0], walk(expr), MAP(body, function(branch){
  9229. return [ branch[0] ? walk(branch[0]) : null,
  9230. MAP(branch[1], walk) ];
  9231. }) ];
  9232. },
  9233. "break": function(label) {
  9234. return [ this[0], label ];
  9235. },
  9236. "continue": function(label) {
  9237. return [ this[0], label ];
  9238. },
  9239. "conditional": function(cond, t, e) {
  9240. return [ this[0], walk(cond), walk(t), walk(e) ];
  9241. },
  9242. "assign": function(op, lvalue, rvalue) {
  9243. return [ this[0], op, walk(lvalue), walk(rvalue) ];
  9244. },
  9245. "dot": function(expr) {
  9246. return [ this[0], walk(expr) ].concat(slice(arguments, 1));
  9247. },
  9248. "call": function(expr, args) {
  9249. return [ this[0], walk(expr), MAP(args, walk) ];
  9250. },
  9251. "function": function(name, args, body) {
  9252. return [ this[0], name, args.slice(), MAP(body, walk) ];
  9253. },
  9254. "debugger": function() {
  9255. return [ this[0] ];
  9256. },
  9257. "defun": function(name, args, body) {
  9258. return [ this[0], name, args.slice(), MAP(body, walk) ];
  9259. },
  9260. "if": function(conditional, t, e) {
  9261. return [ this[0], walk(conditional), walk(t), walk(e) ];
  9262. },
  9263. "for": function(init, cond, step, block) {
  9264. return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
  9265. },
  9266. "for-in": function(vvar, key, hash, block) {
  9267. return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
  9268. },
  9269. "while": function(cond, block) {
  9270. return [ this[0], walk(cond), walk(block) ];
  9271. },
  9272. "do": function(cond, block) {
  9273. return [ this[0], walk(cond), walk(block) ];
  9274. },
  9275. "return": function(expr) {
  9276. return [ this[0], walk(expr) ];
  9277. },
  9278. "binary": function(op, left, right) {
  9279. return [ this[0], op, walk(left), walk(right) ];
  9280. },
  9281. "unary-prefix": function(op, expr) {
  9282. return [ this[0], op, walk(expr) ];
  9283. },
  9284. "unary-postfix": function(op, expr) {
  9285. return [ this[0], op, walk(expr) ];
  9286. },
  9287. "sub": function(expr, subscript) {
  9288. return [ this[0], walk(expr), walk(subscript) ];
  9289. },
  9290. "object": function(props) {
  9291. return [ this[0], MAP(props, function(p){
  9292. return p.length == 2
  9293. ? [ p[0], walk(p[1]) ]
  9294. : [ p[0], walk(p[1]), p[2] ]; // get/set-ter
  9295. }) ];
  9296. },
  9297. "regexp": function(rx, mods) {
  9298. return [ this[0], rx, mods ];
  9299. },
  9300. "array": function(elements) {
  9301. return [ this[0], MAP(elements, walk) ];
  9302. },
  9303. "stat": function(stat) {
  9304. return [ this[0], walk(stat) ];
  9305. },
  9306. "seq": function() {
  9307. return [ this[0] ].concat(MAP(slice(arguments), walk));
  9308. },
  9309. "label": function(name, block) {
  9310. return [ this[0], name, walk(block) ];
  9311. },
  9312. "with": function(expr, block) {
  9313. return [ this[0], walk(expr), walk(block) ];
  9314. },
  9315. "atom": function(name) {
  9316. return [ this[0], name ];
  9317. },
  9318. "directive": function(dir) {
  9319. return [ this[0], dir ];
  9320. }
  9321. };
  9322. var user = {};
  9323. var stack = [];
  9324. function walk(ast) {
  9325. if (ast == null)
  9326. return null;
  9327. try {
  9328. stack.push(ast);
  9329. var type = ast[0];
  9330. var gen = user[type];
  9331. if (gen) {
  9332. var ret = gen.apply(ast, ast.slice(1));
  9333. if (ret != null)
  9334. return ret;
  9335. }
  9336. gen = walkers[type];
  9337. return gen.apply(ast, ast.slice(1));
  9338. } finally {
  9339. stack.pop();
  9340. }
  9341. };
  9342. function dive(ast) {
  9343. if (ast == null)
  9344. return null;
  9345. try {
  9346. stack.push(ast);
  9347. return walkers[ast[0]].apply(ast, ast.slice(1));
  9348. } finally {
  9349. stack.pop();
  9350. }
  9351. };
  9352. function with_walkers(walkers, cont){
  9353. var save = {}, i;
  9354. for (i in walkers) if (HOP(walkers, i)) {
  9355. save[i] = user[i];
  9356. user[i] = walkers[i];
  9357. }
  9358. var ret = cont();
  9359. for (i in save) if (HOP(save, i)) {
  9360. if (!save[i]) delete user[i];
  9361. else user[i] = save[i];
  9362. }
  9363. return ret;
  9364. };
  9365. return {
  9366. walk: walk,
  9367. dive: dive,
  9368. with_walkers: with_walkers,
  9369. parent: function() {
  9370. return stack[stack.length - 2]; // last one is current node
  9371. },
  9372. stack: function() {
  9373. return stack;
  9374. }
  9375. };
  9376. };
  9377. /* -----[ Scope and mangling ]----- */
  9378. function Scope(parent) {
  9379. this.names = {}; // names defined in this scope
  9380. this.mangled = {}; // mangled names (orig.name => mangled)
  9381. this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
  9382. this.cname = -1; // current mangled name
  9383. this.refs = {}; // names referenced from this scope
  9384. this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
  9385. this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
  9386. this.directives = []; // directives activated from this scope
  9387. this.parent = parent; // parent scope
  9388. this.children = []; // sub-scopes
  9389. if (parent) {
  9390. this.level = parent.level + 1;
  9391. parent.children.push(this);
  9392. } else {
  9393. this.level = 0;
  9394. }
  9395. };
  9396. function base54_digits() {
  9397. if (typeof DIGITS_OVERRIDE_FOR_TESTING != "undefined")
  9398. return DIGITS_OVERRIDE_FOR_TESTING;
  9399. else
  9400. return "etnrisouaflchpdvmgybwESxTNCkLAOM_DPHBjFIqRUzWXV$JKQGYZ0516372984";
  9401. }
  9402. var base54 = (function(){
  9403. var DIGITS = base54_digits();
  9404. return function(num) {
  9405. var ret = "", base = 54;
  9406. do {
  9407. ret += DIGITS.charAt(num % base);
  9408. num = Math.floor(num / base);
  9409. base = 64;
  9410. } while (num > 0);
  9411. return ret;
  9412. };
  9413. })();
  9414. Scope.prototype = {
  9415. has: function(name) {
  9416. for (var s = this; s; s = s.parent)
  9417. if (HOP(s.names, name))
  9418. return s;
  9419. },
  9420. has_mangled: function(mname) {
  9421. for (var s = this; s; s = s.parent)
  9422. if (HOP(s.rev_mangled, mname))
  9423. return s;
  9424. },
  9425. toJSON: function() {
  9426. return {
  9427. names: this.names,
  9428. uses_eval: this.uses_eval,
  9429. uses_with: this.uses_with
  9430. };
  9431. },
  9432. next_mangled: function() {
  9433. // we must be careful that the new mangled name:
  9434. //
  9435. // 1. doesn't shadow a mangled name from a parent
  9436. // scope, unless we don't reference the original
  9437. // name from this scope OR from any sub-scopes!
  9438. // This will get slow.
  9439. //
  9440. // 2. doesn't shadow an original name from a parent
  9441. // scope, in the event that the name is not mangled
  9442. // in the parent scope and we reference that name
  9443. // here OR IN ANY SUBSCOPES!
  9444. //
  9445. // 3. doesn't shadow a name that is referenced but not
  9446. // defined (possibly global defined elsewhere).
  9447. for (;;) {
  9448. var m = base54(++this.cname), prior;
  9449. // case 1.
  9450. prior = this.has_mangled(m);
  9451. if (prior && this.refs[prior.rev_mangled[m]] === prior)
  9452. continue;
  9453. // case 2.
  9454. prior = this.has(m);
  9455. if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
  9456. continue;
  9457. // case 3.
  9458. if (HOP(this.refs, m) && this.refs[m] == null)
  9459. continue;
  9460. // I got "do" once. :-/
  9461. if (!is_identifier(m))
  9462. continue;
  9463. return m;
  9464. }
  9465. },
  9466. set_mangle: function(name, m) {
  9467. this.rev_mangled[m] = name;
  9468. return this.mangled[name] = m;
  9469. },
  9470. get_mangled: function(name, newMangle) {
  9471. if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
  9472. var s = this.has(name);
  9473. if (!s) return name; // not in visible scope, no mangle
  9474. if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
  9475. if (!newMangle) return name; // not found and no mangling requested
  9476. return s.set_mangle(name, s.next_mangled());
  9477. },
  9478. references: function(name) {
  9479. return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];
  9480. },
  9481. define: function(name, type) {
  9482. if (name != null) {
  9483. if (type == "var" || !HOP(this.names, name))
  9484. this.names[name] = type || "var";
  9485. return name;
  9486. }
  9487. },
  9488. active_directive: function(dir) {
  9489. return member(dir, this.directives) || this.parent && this.parent.active_directive(dir);
  9490. }
  9491. };
  9492. function ast_add_scope(ast) {
  9493. var current_scope = null;
  9494. var w = ast_walker(), walk = w.walk;
  9495. var having_eval = [];
  9496. function with_new_scope(cont) {
  9497. current_scope = new Scope(current_scope);
  9498. current_scope.labels = new Scope();
  9499. var ret = current_scope.body = cont();
  9500. ret.scope = current_scope;
  9501. current_scope = current_scope.parent;
  9502. return ret;
  9503. };
  9504. function define(name, type) {
  9505. return current_scope.define(name, type);
  9506. };
  9507. function reference(name) {
  9508. current_scope.refs[name] = true;
  9509. };
  9510. function _lambda(name, args, body) {
  9511. var is_defun = this[0] == "defun";
  9512. return [ this[0], is_defun ? define(name, "defun") : name, args, with_new_scope(function(){
  9513. if (!is_defun) define(name, "lambda");
  9514. MAP(args, function(name){ define(name, "arg") });
  9515. return MAP(body, walk);
  9516. })];
  9517. };
  9518. function _vardefs(type) {
  9519. return function(defs) {
  9520. MAP(defs, function(d){
  9521. define(d[0], type);
  9522. if (d[1]) reference(d[0]);
  9523. });
  9524. };
  9525. };
  9526. function _breacont(label) {
  9527. if (label)
  9528. current_scope.labels.refs[label] = true;
  9529. };
  9530. return with_new_scope(function(){
  9531. // process AST
  9532. var ret = w.with_walkers({
  9533. "function": _lambda,
  9534. "defun": _lambda,
  9535. "label": function(name, stat) { current_scope.labels.define(name) },
  9536. "break": _breacont,
  9537. "continue": _breacont,
  9538. "with": function(expr, block) {
  9539. for (var s = current_scope; s; s = s.parent)
  9540. s.uses_with = true;
  9541. },
  9542. "var": _vardefs("var"),
  9543. "const": _vardefs("const"),
  9544. "try": function(t, c, f) {
  9545. if (c != null) return [
  9546. this[0],
  9547. MAP(t, walk),
  9548. [ define(c[0], "catch"), MAP(c[1], walk) ],
  9549. f != null ? MAP(f, walk) : null
  9550. ];
  9551. },
  9552. "name": function(name) {
  9553. if (name == "eval")
  9554. having_eval.push(current_scope);
  9555. reference(name);
  9556. }
  9557. }, function(){
  9558. return walk(ast);
  9559. });
  9560. // the reason why we need an additional pass here is
  9561. // that names can be used prior to their definition.
  9562. // scopes where eval was detected and their parents
  9563. // are marked with uses_eval, unless they define the
  9564. // "eval" name.
  9565. MAP(having_eval, function(scope){
  9566. if (!scope.has("eval")) while (scope) {
  9567. scope.uses_eval = true;
  9568. scope = scope.parent;
  9569. }
  9570. });
  9571. // for referenced names it might be useful to know
  9572. // their origin scope. current_scope here is the
  9573. // toplevel one.
  9574. function fixrefs(scope, i) {
  9575. // do children first; order shouldn't matter
  9576. for (i = scope.children.length; --i >= 0;)
  9577. fixrefs(scope.children[i]);
  9578. for (i in scope.refs) if (HOP(scope.refs, i)) {
  9579. // find origin scope and propagate the reference to origin
  9580. for (var origin = scope.has(i), s = scope; s; s = s.parent) {
  9581. s.refs[i] = origin;
  9582. if (s === origin) break;
  9583. }
  9584. }
  9585. };
  9586. fixrefs(current_scope);
  9587. return ret;
  9588. });
  9589. };
  9590. /* -----[ mangle names ]----- */
  9591. function ast_mangle(ast, options) {
  9592. var w = ast_walker(), walk = w.walk, scope;
  9593. options = defaults(options, {
  9594. mangle : true,
  9595. toplevel : false,
  9596. defines : null,
  9597. except : null,
  9598. no_functions : false
  9599. });
  9600. function get_mangled(name, newMangle) {
  9601. if (!options.mangle) return name;
  9602. if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
  9603. if (options.except && member(name, options.except))
  9604. return name;
  9605. if (options.no_functions && HOP(scope.names, name) &&
  9606. (scope.names[name] == 'defun' || scope.names[name] == 'lambda'))
  9607. return name;
  9608. return scope.get_mangled(name, newMangle);
  9609. };
  9610. function get_define(name) {
  9611. if (options.defines) {
  9612. // we always lookup a defined symbol for the current scope FIRST, so declared
  9613. // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value
  9614. if (!scope.has(name)) {
  9615. if (HOP(options.defines, name)) {
  9616. return options.defines[name];
  9617. }
  9618. }
  9619. return null;
  9620. }
  9621. };
  9622. function _lambda(name, args, body) {
  9623. if (!options.no_functions && options.mangle) {
  9624. var is_defun = this[0] == "defun", extra;
  9625. if (name) {
  9626. if (is_defun) name = get_mangled(name);
  9627. else if (body.scope.references(name)) {
  9628. extra = {};
  9629. if (!(scope.uses_eval || scope.uses_with))
  9630. name = extra[name] = scope.next_mangled();
  9631. else
  9632. extra[name] = name;
  9633. }
  9634. else name = null;
  9635. }
  9636. }
  9637. body = with_scope(body.scope, function(){
  9638. args = MAP(args, function(name){ return get_mangled(name) });
  9639. return MAP(body, walk);
  9640. }, extra);
  9641. return [ this[0], name, args, body ];
  9642. };
  9643. function with_scope(s, cont, extra) {
  9644. var _scope = scope;
  9645. scope = s;
  9646. if (extra) for (var i in extra) if (HOP(extra, i)) {
  9647. s.set_mangle(i, extra[i]);
  9648. }
  9649. for (var i in s.names) if (HOP(s.names, i)) {
  9650. get_mangled(i, true);
  9651. }
  9652. var ret = cont();
  9653. ret.scope = s;
  9654. scope = _scope;
  9655. return ret;
  9656. };
  9657. function _vardefs(defs) {
  9658. return [ this[0], MAP(defs, function(d){
  9659. return [ get_mangled(d[0]), walk(d[1]) ];
  9660. }) ];
  9661. };
  9662. function _breacont(label) {
  9663. if (label) return [ this[0], scope.labels.get_mangled(label) ];
  9664. };
  9665. return w.with_walkers({
  9666. "function": _lambda,
  9667. "defun": function() {
  9668. // move function declarations to the top when
  9669. // they are not in some block.
  9670. var ast = _lambda.apply(this, arguments);
  9671. switch (w.parent()[0]) {
  9672. case "toplevel":
  9673. case "function":
  9674. case "defun":
  9675. return MAP.at_top(ast);
  9676. }
  9677. return ast;
  9678. },
  9679. "label": function(label, stat) {
  9680. if (scope.labels.refs[label]) return [
  9681. this[0],
  9682. scope.labels.get_mangled(label, true),
  9683. walk(stat)
  9684. ];
  9685. return walk(stat);
  9686. },
  9687. "break": _breacont,
  9688. "continue": _breacont,
  9689. "var": _vardefs,
  9690. "const": _vardefs,
  9691. "name": function(name) {
  9692. return get_define(name) || [ this[0], get_mangled(name) ];
  9693. },
  9694. "try": function(t, c, f) {
  9695. return [ this[0],
  9696. MAP(t, walk),
  9697. c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,
  9698. f != null ? MAP(f, walk) : null ];
  9699. },
  9700. "toplevel": function(body) {
  9701. var self = this;
  9702. return with_scope(self.scope, function(){
  9703. return [ self[0], MAP(body, walk) ];
  9704. });
  9705. },
  9706. "directive": function() {
  9707. return MAP.at_top(this);
  9708. }
  9709. }, function() {
  9710. return walk(ast_add_scope(ast));
  9711. });
  9712. };
  9713. /* -----[
  9714. - compress foo["bar"] into foo.bar,
  9715. - remove block brackets {} where possible
  9716. - join consecutive var declarations
  9717. - various optimizations for IFs:
  9718. - if (cond) foo(); else bar(); ==> cond?foo():bar();
  9719. - if (cond) foo(); ==> cond&&foo();
  9720. - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
  9721. - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
  9722. ]----- */
  9723. var warn = function(){};
  9724. function best_of(ast1, ast2) {
  9725. return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
  9726. };
  9727. function last_stat(b) {
  9728. if (b[0] == "block" && b[1] && b[1].length > 0)
  9729. return b[1][b[1].length - 1];
  9730. return b;
  9731. }
  9732. function aborts(t) {
  9733. if (t) switch (last_stat(t)[0]) {
  9734. case "return":
  9735. case "break":
  9736. case "continue":
  9737. case "throw":
  9738. return true;
  9739. }
  9740. };
  9741. function boolean_expr(expr) {
  9742. return ( (expr[0] == "unary-prefix"
  9743. && member(expr[1], [ "!", "delete" ])) ||
  9744. (expr[0] == "binary"
  9745. && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) ||
  9746. (expr[0] == "binary"
  9747. && member(expr[1], [ "&&", "||" ])
  9748. && boolean_expr(expr[2])
  9749. && boolean_expr(expr[3])) ||
  9750. (expr[0] == "conditional"
  9751. && boolean_expr(expr[2])
  9752. && boolean_expr(expr[3])) ||
  9753. (expr[0] == "assign"
  9754. && expr[1] === true
  9755. && boolean_expr(expr[3])) ||
  9756. (expr[0] == "seq"
  9757. && boolean_expr(expr[expr.length - 1]))
  9758. );
  9759. };
  9760. function empty(b) {
  9761. return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
  9762. };
  9763. function is_string(node) {
  9764. return (node[0] == "string" ||
  9765. node[0] == "unary-prefix" && node[1] == "typeof" ||
  9766. node[0] == "binary" && node[1] == "+" &&
  9767. (is_string(node[2]) || is_string(node[3])));
  9768. };
  9769. var when_constant = (function(){
  9770. var $NOT_CONSTANT = {};
  9771. // this can only evaluate constant expressions. If it finds anything
  9772. // not constant, it throws $NOT_CONSTANT.
  9773. function evaluate(expr) {
  9774. switch (expr[0]) {
  9775. case "string":
  9776. case "num":
  9777. return expr[1];
  9778. case "name":
  9779. case "atom":
  9780. switch (expr[1]) {
  9781. case "true": return true;
  9782. case "false": return false;
  9783. case "null": return null;
  9784. }
  9785. break;
  9786. case "unary-prefix":
  9787. switch (expr[1]) {
  9788. case "!": return !evaluate(expr[2]);
  9789. case "typeof": return typeof evaluate(expr[2]);
  9790. case "~": return ~evaluate(expr[2]);
  9791. case "-": return -evaluate(expr[2]);
  9792. case "+": return +evaluate(expr[2]);
  9793. }
  9794. break;
  9795. case "binary":
  9796. var left = expr[2], right = expr[3];
  9797. switch (expr[1]) {
  9798. case "&&" : return evaluate(left) && evaluate(right);
  9799. case "||" : return evaluate(left) || evaluate(right);
  9800. case "|" : return evaluate(left) | evaluate(right);
  9801. case "&" : return evaluate(left) & evaluate(right);
  9802. case "^" : return evaluate(left) ^ evaluate(right);
  9803. case "+" : return evaluate(left) + evaluate(right);
  9804. case "*" : return evaluate(left) * evaluate(right);
  9805. case "/" : return evaluate(left) / evaluate(right);
  9806. case "%" : return evaluate(left) % evaluate(right);
  9807. case "-" : return evaluate(left) - evaluate(right);
  9808. case "<<" : return evaluate(left) << evaluate(right);
  9809. case ">>" : return evaluate(left) >> evaluate(right);
  9810. case ">>>" : return evaluate(left) >>> evaluate(right);
  9811. case "==" : return evaluate(left) == evaluate(right);
  9812. case "===" : return evaluate(left) === evaluate(right);
  9813. case "!=" : return evaluate(left) != evaluate(right);
  9814. case "!==" : return evaluate(left) !== evaluate(right);
  9815. case "<" : return evaluate(left) < evaluate(right);
  9816. case "<=" : return evaluate(left) <= evaluate(right);
  9817. case ">" : return evaluate(left) > evaluate(right);
  9818. case ">=" : return evaluate(left) >= evaluate(right);
  9819. case "in" : return evaluate(left) in evaluate(right);
  9820. case "instanceof" : return evaluate(left) instanceof evaluate(right);
  9821. }
  9822. }
  9823. throw $NOT_CONSTANT;
  9824. };
  9825. return function(expr, yes, no) {
  9826. try {
  9827. var val = evaluate(expr), ast;
  9828. switch (typeof val) {
  9829. case "string": ast = [ "string", val ]; break;
  9830. case "number": ast = [ "num", val ]; break;
  9831. case "boolean": ast = [ "name", String(val) ]; break;
  9832. default:
  9833. if (val === null) { ast = [ "atom", "null" ]; break; }
  9834. throw new Error("Can't handle constant of type: " + (typeof val));
  9835. }
  9836. return yes.call(expr, ast, val);
  9837. } catch(ex) {
  9838. if (ex === $NOT_CONSTANT) {
  9839. if (expr[0] == "binary"
  9840. && (expr[1] == "===" || expr[1] == "!==")
  9841. && ((is_string(expr[2]) && is_string(expr[3]))
  9842. || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {
  9843. expr[1] = expr[1].substr(0, 2);
  9844. }
  9845. else if (no && expr[0] == "binary"
  9846. && (expr[1] == "||" || expr[1] == "&&")) {
  9847. // the whole expression is not constant but the lval may be...
  9848. try {
  9849. var lval = evaluate(expr[2]);
  9850. expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) ||
  9851. (expr[1] == "||" && (lval ? lval : expr[3])) ||
  9852. expr);
  9853. } catch(ex2) {
  9854. // IGNORE... lval is not constant
  9855. }
  9856. }
  9857. return no ? no.call(expr, expr) : null;
  9858. }
  9859. else throw ex;
  9860. }
  9861. };
  9862. })();
  9863. function warn_unreachable(ast) {
  9864. if (!empty(ast))
  9865. warn("Dropping unreachable code: " + gen_code(ast, true));
  9866. };
  9867. function prepare_ifs(ast) {
  9868. var w = ast_walker(), walk = w.walk;
  9869. // In this first pass, we rewrite ifs which abort with no else with an
  9870. // if-else. For example:
  9871. //
  9872. // if (x) {
  9873. // blah();
  9874. // return y;
  9875. // }
  9876. // foobar();
  9877. //
  9878. // is rewritten into:
  9879. //
  9880. // if (x) {
  9881. // blah();
  9882. // return y;
  9883. // } else {
  9884. // foobar();
  9885. // }
  9886. function redo_if(statements) {
  9887. statements = MAP(statements, walk);
  9888. for (var i = 0; i < statements.length; ++i) {
  9889. var fi = statements[i];
  9890. if (fi[0] != "if") continue;
  9891. if (fi[3]) continue;
  9892. var t = fi[2];
  9893. if (!aborts(t)) continue;
  9894. var conditional = walk(fi[1]);
  9895. var e_body = redo_if(statements.slice(i + 1));
  9896. var e = e_body.length == 1 ? e_body[0] : [ "block", e_body ];
  9897. return statements.slice(0, i).concat([ [
  9898. fi[0], // "if"
  9899. conditional, // conditional
  9900. t, // then
  9901. e // else
  9902. ] ]);
  9903. }
  9904. return statements;
  9905. };
  9906. function redo_if_lambda(name, args, body) {
  9907. body = redo_if(body);
  9908. return [ this[0], name, args, body ];
  9909. };
  9910. function redo_if_block(statements) {
  9911. return [ this[0], statements != null ? redo_if(statements) : null ];
  9912. };
  9913. return w.with_walkers({
  9914. "defun": redo_if_lambda,
  9915. "function": redo_if_lambda,
  9916. "block": redo_if_block,
  9917. "splice": redo_if_block,
  9918. "toplevel": function(statements) {
  9919. return [ this[0], redo_if(statements) ];
  9920. },
  9921. "try": function(t, c, f) {
  9922. return [
  9923. this[0],
  9924. redo_if(t),
  9925. c != null ? [ c[0], redo_if(c[1]) ] : null,
  9926. f != null ? redo_if(f) : null
  9927. ];
  9928. }
  9929. }, function() {
  9930. return walk(ast);
  9931. });
  9932. };
  9933. function for_side_effects(ast, handler) {
  9934. var w = ast_walker(), walk = w.walk;
  9935. var $stop = {}, $restart = {};
  9936. function stop() { throw $stop };
  9937. function restart() { throw $restart };
  9938. function found(){ return handler.call(this, this, w, stop, restart) };
  9939. function unary(op) {
  9940. if (op == "++" || op == "--")
  9941. return found.apply(this, arguments);
  9942. };
  9943. function binary(op) {
  9944. if (op == "&&" || op == "||")
  9945. return found.apply(this, arguments);
  9946. };
  9947. return w.with_walkers({
  9948. "try": found,
  9949. "throw": found,
  9950. "return": found,
  9951. "new": found,
  9952. "switch": found,
  9953. "break": found,
  9954. "continue": found,
  9955. "assign": found,
  9956. "call": found,
  9957. "if": found,
  9958. "for": found,
  9959. "for-in": found,
  9960. "while": found,
  9961. "do": found,
  9962. "return": found,
  9963. "unary-prefix": unary,
  9964. "unary-postfix": unary,
  9965. "conditional": found,
  9966. "binary": binary,
  9967. "defun": found
  9968. }, function(){
  9969. while (true) try {
  9970. walk(ast);
  9971. break;
  9972. } catch(ex) {
  9973. if (ex === $stop) break;
  9974. if (ex === $restart) continue;
  9975. throw ex;
  9976. }
  9977. });
  9978. };
  9979. function ast_lift_variables(ast) {
  9980. var w = ast_walker(), walk = w.walk, scope;
  9981. function do_body(body, env) {
  9982. var _scope = scope;
  9983. scope = env;
  9984. body = MAP(body, walk);
  9985. var hash = {}, names = MAP(env.names, function(type, name){
  9986. if (type != "var") return MAP.skip;
  9987. if (!env.references(name)) return MAP.skip;
  9988. hash[name] = true;
  9989. return [ name ];
  9990. });
  9991. if (names.length > 0) {
  9992. // looking for assignments to any of these variables.
  9993. // we can save considerable space by moving the definitions
  9994. // in the var declaration.
  9995. for_side_effects([ "block", body ], function(ast, walker, stop, restart) {
  9996. if (ast[0] == "assign"
  9997. && ast[1] === true
  9998. && ast[2][0] == "name"
  9999. && HOP(hash, ast[2][1])) {
  10000. // insert the definition into the var declaration
  10001. for (var i = names.length; --i >= 0;) {
  10002. if (names[i][0] == ast[2][1]) {
  10003. if (names[i][1]) // this name already defined, we must stop
  10004. stop();
  10005. names[i][1] = ast[3]; // definition
  10006. names.push(names.splice(i, 1)[0]);
  10007. break;
  10008. }
  10009. }
  10010. // remove this assignment from the AST.
  10011. var p = walker.parent();
  10012. if (p[0] == "seq") {
  10013. var a = p[2];
  10014. a.unshift(0, p.length);
  10015. p.splice.apply(p, a);
  10016. }
  10017. else if (p[0] == "stat") {
  10018. p.splice(0, p.length, "block"); // empty statement
  10019. }
  10020. else {
  10021. stop();
  10022. }
  10023. restart();
  10024. }
  10025. stop();
  10026. });
  10027. body.unshift([ "var", names ]);
  10028. }
  10029. scope = _scope;
  10030. return body;
  10031. };
  10032. function _vardefs(defs) {
  10033. var ret = null;
  10034. for (var i = defs.length; --i >= 0;) {
  10035. var d = defs[i];
  10036. if (!d[1]) continue;
  10037. d = [ "assign", true, [ "name", d[0] ], d[1] ];
  10038. if (ret == null) ret = d;
  10039. else ret = [ "seq", d, ret ];
  10040. }
  10041. if (ret == null && w.parent()[0] != "for") {
  10042. if (w.parent()[0] == "for-in")
  10043. return [ "name", defs[0][0] ];
  10044. return MAP.skip;
  10045. }
  10046. return [ "stat", ret ];
  10047. };
  10048. function _toplevel(body) {
  10049. return [ this[0], do_body(body, this.scope) ];
  10050. };
  10051. return w.with_walkers({
  10052. "function": function(name, args, body){
  10053. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  10054. args.pop();
  10055. if (!body.scope.references(name)) name = null;
  10056. return [ this[0], name, args, do_body(body, body.scope) ];
  10057. },
  10058. "defun": function(name, args, body){
  10059. if (!scope.references(name)) return MAP.skip;
  10060. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  10061. args.pop();
  10062. return [ this[0], name, args, do_body(body, body.scope) ];
  10063. },
  10064. "var": _vardefs,
  10065. "toplevel": _toplevel
  10066. }, function(){
  10067. return walk(ast_add_scope(ast));
  10068. });
  10069. };
  10070. function ast_squeeze(ast, options) {
  10071. ast = squeeze_1(ast, options);
  10072. ast = squeeze_2(ast, options);
  10073. return ast;
  10074. };
  10075. function squeeze_1(ast, options) {
  10076. options = defaults(options, {
  10077. make_seqs : true,
  10078. dead_code : true,
  10079. no_warnings : false,
  10080. keep_comps : true,
  10081. unsafe : false
  10082. });
  10083. var w = ast_walker(), walk = w.walk, scope;
  10084. function negate(c) {
  10085. var not_c = [ "unary-prefix", "!", c ];
  10086. switch (c[0]) {
  10087. case "unary-prefix":
  10088. return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c;
  10089. case "seq":
  10090. c = slice(c);
  10091. c[c.length - 1] = negate(c[c.length - 1]);
  10092. return c;
  10093. case "conditional":
  10094. return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]);
  10095. case "binary":
  10096. var op = c[1], left = c[2], right = c[3];
  10097. if (!options.keep_comps) switch (op) {
  10098. case "<=" : return [ "binary", ">", left, right ];
  10099. case "<" : return [ "binary", ">=", left, right ];
  10100. case ">=" : return [ "binary", "<", left, right ];
  10101. case ">" : return [ "binary", "<=", left, right ];
  10102. }
  10103. switch (op) {
  10104. case "==" : return [ "binary", "!=", left, right ];
  10105. case "!=" : return [ "binary", "==", left, right ];
  10106. case "===" : return [ "binary", "!==", left, right ];
  10107. case "!==" : return [ "binary", "===", left, right ];
  10108. case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]);
  10109. case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]);
  10110. }
  10111. break;
  10112. }
  10113. return not_c;
  10114. };
  10115. function make_conditional(c, t, e) {
  10116. var make_real_conditional = function() {
  10117. if (c[0] == "unary-prefix" && c[1] == "!") {
  10118. return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
  10119. } else {
  10120. return e ? best_of(
  10121. [ "conditional", c, t, e ],
  10122. [ "conditional", negate(c), e, t ]
  10123. ) : [ "binary", "&&", c, t ];
  10124. }
  10125. };
  10126. // shortcut the conditional if the expression has a constant value
  10127. return when_constant(c, function(ast, val){
  10128. warn_unreachable(val ? e : t);
  10129. return (val ? t : e);
  10130. }, make_real_conditional);
  10131. };
  10132. function rmblock(block) {
  10133. if (block != null && block[0] == "block" && block[1]) {
  10134. if (block[1].length == 1)
  10135. block = block[1][0];
  10136. else if (block[1].length == 0)
  10137. block = [ "block" ];
  10138. }
  10139. return block;
  10140. };
  10141. function _lambda(name, args, body) {
  10142. return [ this[0], name, args, tighten(body, "lambda") ];
  10143. };
  10144. // this function does a few things:
  10145. // 1. discard useless blocks
  10146. // 2. join consecutive var declarations
  10147. // 3. remove obviously dead code
  10148. // 4. transform consecutive statements using the comma operator
  10149. // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }
  10150. function tighten(statements, block_type) {
  10151. statements = MAP(statements, walk);
  10152. statements = statements.reduce(function(a, stat){
  10153. if (stat[0] == "block") {
  10154. if (stat[1]) {
  10155. a.push.apply(a, stat[1]);
  10156. }
  10157. } else {
  10158. a.push(stat);
  10159. }
  10160. return a;
  10161. }, []);
  10162. statements = (function(a, prev){
  10163. statements.forEach(function(cur){
  10164. if (prev && ((cur[0] == "var" && prev[0] == "var") ||
  10165. (cur[0] == "const" && prev[0] == "const"))) {
  10166. prev[1] = prev[1].concat(cur[1]);
  10167. } else {
  10168. a.push(cur);
  10169. prev = cur;
  10170. }
  10171. });
  10172. return a;
  10173. })([]);
  10174. if (options.dead_code) statements = (function(a, has_quit){
  10175. statements.forEach(function(st){
  10176. if (has_quit) {
  10177. if (st[0] == "function" || st[0] == "defun") {
  10178. a.push(st);
  10179. }
  10180. else if (st[0] == "var" || st[0] == "const") {
  10181. if (!options.no_warnings)
  10182. warn("Variables declared in unreachable code");
  10183. st[1] = MAP(st[1], function(def){
  10184. if (def[1] && !options.no_warnings)
  10185. warn_unreachable([ "assign", true, [ "name", def[0] ], def[1] ]);
  10186. return [ def[0] ];
  10187. });
  10188. a.push(st);
  10189. }
  10190. else if (!options.no_warnings)
  10191. warn_unreachable(st);
  10192. }
  10193. else {
  10194. a.push(st);
  10195. if (member(st[0], [ "return", "throw", "break", "continue" ]))
  10196. has_quit = true;
  10197. }
  10198. });
  10199. return a;
  10200. })([]);
  10201. if (options.make_seqs) statements = (function(a, prev) {
  10202. statements.forEach(function(cur){
  10203. if (prev && prev[0] == "stat" && cur[0] == "stat") {
  10204. prev[1] = [ "seq", prev[1], cur[1] ];
  10205. } else {
  10206. a.push(cur);
  10207. prev = cur;
  10208. }
  10209. });
  10210. if (a.length >= 2
  10211. && a[a.length-2][0] == "stat"
  10212. && (a[a.length-1][0] == "return" || a[a.length-1][0] == "throw")
  10213. && a[a.length-1][1])
  10214. {
  10215. a.splice(a.length - 2, 2,
  10216. [ a[a.length-1][0],
  10217. [ "seq", a[a.length-2][1], a[a.length-1][1] ]]);
  10218. }
  10219. return a;
  10220. })([]);
  10221. // this increases jQuery by 1K. Probably not such a good idea after all..
  10222. // part of this is done in prepare_ifs anyway.
  10223. // if (block_type == "lambda") statements = (function(i, a, stat){
  10224. // while (i < statements.length) {
  10225. // stat = statements[i++];
  10226. // if (stat[0] == "if" && !stat[3]) {
  10227. // if (stat[2][0] == "return" && stat[2][1] == null) {
  10228. // a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
  10229. // break;
  10230. // }
  10231. // var last = last_stat(stat[2]);
  10232. // if (last[0] == "return" && last[1] == null) {
  10233. // a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ]));
  10234. // break;
  10235. // }
  10236. // }
  10237. // a.push(stat);
  10238. // }
  10239. // return a;
  10240. // })(0, []);
  10241. return statements;
  10242. };
  10243. function make_if(c, t, e) {
  10244. return when_constant(c, function(ast, val){
  10245. if (val) {
  10246. t = walk(t);
  10247. warn_unreachable(e);
  10248. return t || [ "block" ];
  10249. } else {
  10250. e = walk(e);
  10251. warn_unreachable(t);
  10252. return e || [ "block" ];
  10253. }
  10254. }, function() {
  10255. return make_real_if(c, t, e);
  10256. });
  10257. };
  10258. function abort_else(c, t, e) {
  10259. var ret = [ [ "if", negate(c), e ] ];
  10260. if (t[0] == "block") {
  10261. if (t[1]) ret = ret.concat(t[1]);
  10262. } else {
  10263. ret.push(t);
  10264. }
  10265. return walk([ "block", ret ]);
  10266. };
  10267. function make_real_if(c, t, e) {
  10268. c = walk(c);
  10269. t = walk(t);
  10270. e = walk(e);
  10271. if (empty(e) && empty(t))
  10272. return [ "stat", c ];
  10273. if (empty(t)) {
  10274. c = negate(c);
  10275. t = e;
  10276. e = null;
  10277. } else if (empty(e)) {
  10278. e = null;
  10279. } else {
  10280. // if we have both else and then, maybe it makes sense to switch them?
  10281. (function(){
  10282. var a = gen_code(c);
  10283. var n = negate(c);
  10284. var b = gen_code(n);
  10285. if (b.length < a.length) {
  10286. var tmp = t;
  10287. t = e;
  10288. e = tmp;
  10289. c = n;
  10290. }
  10291. })();
  10292. }
  10293. var ret = [ "if", c, t, e ];
  10294. if (t[0] == "if" && empty(t[3]) && empty(e)) {
  10295. ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ]));
  10296. }
  10297. else if (t[0] == "stat") {
  10298. if (e) {
  10299. if (e[0] == "stat")
  10300. ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
  10301. else if (aborts(e))
  10302. ret = abort_else(c, t, e);
  10303. }
  10304. else {
  10305. ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
  10306. }
  10307. }
  10308. else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) {
  10309. ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
  10310. }
  10311. else if (e && aborts(t)) {
  10312. ret = [ [ "if", c, t ] ];
  10313. if (e[0] == "block") {
  10314. if (e[1]) ret = ret.concat(e[1]);
  10315. }
  10316. else {
  10317. ret.push(e);
  10318. }
  10319. ret = walk([ "block", ret ]);
  10320. }
  10321. else if (t && aborts(e)) {
  10322. ret = abort_else(c, t, e);
  10323. }
  10324. return ret;
  10325. };
  10326. function _do_while(cond, body) {
  10327. return when_constant(cond, function(cond, val){
  10328. if (!val) {
  10329. warn_unreachable(body);
  10330. return [ "block" ];
  10331. } else {
  10332. return [ "for", null, null, null, walk(body) ];
  10333. }
  10334. });
  10335. };
  10336. return w.with_walkers({
  10337. "sub": function(expr, subscript) {
  10338. if (subscript[0] == "string") {
  10339. var name = subscript[1];
  10340. if (is_identifier(name))
  10341. return [ "dot", walk(expr), name ];
  10342. else if (/^[1-9][0-9]*$/.test(name) || name === "0")
  10343. return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ];
  10344. }
  10345. },
  10346. "if": make_if,
  10347. "toplevel": function(body) {
  10348. return [ "toplevel", tighten(body) ];
  10349. },
  10350. "switch": function(expr, body) {
  10351. var last = body.length - 1;
  10352. return [ "switch", walk(expr), MAP(body, function(branch, i){
  10353. var block = tighten(branch[1]);
  10354. if (i == last && block.length > 0) {
  10355. var node = block[block.length - 1];
  10356. if (node[0] == "break" && !node[1])
  10357. block.pop();
  10358. }
  10359. return [ branch[0] ? walk(branch[0]) : null, block ];
  10360. }) ];
  10361. },
  10362. "function": _lambda,
  10363. "defun": _lambda,
  10364. "block": function(body) {
  10365. if (body) return rmblock([ "block", tighten(body) ]);
  10366. },
  10367. "binary": function(op, left, right) {
  10368. return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){
  10369. return best_of(walk(c), this);
  10370. }, function no() {
  10371. return function(){
  10372. if(op != "==" && op != "!=") return;
  10373. var l = walk(left), r = walk(right);
  10374. if(l && l[0] == "unary-prefix" && l[1] == "!" && l[2][0] == "num")
  10375. left = ['num', +!l[2][1]];
  10376. else if (r && r[0] == "unary-prefix" && r[1] == "!" && r[2][0] == "num")
  10377. right = ['num', +!r[2][1]];
  10378. return ["binary", op, left, right];
  10379. }() || this;
  10380. });
  10381. },
  10382. "conditional": function(c, t, e) {
  10383. return make_conditional(walk(c), walk(t), walk(e));
  10384. },
  10385. "try": function(t, c, f) {
  10386. return [
  10387. "try",
  10388. tighten(t),
  10389. c != null ? [ c[0], tighten(c[1]) ] : null,
  10390. f != null ? tighten(f) : null
  10391. ];
  10392. },
  10393. "unary-prefix": function(op, expr) {
  10394. expr = walk(expr);
  10395. var ret = [ "unary-prefix", op, expr ];
  10396. if (op == "!")
  10397. ret = best_of(ret, negate(expr));
  10398. return when_constant(ret, function(ast, val){
  10399. return walk(ast); // it's either true or false, so minifies to !0 or !1
  10400. }, function() { return ret });
  10401. },
  10402. "name": function(name) {
  10403. switch (name) {
  10404. case "true": return [ "unary-prefix", "!", [ "num", 0 ]];
  10405. case "false": return [ "unary-prefix", "!", [ "num", 1 ]];
  10406. }
  10407. },
  10408. "while": _do_while,
  10409. "assign": function(op, lvalue, rvalue) {
  10410. lvalue = walk(lvalue);
  10411. rvalue = walk(rvalue);
  10412. var okOps = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  10413. if (op === true && lvalue[0] === "name" && rvalue[0] === "binary" &&
  10414. ~okOps.indexOf(rvalue[1]) && rvalue[2][0] === "name" &&
  10415. rvalue[2][1] === lvalue[1]) {
  10416. return [ this[0], rvalue[1], lvalue, rvalue[3] ]
  10417. }
  10418. return [ this[0], op, lvalue, rvalue ];
  10419. },
  10420. "call": function(expr, args) {
  10421. expr = walk(expr);
  10422. if (options.unsafe && expr[0] == "dot" && expr[1][0] == "string" && expr[2] == "toString") {
  10423. return expr[1];
  10424. }
  10425. return [ this[0], expr, MAP(args, walk) ];
  10426. },
  10427. "num": function (num) {
  10428. if (!isFinite(num))
  10429. return [ "binary", "/", num === 1 / 0
  10430. ? [ "num", 1 ] : num === -1 / 0
  10431. ? [ "unary-prefix", "-", [ "num", 1 ] ]
  10432. : [ "num", 0 ], [ "num", 0 ] ];
  10433. return [ this[0], num ];
  10434. }
  10435. }, function() {
  10436. return walk(prepare_ifs(walk(prepare_ifs(ast))));
  10437. });
  10438. };
  10439. function squeeze_2(ast, options) {
  10440. var w = ast_walker(), walk = w.walk, scope;
  10441. function with_scope(s, cont) {
  10442. var save = scope, ret;
  10443. scope = s;
  10444. ret = cont();
  10445. scope = save;
  10446. return ret;
  10447. };
  10448. function lambda(name, args, body) {
  10449. return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  10450. };
  10451. return w.with_walkers({
  10452. "directive": function(dir) {
  10453. if (scope.active_directive(dir))
  10454. return [ "block" ];
  10455. scope.directives.push(dir);
  10456. },
  10457. "toplevel": function(body) {
  10458. return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
  10459. },
  10460. "function": lambda,
  10461. "defun": lambda
  10462. }, function(){
  10463. return walk(ast_add_scope(ast));
  10464. });
  10465. };
  10466. /* -----[ re-generate code from the AST ]----- */
  10467. var DOT_CALL_NO_PARENS = jsp.array_to_hash([
  10468. "name",
  10469. "array",
  10470. "object",
  10471. "string",
  10472. "dot",
  10473. "sub",
  10474. "call",
  10475. "regexp",
  10476. "defun"
  10477. ]);
  10478. function make_string(str, ascii_only) {
  10479. var dq = 0, sq = 0;
  10480. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
  10481. switch (s) {
  10482. case "\\": return "\\\\";
  10483. case "\b": return "\\b";
  10484. case "\f": return "\\f";
  10485. case "\n": return "\\n";
  10486. case "\r": return "\\r";
  10487. case "\u2028": return "\\u2028";
  10488. case "\u2029": return "\\u2029";
  10489. case '"': ++dq; return '"';
  10490. case "'": ++sq; return "'";
  10491. case "\0": return "\\0";
  10492. }
  10493. return s;
  10494. });
  10495. if (ascii_only) str = to_ascii(str);
  10496. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
  10497. else return '"' + str.replace(/\x22/g, '\\"') + '"';
  10498. };
  10499. function to_ascii(str) {
  10500. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  10501. var code = ch.charCodeAt(0).toString(16);
  10502. while (code.length < 4) code = "0" + code;
  10503. return "\\u" + code;
  10504. });
  10505. };
  10506. var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]);
  10507. function gen_code(ast, options) {
  10508. options = defaults(options, {
  10509. indent_start : 0,
  10510. indent_level : 4,
  10511. quote_keys : false,
  10512. space_colon : false,
  10513. beautify : false,
  10514. ascii_only : false,
  10515. inline_script: false
  10516. });
  10517. var beautify = !!options.beautify;
  10518. var indentation = 0,
  10519. newline = beautify ? "\n" : "",
  10520. space = beautify ? " " : "";
  10521. function encode_string(str) {
  10522. var ret = make_string(str, options.ascii_only);
  10523. if (options.inline_script)
  10524. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  10525. return ret;
  10526. };
  10527. function make_name(name) {
  10528. name = name.toString();
  10529. if (options.ascii_only)
  10530. name = to_ascii(name);
  10531. return name;
  10532. };
  10533. function indent(line) {
  10534. if (line == null)
  10535. line = "";
  10536. if (beautify)
  10537. line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line;
  10538. return line;
  10539. };
  10540. function with_indent(cont, incr) {
  10541. if (incr == null) incr = 1;
  10542. indentation += incr;
  10543. try { return cont.apply(null, slice(arguments, 1)); }
  10544. finally { indentation -= incr; }
  10545. };
  10546. function last_char(str) {
  10547. str = str.toString();
  10548. return str.charAt(str.length - 1);
  10549. };
  10550. function first_char(str) {
  10551. return str.toString().charAt(0);
  10552. };
  10553. function add_spaces(a) {
  10554. if (beautify)
  10555. return a.join(" ");
  10556. var b = [];
  10557. for (var i = 0; i < a.length; ++i) {
  10558. var next = a[i + 1];
  10559. b.push(a[i]);
  10560. if (next &&
  10561. ((is_identifier_char(last_char(a[i])) && (is_identifier_char(first_char(next))
  10562. || first_char(next) == "\\")) ||
  10563. (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString()) ||
  10564. last_char(a[i]) == "/" && first_char(next) == "/"))) {
  10565. b.push(" ");
  10566. }
  10567. }
  10568. return b.join("");
  10569. };
  10570. function add_commas(a) {
  10571. return a.join("," + space);
  10572. };
  10573. function parenthesize(expr) {
  10574. var gen = make(expr);
  10575. for (var i = 1; i < arguments.length; ++i) {
  10576. var el = arguments[i];
  10577. if ((el instanceof Function && el(expr)) || expr[0] == el)
  10578. return "(" + gen + ")";
  10579. }
  10580. return gen;
  10581. };
  10582. function best_of(a) {
  10583. if (a.length == 1) {
  10584. return a[0];
  10585. }
  10586. if (a.length == 2) {
  10587. var b = a[1];
  10588. a = a[0];
  10589. return a.length <= b.length ? a : b;
  10590. }
  10591. return best_of([ a[0], best_of(a.slice(1)) ]);
  10592. };
  10593. function needs_parens(expr) {
  10594. if (expr[0] == "function" || expr[0] == "object") {
  10595. // dot/call on a literal function requires the
  10596. // function literal itself to be parenthesized
  10597. // only if it's the first "thing" in a
  10598. // statement. This means that the parent is
  10599. // "stat", but it could also be a "seq" and
  10600. // we're the first in this "seq" and the
  10601. // parent is "stat", and so on. Messy stuff,
  10602. // but it worths the trouble.
  10603. var a = slice(w.stack()), self = a.pop(), p = a.pop();
  10604. while (p) {
  10605. if (p[0] == "stat") return true;
  10606. if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) ||
  10607. ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) {
  10608. self = p;
  10609. p = a.pop();
  10610. } else {
  10611. return false;
  10612. }
  10613. }
  10614. }
  10615. return !HOP(DOT_CALL_NO_PARENS, expr[0]);
  10616. };
  10617. function make_num(num) {
  10618. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  10619. if (Math.floor(num) === num) {
  10620. if (num >= 0) {
  10621. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  10622. "0" + num.toString(8)); // same.
  10623. } else {
  10624. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  10625. "-0" + (-num).toString(8)); // same.
  10626. }
  10627. if ((m = /^(.*?)(0+)$/.exec(num))) {
  10628. a.push(m[1] + "e" + m[2].length);
  10629. }
  10630. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  10631. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  10632. str.substr(str.indexOf(".")));
  10633. }
  10634. return best_of(a);
  10635. };
  10636. var w = ast_walker();
  10637. var make = w.walk;
  10638. return w.with_walkers({
  10639. "string": encode_string,
  10640. "num": make_num,
  10641. "name": make_name,
  10642. "debugger": function(){ return "debugger;" },
  10643. "toplevel": function(statements) {
  10644. return make_block_statements(statements)
  10645. .join(newline + newline);
  10646. },
  10647. "splice": function(statements) {
  10648. var parent = w.parent();
  10649. if (HOP(SPLICE_NEEDS_BRACKETS, parent)) {
  10650. // we need block brackets in this case
  10651. return make_block.apply(this, arguments);
  10652. } else {
  10653. return MAP(make_block_statements(statements, true),
  10654. function(line, i) {
  10655. // the first line is already indented
  10656. return i > 0 ? indent(line) : line;
  10657. }).join(newline);
  10658. }
  10659. },
  10660. "block": make_block,
  10661. "var": function(defs) {
  10662. return "var " + add_commas(MAP(defs, make_1vardef)) + ";";
  10663. },
  10664. "const": function(defs) {
  10665. return "const " + add_commas(MAP(defs, make_1vardef)) + ";";
  10666. },
  10667. "try": function(tr, ca, fi) {
  10668. var out = [ "try", make_block(tr) ];
  10669. if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
  10670. if (fi) out.push("finally", make_block(fi));
  10671. return add_spaces(out);
  10672. },
  10673. "throw": function(expr) {
  10674. return add_spaces([ "throw", make(expr) ]) + ";";
  10675. },
  10676. "new": function(ctor, args) {
  10677. args = args.length > 0 ? "(" + add_commas(MAP(args, function(expr){
  10678. return parenthesize(expr, "seq");
  10679. })) + ")" : "";
  10680. return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
  10681. var w = ast_walker(), has_call = {};
  10682. try {
  10683. w.with_walkers({
  10684. "call": function() { throw has_call },
  10685. "function": function() { return this }
  10686. }, function(){
  10687. w.walk(expr);
  10688. });
  10689. } catch(ex) {
  10690. if (ex === has_call)
  10691. return true;
  10692. throw ex;
  10693. }
  10694. }) + args ]);
  10695. },
  10696. "switch": function(expr, body) {
  10697. return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
  10698. },
  10699. "break": function(label) {
  10700. var out = "break";
  10701. if (label != null)
  10702. out += " " + make_name(label);
  10703. return out + ";";
  10704. },
  10705. "continue": function(label) {
  10706. var out = "continue";
  10707. if (label != null)
  10708. out += " " + make_name(label);
  10709. return out + ";";
  10710. },
  10711. "conditional": function(co, th, el) {
  10712. return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
  10713. parenthesize(th, "seq"), ":",
  10714. parenthesize(el, "seq") ]);
  10715. },
  10716. "assign": function(op, lvalue, rvalue) {
  10717. if (op && op !== true) op += "=";
  10718. else op = "=";
  10719. return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]);
  10720. },
  10721. "dot": function(expr) {
  10722. var out = make(expr), i = 1;
  10723. if (expr[0] == "num") {
  10724. if (!/[a-f.]/i.test(out))
  10725. out += ".";
  10726. } else if (expr[0] != "function" && needs_parens(expr))
  10727. out = "(" + out + ")";
  10728. while (i < arguments.length)
  10729. out += "." + make_name(arguments[i++]);
  10730. return out;
  10731. },
  10732. "call": function(func, args) {
  10733. var f = make(func);
  10734. if (f.charAt(0) != "(" && needs_parens(func))
  10735. f = "(" + f + ")";
  10736. return f + "(" + add_commas(MAP(args, function(expr){
  10737. return parenthesize(expr, "seq");
  10738. })) + ")";
  10739. },
  10740. "function": make_function,
  10741. "defun": make_function,
  10742. "if": function(co, th, el) {
  10743. var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
  10744. if (el) {
  10745. out.push("else", make(el));
  10746. }
  10747. return add_spaces(out);
  10748. },
  10749. "for": function(init, cond, step, block) {
  10750. var out = [ "for" ];
  10751. init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
  10752. cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
  10753. step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
  10754. var args = init + cond + step;
  10755. if (args == "; ; ") args = ";;";
  10756. out.push("(" + args + ")", make(block));
  10757. return add_spaces(out);
  10758. },
  10759. "for-in": function(vvar, key, hash, block) {
  10760. return add_spaces([ "for", "(" +
  10761. (vvar ? make(vvar).replace(/;+$/, "") : make(key)),
  10762. "in",
  10763. make(hash) + ")", make(block) ]);
  10764. },
  10765. "while": function(condition, block) {
  10766. return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
  10767. },
  10768. "do": function(condition, block) {
  10769. return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
  10770. },
  10771. "return": function(expr) {
  10772. var out = [ "return" ];
  10773. if (expr != null) out.push(make(expr));
  10774. return add_spaces(out) + ";";
  10775. },
  10776. "binary": function(operator, lvalue, rvalue) {
  10777. var left = make(lvalue), right = make(rvalue);
  10778. // XXX: I'm pretty sure other cases will bite here.
  10779. // we need to be smarter.
  10780. // adding parens all the time is the safest bet.
  10781. if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
  10782. lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]] ||
  10783. lvalue[0] == "function" && needs_parens(this)) {
  10784. left = "(" + left + ")";
  10785. }
  10786. if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
  10787. rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&
  10788. !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) {
  10789. right = "(" + right + ")";
  10790. }
  10791. else if (!beautify && options.inline_script && (operator == "<" || operator == "<<")
  10792. && rvalue[0] == "regexp" && /^script/i.test(rvalue[1])) {
  10793. right = " " + right;
  10794. }
  10795. return add_spaces([ left, operator, right ]);
  10796. },
  10797. "unary-prefix": function(operator, expr) {
  10798. var val = make(expr);
  10799. if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  10800. val = "(" + val + ")";
  10801. return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
  10802. },
  10803. "unary-postfix": function(operator, expr) {
  10804. var val = make(expr);
  10805. if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  10806. val = "(" + val + ")";
  10807. return val + operator;
  10808. },
  10809. "sub": function(expr, subscript) {
  10810. var hash = make(expr);
  10811. if (needs_parens(expr))
  10812. hash = "(" + hash + ")";
  10813. return hash + "[" + make(subscript) + "]";
  10814. },
  10815. "object": function(props) {
  10816. var obj_needs_parens = needs_parens(this);
  10817. if (props.length == 0)
  10818. return obj_needs_parens ? "({})" : "{}";
  10819. var out = "{" + newline + with_indent(function(){
  10820. return MAP(props, function(p){
  10821. if (p.length == 3) {
  10822. // getter/setter. The name is in p[0], the arg.list in p[1][2], the
  10823. // body in p[1][3] and type ("get" / "set") in p[2].
  10824. return indent(make_function(p[0], p[1][2], p[1][3], p[2], true));
  10825. }
  10826. var key = p[0], val = parenthesize(p[1], "seq");
  10827. if (options.quote_keys) {
  10828. key = encode_string(key);
  10829. } else if ((typeof key == "number" || !beautify && +key + "" == key)
  10830. && parseFloat(key) >= 0) {
  10831. key = make_num(+key);
  10832. } else if (!is_identifier(key)) {
  10833. key = encode_string(key);
  10834. }
  10835. return indent(add_spaces(beautify && options.space_colon
  10836. ? [ key, ":", val ]
  10837. : [ key + ":", val ]));
  10838. }).join("," + newline);
  10839. }) + newline + indent("}");
  10840. return obj_needs_parens ? "(" + out + ")" : out;
  10841. },
  10842. "regexp": function(rx, mods) {
  10843. if (options.ascii_only) rx = to_ascii(rx);
  10844. return "/" + rx + "/" + mods;
  10845. },
  10846. "array": function(elements) {
  10847. if (elements.length == 0) return "[]";
  10848. return add_spaces([ "[", add_commas(MAP(elements, function(el, i){
  10849. if (!beautify && el[0] == "atom" && el[1] == "undefined") return i === elements.length - 1 ? "," : "";
  10850. return parenthesize(el, "seq");
  10851. })), "]" ]);
  10852. },
  10853. "stat": function(stmt) {
  10854. return stmt != null
  10855. ? make(stmt).replace(/;*\s*$/, ";")
  10856. : ";";
  10857. },
  10858. "seq": function() {
  10859. return add_commas(MAP(slice(arguments), make));
  10860. },
  10861. "label": function(name, block) {
  10862. return add_spaces([ make_name(name), ":", make(block) ]);
  10863. },
  10864. "with": function(expr, block) {
  10865. return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
  10866. },
  10867. "atom": function(name) {
  10868. return make_name(name);
  10869. },
  10870. "directive": function(dir) {
  10871. return make_string(dir) + ";";
  10872. }
  10873. }, function(){ return make(ast) });
  10874. // The squeezer replaces "block"-s that contain only a single
  10875. // statement with the statement itself; technically, the AST
  10876. // is correct, but this can create problems when we output an
  10877. // IF having an ELSE clause where the THEN clause ends in an
  10878. // IF *without* an ELSE block (then the outer ELSE would refer
  10879. // to the inner IF). This function checks for this case and
  10880. // adds the block brackets if needed.
  10881. function make_then(th) {
  10882. if (th == null) return ";";
  10883. if (th[0] == "do") {
  10884. // https://github.com/mishoo/UglifyJS/issues/#issue/57
  10885. // IE croaks with "syntax error" on code like this:
  10886. // if (foo) do ... while(cond); else ...
  10887. // we need block brackets around do/while
  10888. return make_block([ th ]);
  10889. }
  10890. var b = th;
  10891. while (true) {
  10892. var type = b[0];
  10893. if (type == "if") {
  10894. if (!b[3])
  10895. // no else, we must add the block
  10896. return make([ "block", [ th ]]);
  10897. b = b[3];
  10898. }
  10899. else if (type == "while" || type == "do") b = b[2];
  10900. else if (type == "for" || type == "for-in") b = b[4];
  10901. else break;
  10902. }
  10903. return make(th);
  10904. };
  10905. function make_function(name, args, body, keyword, no_parens) {
  10906. var out = keyword || "function";
  10907. if (name) {
  10908. out += " " + make_name(name);
  10909. }
  10910. out += "(" + add_commas(MAP(args, make_name)) + ")";
  10911. out = add_spaces([ out, make_block(body) ]);
  10912. return (!no_parens && needs_parens(this)) ? "(" + out + ")" : out;
  10913. };
  10914. function must_has_semicolon(node) {
  10915. switch (node[0]) {
  10916. case "with":
  10917. case "while":
  10918. return empty(node[2]) || must_has_semicolon(node[2]);
  10919. case "for":
  10920. case "for-in":
  10921. return empty(node[4]) || must_has_semicolon(node[4]);
  10922. case "if":
  10923. if (empty(node[2]) && !node[3]) return true; // `if' with empty `then' and no `else'
  10924. if (node[3]) {
  10925. if (empty(node[3])) return true; // `else' present but empty
  10926. return must_has_semicolon(node[3]); // dive into the `else' branch
  10927. }
  10928. return must_has_semicolon(node[2]); // dive into the `then' branch
  10929. case "directive":
  10930. return true;
  10931. }
  10932. };
  10933. function make_block_statements(statements, noindent) {
  10934. for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
  10935. var stat = statements[i];
  10936. var code = make(stat);
  10937. if (code != ";") {
  10938. if (!beautify && i == last && !must_has_semicolon(stat)) {
  10939. code = code.replace(/;+\s*$/, "");
  10940. }
  10941. a.push(code);
  10942. }
  10943. }
  10944. return noindent ? a : MAP(a, indent);
  10945. };
  10946. function make_switch_block(body) {
  10947. var n = body.length;
  10948. if (n == 0) return "{}";
  10949. return "{" + newline + MAP(body, function(branch, i){
  10950. var has_body = branch[1].length > 0, code = with_indent(function(){
  10951. return indent(branch[0]
  10952. ? add_spaces([ "case", make(branch[0]) + ":" ])
  10953. : "default:");
  10954. }, 0.5) + (has_body ? newline + with_indent(function(){
  10955. return make_block_statements(branch[1]).join(newline);
  10956. }) : "");
  10957. if (!beautify && has_body && i < n - 1)
  10958. code += ";";
  10959. return code;
  10960. }).join(newline) + newline + indent("}");
  10961. };
  10962. function make_block(statements) {
  10963. if (!statements) return ";";
  10964. if (statements.length == 0) return "{}";
  10965. return "{" + newline + with_indent(function(){
  10966. return make_block_statements(statements).join(newline);
  10967. }) + newline + indent("}");
  10968. };
  10969. function make_1vardef(def) {
  10970. var name = def[0], val = def[1];
  10971. if (val != null)
  10972. name = add_spaces([ make_name(name), "=", parenthesize(val, "seq") ]);
  10973. return name;
  10974. };
  10975. };
  10976. function split_lines(code, max_line_length) {
  10977. var splits = [ 0 ];
  10978. jsp.parse(function(){
  10979. var next_token = jsp.tokenizer(code);
  10980. var last_split = 0;
  10981. var prev_token;
  10982. function current_length(tok) {
  10983. return tok.pos - last_split;
  10984. };
  10985. function split_here(tok) {
  10986. last_split = tok.pos;
  10987. splits.push(last_split);
  10988. };
  10989. function custom(){
  10990. var tok = next_token.apply(this, arguments);
  10991. out: {
  10992. if (prev_token) {
  10993. if (prev_token.type == "keyword") break out;
  10994. }
  10995. if (current_length(tok) > max_line_length) {
  10996. switch (tok.type) {
  10997. case "keyword":
  10998. case "atom":
  10999. case "name":
  11000. case "punc":
  11001. split_here(tok);
  11002. break out;
  11003. }
  11004. }
  11005. }
  11006. prev_token = tok;
  11007. return tok;
  11008. };
  11009. custom.context = function() {
  11010. return next_token.context.apply(this, arguments);
  11011. };
  11012. return custom;
  11013. }());
  11014. return splits.map(function(pos, i){
  11015. return code.substring(pos, splits[i + 1] || code.length);
  11016. }).join("\n");
  11017. };
  11018. /* -----[ Utilities ]----- */
  11019. function repeat_string(str, i) {
  11020. if (i <= 0) return "";
  11021. if (i == 1) return str;
  11022. var d = repeat_string(str, i >> 1);
  11023. d += d;
  11024. if (i & 1) d += str;
  11025. return d;
  11026. };
  11027. function defaults(args, defs) {
  11028. var ret = {};
  11029. if (args === true)
  11030. args = {};
  11031. for (var i in defs) if (HOP(defs, i)) {
  11032. ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
  11033. }
  11034. return ret;
  11035. };
  11036. function is_identifier(name) {
  11037. return /^[a-z_$][a-z0-9_$]*$/i.test(name)
  11038. && name != "this"
  11039. && !HOP(jsp.KEYWORDS_ATOM, name)
  11040. && !HOP(jsp.RESERVED_WORDS, name)
  11041. && !HOP(jsp.KEYWORDS, name);
  11042. };
  11043. function HOP(obj, prop) {
  11044. return Object.prototype.hasOwnProperty.call(obj, prop);
  11045. };
  11046. // some utilities
  11047. var MAP;
  11048. (function(){
  11049. MAP = function(a, f, o) {
  11050. var ret = [], top = [], i;
  11051. function doit() {
  11052. var val = f.call(o, a[i], i);
  11053. if (val instanceof AtTop) {
  11054. val = val.v;
  11055. if (val instanceof Splice) {
  11056. top.push.apply(top, val.v);
  11057. } else {
  11058. top.push(val);
  11059. }
  11060. }
  11061. else if (val != skip) {
  11062. if (val instanceof Splice) {
  11063. ret.push.apply(ret, val.v);
  11064. } else {
  11065. ret.push(val);
  11066. }
  11067. }
  11068. };
  11069. if (a instanceof Array) for (i = 0; i < a.length; ++i) doit();
  11070. else for (i in a) if (HOP(a, i)) doit();
  11071. return top.concat(ret);
  11072. };
  11073. MAP.at_top = function(val) { return new AtTop(val) };
  11074. MAP.splice = function(val) { return new Splice(val) };
  11075. var skip = MAP.skip = {};
  11076. function AtTop(val) { this.v = val };
  11077. function Splice(val) { this.v = val };
  11078. })();
  11079. /* -----[ Exports ]----- */
  11080. exports.ast_walker = ast_walker;
  11081. exports.ast_mangle = ast_mangle;
  11082. exports.ast_squeeze = ast_squeeze;
  11083. exports.ast_lift_variables = ast_lift_variables;
  11084. exports.gen_code = gen_code;
  11085. exports.ast_add_scope = ast_add_scope;
  11086. exports.set_logger = function(logger) { warn = logger };
  11087. exports.make_string = make_string;
  11088. exports.split_lines = split_lines;
  11089. exports.MAP = MAP;
  11090. // keep this last!
  11091. exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more;
  11092. // Local variables:
  11093. // js-indent-level: 4
  11094. // End:
  11095. });
  11096. define('uglifyjs/index', ["require", "exports", "module", "./parse-js", "./process", "./consolidator"], function(require, exports, module) {
  11097. //convienence function(src, [options]);
  11098. function uglify(orig_code, options){
  11099. options || (options = {});
  11100. var jsp = uglify.parser;
  11101. var pro = uglify.uglify;
  11102. var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST
  11103. ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names
  11104. ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations
  11105. var final_code = pro.gen_code(ast, options.gen_options); // compressed code here
  11106. return final_code;
  11107. };
  11108. uglify.parser = require("./parse-js");
  11109. uglify.uglify = require("./process");
  11110. uglify.consolidator = require("./consolidator");
  11111. module.exports = uglify
  11112. });/* -*- Mode: js; js-indent-level: 2; -*- */
  11113. /*
  11114. * Copyright 2011 Mozilla Foundation and contributors
  11115. * Licensed under the New BSD license. See LICENSE or:
  11116. * http://opensource.org/licenses/BSD-3-Clause
  11117. */
  11118. define('source-map/array-set', function (require, exports, module) {
  11119. /**
  11120. * A data structure which is a combination of an array and a set. Adding a new
  11121. * member is O(1), testing for membership is O(1), and finding the index of an
  11122. * element is O(1). Removing elements from the set is not supported. Only
  11123. * strings are supported for membership.
  11124. */
  11125. function ArraySet() {
  11126. this._array = [];
  11127. this._set = {};
  11128. }
  11129. /**
  11130. * Static method for creating ArraySet instances from an existing array.
  11131. */
  11132. ArraySet.fromArray = function ArraySet_fromArray(aArray) {
  11133. var set = new ArraySet();
  11134. for (var i = 0, len = aArray.length; i < len; i++) {
  11135. set.add(aArray[i]);
  11136. }
  11137. return set;
  11138. };
  11139. /**
  11140. * Because behavior goes wacky when you set `__proto__` on `this._set`, we
  11141. * have to prefix all the strings in our set with an arbitrary character.
  11142. *
  11143. * See https://github.com/mozilla/source-map/pull/31 and
  11144. * https://github.com/mozilla/source-map/issues/30
  11145. *
  11146. * @param String aStr
  11147. */
  11148. ArraySet.prototype._toSetString = function ArraySet__toSetString (aStr) {
  11149. return "$" + aStr;
  11150. };
  11151. /**
  11152. * Add the given string to this set.
  11153. *
  11154. * @param String aStr
  11155. */
  11156. ArraySet.prototype.add = function ArraySet_add(aStr) {
  11157. if (this.has(aStr)) {
  11158. // Already a member; nothing to do.
  11159. return;
  11160. }
  11161. var idx = this._array.length;
  11162. this._array.push(aStr);
  11163. this._set[this._toSetString(aStr)] = idx;
  11164. };
  11165. /**
  11166. * Is the given string a member of this set?
  11167. *
  11168. * @param String aStr
  11169. */
  11170. ArraySet.prototype.has = function ArraySet_has(aStr) {
  11171. return Object.prototype.hasOwnProperty.call(this._set,
  11172. this._toSetString(aStr));
  11173. };
  11174. /**
  11175. * What is the index of the given string in the array?
  11176. *
  11177. * @param String aStr
  11178. */
  11179. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  11180. if (this.has(aStr)) {
  11181. return this._set[this._toSetString(aStr)];
  11182. }
  11183. throw new Error('"' + aStr + '" is not in the set.');
  11184. };
  11185. /**
  11186. * What is the element at the given index?
  11187. *
  11188. * @param Number aIdx
  11189. */
  11190. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  11191. if (aIdx >= 0 && aIdx < this._array.length) {
  11192. return this._array[aIdx];
  11193. }
  11194. throw new Error('No element indexed by ' + aIdx);
  11195. };
  11196. /**
  11197. * Returns the array representation of this set (which has the proper indices
  11198. * indicated by indexOf). Note that this is a copy of the internal array used
  11199. * for storing the members so that no one can mess with internal state.
  11200. */
  11201. ArraySet.prototype.toArray = function ArraySet_toArray() {
  11202. return this._array.slice();
  11203. };
  11204. exports.ArraySet = ArraySet;
  11205. });
  11206. /* -*- Mode: js; js-indent-level: 2; -*- */
  11207. /*
  11208. * Copyright 2011 Mozilla Foundation and contributors
  11209. * Licensed under the New BSD license. See LICENSE or:
  11210. * http://opensource.org/licenses/BSD-3-Clause
  11211. *
  11212. * Based on the Base 64 VLQ implementation in Closure Compiler:
  11213. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  11214. *
  11215. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  11216. * Redistribution and use in source and binary forms, with or without
  11217. * modification, are permitted provided that the following conditions are
  11218. * met:
  11219. *
  11220. * * Redistributions of source code must retain the above copyright
  11221. * notice, this list of conditions and the following disclaimer.
  11222. * * Redistributions in binary form must reproduce the above
  11223. * copyright notice, this list of conditions and the following
  11224. * disclaimer in the documentation and/or other materials provided
  11225. * with the distribution.
  11226. * * Neither the name of Google Inc. nor the names of its
  11227. * contributors may be used to endorse or promote products derived
  11228. * from this software without specific prior written permission.
  11229. *
  11230. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  11231. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  11232. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  11233. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  11234. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  11235. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11236. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  11237. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11238. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  11239. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  11240. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  11241. */
  11242. define('source-map/base64-vlq', function (require, exports, module) {
  11243. var base64 = require('./base64');
  11244. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  11245. // length quantities we use in the source map spec, the first bit is the sign,
  11246. // the next four bits are the actual value, and the 6th bit is the
  11247. // continuation bit. The continuation bit tells us whether there are more
  11248. // digits in this value following this digit.
  11249. //
  11250. // Continuation
  11251. // | Sign
  11252. // | |
  11253. // V V
  11254. // 101011
  11255. var VLQ_BASE_SHIFT = 5;
  11256. // binary: 100000
  11257. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  11258. // binary: 011111
  11259. var VLQ_BASE_MASK = VLQ_BASE - 1;
  11260. // binary: 100000
  11261. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  11262. /**
  11263. * Converts from a two-complement value to a value where the sign bit is
  11264. * is placed in the least significant bit. For example, as decimals:
  11265. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  11266. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  11267. */
  11268. function toVLQSigned(aValue) {
  11269. return aValue < 0
  11270. ? ((-aValue) << 1) + 1
  11271. : (aValue << 1) + 0;
  11272. }
  11273. /**
  11274. * Converts to a two-complement value from a value where the sign bit is
  11275. * is placed in the least significant bit. For example, as decimals:
  11276. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  11277. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  11278. */
  11279. function fromVLQSigned(aValue) {
  11280. var isNegative = (aValue & 1) === 1;
  11281. var shifted = aValue >> 1;
  11282. return isNegative
  11283. ? -shifted
  11284. : shifted;
  11285. }
  11286. /**
  11287. * Returns the base 64 VLQ encoded value.
  11288. */
  11289. exports.encode = function base64VLQ_encode(aValue) {
  11290. var encoded = "";
  11291. var digit;
  11292. var vlq = toVLQSigned(aValue);
  11293. do {
  11294. digit = vlq & VLQ_BASE_MASK;
  11295. vlq >>>= VLQ_BASE_SHIFT;
  11296. if (vlq > 0) {
  11297. // There are still more digits in this value, so we must make sure the
  11298. // continuation bit is marked.
  11299. digit |= VLQ_CONTINUATION_BIT;
  11300. }
  11301. encoded += base64.encode(digit);
  11302. } while (vlq > 0);
  11303. return encoded;
  11304. };
  11305. /**
  11306. * Decodes the next base 64 VLQ value from the given string and returns the
  11307. * value and the rest of the string.
  11308. */
  11309. exports.decode = function base64VLQ_decode(aStr) {
  11310. var i = 0;
  11311. var strLen = aStr.length;
  11312. var result = 0;
  11313. var shift = 0;
  11314. var continuation, digit;
  11315. do {
  11316. if (i >= strLen) {
  11317. throw new Error("Expected more digits in base 64 VLQ value.");
  11318. }
  11319. digit = base64.decode(aStr.charAt(i++));
  11320. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  11321. digit &= VLQ_BASE_MASK;
  11322. result = result + (digit << shift);
  11323. shift += VLQ_BASE_SHIFT;
  11324. } while (continuation);
  11325. return {
  11326. value: fromVLQSigned(result),
  11327. rest: aStr.slice(i)
  11328. };
  11329. };
  11330. });
  11331. /* -*- Mode: js; js-indent-level: 2; -*- */
  11332. /*
  11333. * Copyright 2011 Mozilla Foundation and contributors
  11334. * Licensed under the New BSD license. See LICENSE or:
  11335. * http://opensource.org/licenses/BSD-3-Clause
  11336. */
  11337. define('source-map/base64', function (require, exports, module) {
  11338. var charToIntMap = {};
  11339. var intToCharMap = {};
  11340. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  11341. .split('')
  11342. .forEach(function (ch, index) {
  11343. charToIntMap[ch] = index;
  11344. intToCharMap[index] = ch;
  11345. });
  11346. /**
  11347. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  11348. */
  11349. exports.encode = function base64_encode(aNumber) {
  11350. if (aNumber in intToCharMap) {
  11351. return intToCharMap[aNumber];
  11352. }
  11353. throw new TypeError("Must be between 0 and 63: " + aNumber);
  11354. };
  11355. /**
  11356. * Decode a single base 64 digit to an integer.
  11357. */
  11358. exports.decode = function base64_decode(aChar) {
  11359. if (aChar in charToIntMap) {
  11360. return charToIntMap[aChar];
  11361. }
  11362. throw new TypeError("Not a valid base 64 digit: " + aChar);
  11363. };
  11364. });
  11365. /* -*- Mode: js; js-indent-level: 2; -*- */
  11366. /*
  11367. * Copyright 2011 Mozilla Foundation and contributors
  11368. * Licensed under the New BSD license. See LICENSE or:
  11369. * http://opensource.org/licenses/BSD-3-Clause
  11370. */
  11371. define('source-map/binary-search', function (require, exports, module) {
  11372. /**
  11373. * Recursive implementation of binary search.
  11374. *
  11375. * @param aLow Indices here and lower do not contain the needle.
  11376. * @param aHigh Indices here and higher do not contain the needle.
  11377. * @param aNeedle The element being searched for.
  11378. * @param aHaystack The non-empty array being searched.
  11379. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  11380. */
  11381. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
  11382. // This function terminates when one of the following is true:
  11383. //
  11384. // 1. We find the exact element we are looking for.
  11385. //
  11386. // 2. We did not find the exact element, but we can return the next
  11387. // closest element that is less than that element.
  11388. //
  11389. // 3. We did not find the exact element, and there is no next-closest
  11390. // element which is less than the one we are searching for, so we
  11391. // return null.
  11392. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  11393. var cmp = aCompare(aNeedle, aHaystack[mid]);
  11394. if (cmp === 0) {
  11395. // Found the element we are looking for.
  11396. return aHaystack[mid];
  11397. }
  11398. else if (cmp > 0) {
  11399. // aHaystack[mid] is greater than our needle.
  11400. if (aHigh - mid > 1) {
  11401. // The element is in the upper half.
  11402. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
  11403. }
  11404. // We did not find an exact match, return the next closest one
  11405. // (termination case 2).
  11406. return aHaystack[mid];
  11407. }
  11408. else {
  11409. // aHaystack[mid] is less than our needle.
  11410. if (mid - aLow > 1) {
  11411. // The element is in the lower half.
  11412. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
  11413. }
  11414. // The exact needle element was not found in this haystack. Determine if
  11415. // we are in termination case (2) or (3) and return the appropriate thing.
  11416. return aLow < 0
  11417. ? null
  11418. : aHaystack[aLow];
  11419. }
  11420. }
  11421. /**
  11422. * This is an implementation of binary search which will always try and return
  11423. * the next lowest value checked if there is no exact hit. This is because
  11424. * mappings between original and generated line/col pairs are single points,
  11425. * and there is an implicit region between each of them, so a miss just means
  11426. * that you aren't on the very start of a region.
  11427. *
  11428. * @param aNeedle The element you are looking for.
  11429. * @param aHaystack The array that is being searched.
  11430. * @param aCompare A function which takes the needle and an element in the
  11431. * array and returns -1, 0, or 1 depending on whether the needle is less
  11432. * than, equal to, or greater than the element, respectively.
  11433. */
  11434. exports.search = function search(aNeedle, aHaystack, aCompare) {
  11435. return aHaystack.length > 0
  11436. ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
  11437. : null;
  11438. };
  11439. });
  11440. /* -*- Mode: js; js-indent-level: 2; -*- */
  11441. /*
  11442. * Copyright 2011 Mozilla Foundation and contributors
  11443. * Licensed under the New BSD license. See LICENSE or:
  11444. * http://opensource.org/licenses/BSD-3-Clause
  11445. */
  11446. define('source-map/source-map-consumer', function (require, exports, module) {
  11447. var util = require('./util');
  11448. var binarySearch = require('./binary-search');
  11449. var ArraySet = require('./array-set').ArraySet;
  11450. var base64VLQ = require('./base64-vlq');
  11451. /**
  11452. * A SourceMapConsumer instance represents a parsed source map which we can
  11453. * query for information about the original file positions by giving it a file
  11454. * position in the generated source.
  11455. *
  11456. * The only parameter is the raw source map (either as a JSON string, or
  11457. * already parsed to an object). According to the spec, source maps have the
  11458. * following attributes:
  11459. *
  11460. * - version: Which version of the source map spec this map is following.
  11461. * - sources: An array of URLs to the original source files.
  11462. * - names: An array of identifiers which can be referrenced by individual mappings.
  11463. * - sourceRoot: Optional. The URL root from which all sources are relative.
  11464. * - mappings: A string of base64 VLQs which contain the actual mappings.
  11465. * - file: The generated file this source map is associated with.
  11466. *
  11467. * Here is an example source map, taken from the source map spec[0]:
  11468. *
  11469. * {
  11470. * version : 3,
  11471. * file: "out.js",
  11472. * sourceRoot : "",
  11473. * sources: ["foo.js", "bar.js"],
  11474. * names: ["src", "maps", "are", "fun"],
  11475. * mappings: "AA,AB;;ABCDE;"
  11476. * }
  11477. *
  11478. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  11479. */
  11480. function SourceMapConsumer(aSourceMap) {
  11481. var sourceMap = aSourceMap;
  11482. if (typeof aSourceMap === 'string') {
  11483. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  11484. }
  11485. var version = util.getArg(sourceMap, 'version');
  11486. var sources = util.getArg(sourceMap, 'sources');
  11487. var names = util.getArg(sourceMap, 'names');
  11488. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  11489. var mappings = util.getArg(sourceMap, 'mappings');
  11490. var file = util.getArg(sourceMap, 'file');
  11491. if (version !== this._version) {
  11492. throw new Error('Unsupported version: ' + version);
  11493. }
  11494. this._names = ArraySet.fromArray(names);
  11495. this._sources = ArraySet.fromArray(sources);
  11496. this._sourceRoot = sourceRoot;
  11497. this.file = file;
  11498. // `this._generatedMappings` and `this._originalMappings` hold the parsed
  11499. // mapping coordinates from the source map's "mappings" attribute. Each
  11500. // object in the array is of the form
  11501. //
  11502. // {
  11503. // generatedLine: The line number in the generated code,
  11504. // generatedColumn: The column number in the generated code,
  11505. // source: The path to the original source file that generated this
  11506. // chunk of code,
  11507. // originalLine: The line number in the original source that
  11508. // corresponds to this chunk of generated code,
  11509. // originalColumn: The column number in the original source that
  11510. // corresponds to this chunk of generated code,
  11511. // name: The name of the original symbol which generated this chunk of
  11512. // code.
  11513. // }
  11514. //
  11515. // All properties except for `generatedLine` and `generatedColumn` can be
  11516. // `null`.
  11517. //
  11518. // `this._generatedMappings` is ordered by the generated positions.
  11519. //
  11520. // `this._originalMappings` is ordered by the original positions.
  11521. this._generatedMappings = [];
  11522. this._originalMappings = [];
  11523. this._parseMappings(mappings, sourceRoot);
  11524. }
  11525. /**
  11526. * The version of the source mapping spec that we are consuming.
  11527. */
  11528. SourceMapConsumer.prototype._version = 3;
  11529. /**
  11530. * The list of original sources.
  11531. */
  11532. Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
  11533. get: function () {
  11534. return this._sources.toArray().map(function (s) {
  11535. return this._sourceRoot ? util.join(this._sourceRoot, s) : s;
  11536. }, this);
  11537. }
  11538. });
  11539. /**
  11540. * Parse the mappings in a string in to a data structure which we can easily
  11541. * query (an ordered list in this._generatedMappings).
  11542. */
  11543. SourceMapConsumer.prototype._parseMappings =
  11544. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  11545. var generatedLine = 1;
  11546. var previousGeneratedColumn = 0;
  11547. var previousOriginalLine = 0;
  11548. var previousOriginalColumn = 0;
  11549. var previousSource = 0;
  11550. var previousName = 0;
  11551. var mappingSeparator = /^[,;]/;
  11552. var str = aStr;
  11553. var mapping;
  11554. var temp;
  11555. while (str.length > 0) {
  11556. if (str.charAt(0) === ';') {
  11557. generatedLine++;
  11558. str = str.slice(1);
  11559. previousGeneratedColumn = 0;
  11560. }
  11561. else if (str.charAt(0) === ',') {
  11562. str = str.slice(1);
  11563. }
  11564. else {
  11565. mapping = {};
  11566. mapping.generatedLine = generatedLine;
  11567. // Generated column.
  11568. temp = base64VLQ.decode(str);
  11569. mapping.generatedColumn = previousGeneratedColumn + temp.value;
  11570. previousGeneratedColumn = mapping.generatedColumn;
  11571. str = temp.rest;
  11572. if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
  11573. // Original source.
  11574. temp = base64VLQ.decode(str);
  11575. if (aSourceRoot) {
  11576. mapping.source = util.join(aSourceRoot, this._sources.at(previousSource + temp.value));
  11577. }
  11578. else {
  11579. mapping.source = this._sources.at(previousSource + temp.value);
  11580. }
  11581. previousSource += temp.value;
  11582. str = temp.rest;
  11583. if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
  11584. throw new Error('Found a source, but no line and column');
  11585. }
  11586. // Original line.
  11587. temp = base64VLQ.decode(str);
  11588. mapping.originalLine = previousOriginalLine + temp.value;
  11589. previousOriginalLine = mapping.originalLine;
  11590. // Lines are stored 0-based
  11591. mapping.originalLine += 1;
  11592. str = temp.rest;
  11593. if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
  11594. throw new Error('Found a source and line, but no column');
  11595. }
  11596. // Original column.
  11597. temp = base64VLQ.decode(str);
  11598. mapping.originalColumn = previousOriginalColumn + temp.value;
  11599. previousOriginalColumn = mapping.originalColumn;
  11600. str = temp.rest;
  11601. if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
  11602. // Original name.
  11603. temp = base64VLQ.decode(str);
  11604. mapping.name = this._names.at(previousName + temp.value);
  11605. previousName += temp.value;
  11606. str = temp.rest;
  11607. }
  11608. }
  11609. this._generatedMappings.push(mapping);
  11610. this._originalMappings.push(mapping);
  11611. }
  11612. }
  11613. this._originalMappings.sort(this._compareOriginalPositions);
  11614. };
  11615. /**
  11616. * Comparator between two mappings where the original positions are compared.
  11617. */
  11618. SourceMapConsumer.prototype._compareOriginalPositions =
  11619. function SourceMapConsumer_compareOriginalPositions(mappingA, mappingB) {
  11620. if (mappingA.source > mappingB.source) {
  11621. return 1;
  11622. }
  11623. else if (mappingA.source < mappingB.source) {
  11624. return -1;
  11625. }
  11626. else {
  11627. var cmp = mappingA.originalLine - mappingB.originalLine;
  11628. return cmp === 0
  11629. ? mappingA.originalColumn - mappingB.originalColumn
  11630. : cmp;
  11631. }
  11632. };
  11633. /**
  11634. * Comparator between two mappings where the generated positions are compared.
  11635. */
  11636. SourceMapConsumer.prototype._compareGeneratedPositions =
  11637. function SourceMapConsumer_compareGeneratedPositions(mappingA, mappingB) {
  11638. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  11639. return cmp === 0
  11640. ? mappingA.generatedColumn - mappingB.generatedColumn
  11641. : cmp;
  11642. };
  11643. /**
  11644. * Find the mapping that best matches the hypothetical "needle" mapping that
  11645. * we are searching for in the given "haystack" of mappings.
  11646. */
  11647. SourceMapConsumer.prototype._findMapping =
  11648. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  11649. aColumnName, aComparator) {
  11650. // To return the position we are searching for, we must first find the
  11651. // mapping for the given position and then return the opposite position it
  11652. // points to. Because the mappings are sorted, we can use binary search to
  11653. // find the best mapping.
  11654. if (aNeedle[aLineName] <= 0) {
  11655. throw new TypeError('Line must be greater than or equal to 1, got '
  11656. + aNeedle[aLineName]);
  11657. }
  11658. if (aNeedle[aColumnName] < 0) {
  11659. throw new TypeError('Column must be greater than or equal to 0, got '
  11660. + aNeedle[aColumnName]);
  11661. }
  11662. return binarySearch.search(aNeedle, aMappings, aComparator);
  11663. };
  11664. /**
  11665. * Returns the original source, line, and column information for the generated
  11666. * source's line and column positions provided. The only argument is an object
  11667. * with the following properties:
  11668. *
  11669. * - line: The line number in the generated source.
  11670. * - column: The column number in the generated source.
  11671. *
  11672. * and an object is returned with the following properties:
  11673. *
  11674. * - source: The original source file, or null.
  11675. * - line: The line number in the original source, or null.
  11676. * - column: The column number in the original source, or null.
  11677. * - name: The original identifier, or null.
  11678. */
  11679. SourceMapConsumer.prototype.originalPositionFor =
  11680. function SourceMapConsumer_originalPositionFor(aArgs) {
  11681. var needle = {
  11682. generatedLine: util.getArg(aArgs, 'line'),
  11683. generatedColumn: util.getArg(aArgs, 'column')
  11684. };
  11685. var mapping = this._findMapping(needle,
  11686. this._generatedMappings,
  11687. "generatedLine",
  11688. "generatedColumn",
  11689. this._compareGeneratedPositions)
  11690. if (mapping) {
  11691. return {
  11692. source: util.getArg(mapping, 'source', null),
  11693. line: util.getArg(mapping, 'originalLine', null),
  11694. column: util.getArg(mapping, 'originalColumn', null),
  11695. name: util.getArg(mapping, 'name', null)
  11696. };
  11697. }
  11698. return {
  11699. source: null,
  11700. line: null,
  11701. column: null,
  11702. name: null
  11703. };
  11704. };
  11705. /**
  11706. * Returns the generated line and column information for the original source,
  11707. * line, and column positions provided. The only argument is an object with
  11708. * the following properties:
  11709. *
  11710. * - source: The filename of the original source.
  11711. * - line: The line number in the original source.
  11712. * - column: The column number in the original source.
  11713. *
  11714. * and an object is returned with the following properties:
  11715. *
  11716. * - line: The line number in the generated source, or null.
  11717. * - column: The column number in the generated source, or null.
  11718. */
  11719. SourceMapConsumer.prototype.generatedPositionFor =
  11720. function SourceMapConsumer_generatedPositionFor(aArgs) {
  11721. var needle = {
  11722. source: util.getArg(aArgs, 'source'),
  11723. originalLine: util.getArg(aArgs, 'line'),
  11724. originalColumn: util.getArg(aArgs, 'column')
  11725. };
  11726. var mapping = this._findMapping(needle,
  11727. this._originalMappings,
  11728. "originalLine",
  11729. "originalColumn",
  11730. this._compareOriginalPositions)
  11731. if (mapping) {
  11732. return {
  11733. line: util.getArg(mapping, 'generatedLine', null),
  11734. column: util.getArg(mapping, 'generatedColumn', null)
  11735. };
  11736. }
  11737. return {
  11738. line: null,
  11739. column: null
  11740. };
  11741. };
  11742. SourceMapConsumer.GENERATED_ORDER = 1;
  11743. SourceMapConsumer.ORIGINAL_ORDER = 2;
  11744. /**
  11745. * Iterate over each mapping between an original source/line/column and a
  11746. * generated line/column in this source map.
  11747. *
  11748. * @param Function aCallback
  11749. * The function that is called with each mapping. This function should
  11750. * not mutate the mapping.
  11751. * @param Object aContext
  11752. * Optional. If specified, this object will be the value of `this` every
  11753. * time that `aCallback` is called.
  11754. * @param aOrder
  11755. * Either `SourceMapConsumer.GENERATED_ORDER` or
  11756. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  11757. * iterate over the mappings sorted by the generated file's line/column
  11758. * order or the original's source/line/column order, respectively. Defaults to
  11759. * `SourceMapConsumer.GENERATED_ORDER`.
  11760. */
  11761. SourceMapConsumer.prototype.eachMapping =
  11762. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  11763. var context = aContext || null;
  11764. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  11765. var mappings;
  11766. switch (order) {
  11767. case SourceMapConsumer.GENERATED_ORDER:
  11768. mappings = this._generatedMappings;
  11769. break;
  11770. case SourceMapConsumer.ORIGINAL_ORDER:
  11771. mappings = this._originalMappings;
  11772. break;
  11773. default:
  11774. throw new Error("Unknown order of iteration.");
  11775. }
  11776. mappings.forEach(aCallback, context);
  11777. };
  11778. exports.SourceMapConsumer = SourceMapConsumer;
  11779. });
  11780. /* -*- Mode: js; js-indent-level: 2; -*- */
  11781. /*
  11782. * Copyright 2011 Mozilla Foundation and contributors
  11783. * Licensed under the New BSD license. See LICENSE or:
  11784. * http://opensource.org/licenses/BSD-3-Clause
  11785. */
  11786. define('source-map/source-map-generator', function (require, exports, module) {
  11787. var base64VLQ = require('./base64-vlq');
  11788. var util = require('./util');
  11789. var ArraySet = require('./array-set').ArraySet;
  11790. /**
  11791. * An instance of the SourceMapGenerator represents a source map which is
  11792. * being built incrementally. To create a new one, you must pass an object
  11793. * with the following properties:
  11794. *
  11795. * - file: The filename of the generated source.
  11796. * - sourceRoot: An optional root for all URLs in this source map.
  11797. */
  11798. function SourceMapGenerator(aArgs) {
  11799. this._file = util.getArg(aArgs, 'file');
  11800. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  11801. this._sources = new ArraySet();
  11802. this._names = new ArraySet();
  11803. this._mappings = [];
  11804. }
  11805. SourceMapGenerator.prototype._version = 3;
  11806. /**
  11807. * Add a single mapping from original source line and column to the generated
  11808. * source's line and column for this source map being created. The mapping
  11809. * object should have the following properties:
  11810. *
  11811. * - generated: An object with the generated line and column positions.
  11812. * - original: An object with the original line and column positions.
  11813. * - source: The original source file (relative to the sourceRoot).
  11814. * - name: An optional original token name for this mapping.
  11815. */
  11816. SourceMapGenerator.prototype.addMapping =
  11817. function SourceMapGenerator_addMapping(aArgs) {
  11818. var generated = util.getArg(aArgs, 'generated');
  11819. var original = util.getArg(aArgs, 'original', null);
  11820. var source = util.getArg(aArgs, 'source', null);
  11821. var name = util.getArg(aArgs, 'name', null);
  11822. this._validateMapping(generated, original, source, name);
  11823. if (source && !this._sources.has(source)) {
  11824. this._sources.add(source);
  11825. }
  11826. if (name && !this._names.has(name)) {
  11827. this._names.add(name);
  11828. }
  11829. this._mappings.push({
  11830. generated: generated,
  11831. original: original,
  11832. source: source,
  11833. name: name
  11834. });
  11835. };
  11836. /**
  11837. * A mapping can have one of the three levels of data:
  11838. *
  11839. * 1. Just the generated position.
  11840. * 2. The Generated position, original position, and original source.
  11841. * 3. Generated and original position, original source, as well as a name
  11842. * token.
  11843. *
  11844. * To maintain consistency, we validate that any new mapping being added falls
  11845. * in to one of these categories.
  11846. */
  11847. SourceMapGenerator.prototype._validateMapping =
  11848. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  11849. aName) {
  11850. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  11851. && aGenerated.line > 0 && aGenerated.column >= 0
  11852. && !aOriginal && !aSource && !aName) {
  11853. // Case 1.
  11854. return;
  11855. }
  11856. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  11857. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  11858. && aGenerated.line > 0 && aGenerated.column >= 0
  11859. && aOriginal.line > 0 && aOriginal.column >= 0
  11860. && aSource) {
  11861. // Cases 2 and 3.
  11862. return;
  11863. }
  11864. else {
  11865. throw new Error('Invalid mapping.');
  11866. }
  11867. };
  11868. /**
  11869. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  11870. * specified by the source map format.
  11871. */
  11872. SourceMapGenerator.prototype._serializeMappings =
  11873. function SourceMapGenerator_serializeMappings() {
  11874. var previousGeneratedColumn = 0;
  11875. var previousGeneratedLine = 1;
  11876. var previousOriginalColumn = 0;
  11877. var previousOriginalLine = 0;
  11878. var previousName = 0;
  11879. var previousSource = 0;
  11880. var result = '';
  11881. var mapping;
  11882. // The mappings must be guarenteed to be in sorted order before we start
  11883. // serializing them or else the generated line numbers (which are defined
  11884. // via the ';' separators) will be all messed up. Note: it might be more
  11885. // performant to maintain the sorting as we insert them, rather than as we
  11886. // serialize them, but the big O is the same either way.
  11887. this._mappings.sort(function (mappingA, mappingB) {
  11888. var cmp = mappingA.generated.line - mappingB.generated.line;
  11889. return cmp === 0
  11890. ? mappingA.generated.column - mappingB.generated.column
  11891. : cmp;
  11892. });
  11893. for (var i = 0, len = this._mappings.length; i < len; i++) {
  11894. mapping = this._mappings[i];
  11895. if (mapping.generated.line !== previousGeneratedLine) {
  11896. previousGeneratedColumn = 0;
  11897. while (mapping.generated.line !== previousGeneratedLine) {
  11898. result += ';';
  11899. previousGeneratedLine++;
  11900. }
  11901. }
  11902. else {
  11903. if (i > 0) {
  11904. result += ',';
  11905. }
  11906. }
  11907. result += base64VLQ.encode(mapping.generated.column
  11908. - previousGeneratedColumn);
  11909. previousGeneratedColumn = mapping.generated.column;
  11910. if (mapping.source && mapping.original) {
  11911. result += base64VLQ.encode(this._sources.indexOf(mapping.source)
  11912. - previousSource);
  11913. previousSource = this._sources.indexOf(mapping.source);
  11914. // lines are stored 0-based in SourceMap spec version 3
  11915. result += base64VLQ.encode(mapping.original.line - 1
  11916. - previousOriginalLine);
  11917. previousOriginalLine = mapping.original.line - 1;
  11918. result += base64VLQ.encode(mapping.original.column
  11919. - previousOriginalColumn);
  11920. previousOriginalColumn = mapping.original.column;
  11921. if (mapping.name) {
  11922. result += base64VLQ.encode(this._names.indexOf(mapping.name)
  11923. - previousName);
  11924. previousName = this._names.indexOf(mapping.name);
  11925. }
  11926. }
  11927. }
  11928. return result;
  11929. };
  11930. /**
  11931. * Externalize the source map.
  11932. */
  11933. SourceMapGenerator.prototype.toJSON =
  11934. function SourceMapGenerator_toJSON() {
  11935. var map = {
  11936. version: this._version,
  11937. file: this._file,
  11938. sources: this._sources.toArray(),
  11939. names: this._names.toArray(),
  11940. mappings: this._serializeMappings()
  11941. };
  11942. if (this._sourceRoot) {
  11943. map.sourceRoot = this._sourceRoot;
  11944. }
  11945. return map;
  11946. };
  11947. /**
  11948. * Render the source map being generated to a string.
  11949. */
  11950. SourceMapGenerator.prototype.toString =
  11951. function SourceMapGenerator_toString() {
  11952. return JSON.stringify(this);
  11953. };
  11954. exports.SourceMapGenerator = SourceMapGenerator;
  11955. });
  11956. /* -*- Mode: js; js-indent-level: 2; -*- */
  11957. /*
  11958. * Copyright 2011 Mozilla Foundation and contributors
  11959. * Licensed under the New BSD license. See LICENSE or:
  11960. * http://opensource.org/licenses/BSD-3-Clause
  11961. */
  11962. define('source-map/source-node', function (require, exports, module) {
  11963. var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
  11964. /**
  11965. * SourceNodes provide a way to abstract over interpolating/concatenating
  11966. * snippets of generated JavaScript source code while maintaining the line and
  11967. * column information associated with the original source code.
  11968. *
  11969. * @param aLine The original line number.
  11970. * @param aColumn The original column number.
  11971. * @param aSource The original source's filename.
  11972. * @param aChunks Optional. An array of strings which are snippets of
  11973. * generated JS, or other SourceNodes.
  11974. */
  11975. function SourceNode(aLine, aColumn, aSource, aChunks) {
  11976. this.children = [];
  11977. this.line = aLine;
  11978. this.column = aColumn;
  11979. this.source = aSource;
  11980. if (aChunks != null) this.add(aChunks);
  11981. }
  11982. /**
  11983. * Add a chunk of generated JS to this source node.
  11984. *
  11985. * @param aChunk A string snippet of generated JS code, another instance of
  11986. * SourceNode, or an array where each member is one of those things.
  11987. */
  11988. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  11989. if (Array.isArray(aChunk)) {
  11990. aChunk.forEach(function (chunk) {
  11991. this.add(chunk);
  11992. }, this);
  11993. }
  11994. else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
  11995. if (aChunk) {
  11996. this.children.push(aChunk);
  11997. }
  11998. }
  11999. else {
  12000. throw new TypeError(
  12001. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  12002. );
  12003. }
  12004. return this;
  12005. };
  12006. /**
  12007. * Add a chunk of generated JS to the beginning of this source node.
  12008. *
  12009. * @param aChunk A string snippet of generated JS code, another instance of
  12010. * SourceNode, or an array where each member is one of those things.
  12011. */
  12012. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  12013. if (Array.isArray(aChunk)) {
  12014. for (var i = aChunk.length-1; i >= 0; i--) {
  12015. this.prepend(aChunk[i]);
  12016. }
  12017. }
  12018. else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
  12019. this.children.unshift(aChunk);
  12020. }
  12021. else {
  12022. throw new TypeError(
  12023. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  12024. );
  12025. }
  12026. return this;
  12027. };
  12028. /**
  12029. * Walk over the tree of JS snippets in this node and its children. The
  12030. * walking function is called once for each snippet of JS and is passed that
  12031. * snippet and the its original associated source's line/column location.
  12032. *
  12033. * @param aFn The traversal function.
  12034. */
  12035. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  12036. this.children.forEach(function (chunk) {
  12037. if (chunk instanceof SourceNode) {
  12038. chunk.walk(aFn);
  12039. }
  12040. else {
  12041. if (chunk !== '') {
  12042. aFn(chunk, { source: this.source, line: this.line, column: this.column });
  12043. }
  12044. }
  12045. }, this);
  12046. };
  12047. /**
  12048. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  12049. * each of `this.children`.
  12050. *
  12051. * @param aSep The separator.
  12052. */
  12053. SourceNode.prototype.join = function SourceNode_join(aSep) {
  12054. var newChildren;
  12055. var i;
  12056. var len = this.children.length
  12057. if (len > 0) {
  12058. newChildren = [];
  12059. for (i = 0; i < len-1; i++) {
  12060. newChildren.push(this.children[i]);
  12061. newChildren.push(aSep);
  12062. }
  12063. newChildren.push(this.children[i]);
  12064. this.children = newChildren;
  12065. }
  12066. return this;
  12067. };
  12068. /**
  12069. * Call String.prototype.replace on the very right-most source snippet. Useful
  12070. * for trimming whitespace from the end of a source node, etc.
  12071. *
  12072. * @param aPattern The pattern to replace.
  12073. * @param aReplacement The thing to replace the pattern with.
  12074. */
  12075. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  12076. var lastChild = this.children[this.children.length - 1];
  12077. if (lastChild instanceof SourceNode) {
  12078. lastChild.replaceRight(aPattern, aReplacement);
  12079. }
  12080. else if (typeof lastChild === 'string') {
  12081. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  12082. }
  12083. else {
  12084. this.children.push(''.replace(aPattern, aReplacement));
  12085. }
  12086. return this;
  12087. };
  12088. /**
  12089. * Return the string representation of this source node. Walks over the tree
  12090. * and concatenates all the various snippets together to one string.
  12091. */
  12092. SourceNode.prototype.toString = function SourceNode_toString() {
  12093. var str = "";
  12094. this.walk(function (chunk) {
  12095. str += chunk;
  12096. });
  12097. return str;
  12098. };
  12099. /**
  12100. * Returns the string representation of this source node along with a source
  12101. * map.
  12102. */
  12103. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  12104. var generated = {
  12105. code: "",
  12106. line: 1,
  12107. column: 0
  12108. };
  12109. var map = new SourceMapGenerator(aArgs);
  12110. this.walk(function (chunk, original) {
  12111. generated.code += chunk;
  12112. if (original.source != null
  12113. && original.line != null
  12114. && original.column != null) {
  12115. map.addMapping({
  12116. source: original.source,
  12117. original: {
  12118. line: original.line,
  12119. column: original.column
  12120. },
  12121. generated: {
  12122. line: generated.line,
  12123. column: generated.column
  12124. }
  12125. });
  12126. }
  12127. chunk.split('').forEach(function (char) {
  12128. if (char === '\n') {
  12129. generated.line++;
  12130. generated.column = 0;
  12131. } else {
  12132. generated.column++;
  12133. }
  12134. });
  12135. });
  12136. return { code: generated.code, map: map };
  12137. };
  12138. exports.SourceNode = SourceNode;
  12139. });
  12140. /* -*- Mode: js; js-indent-level: 2; -*- */
  12141. /*
  12142. * Copyright 2011 Mozilla Foundation and contributors
  12143. * Licensed under the New BSD license. See LICENSE or:
  12144. * http://opensource.org/licenses/BSD-3-Clause
  12145. */
  12146. define('source-map/util', function (require, exports, module) {
  12147. /**
  12148. * This is a helper function for getting values from parameter/options
  12149. * objects.
  12150. *
  12151. * @param args The object we are extracting values from
  12152. * @param name The name of the property we are getting.
  12153. * @param defaultValue An optional value to return if the property is missing
  12154. * from the object. If this is not specified and the property is missing, an
  12155. * error will be thrown.
  12156. */
  12157. function getArg(aArgs, aName, aDefaultValue) {
  12158. if (aName in aArgs) {
  12159. return aArgs[aName];
  12160. } else if (arguments.length === 3) {
  12161. return aDefaultValue;
  12162. } else {
  12163. throw new Error('"' + aName + '" is a required argument.');
  12164. }
  12165. }
  12166. exports.getArg = getArg;
  12167. function join(aRoot, aPath) {
  12168. return aPath.charAt(0) === '/'
  12169. ? aPath
  12170. : aRoot.replace(/\/*$/, '') + '/' + aPath;
  12171. }
  12172. exports.join = join;
  12173. });
  12174. define('source-map', function (require, exports, module) {
  12175. /*
  12176. * Copyright 2009-2011 Mozilla Foundation and contributors
  12177. * Licensed under the New BSD license. See LICENSE.txt or:
  12178. * http://opensource.org/licenses/BSD-3-Clause
  12179. */
  12180. exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;
  12181. exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;
  12182. exports.SourceNode = require('./source-map/source-node').SourceNode;
  12183. });
  12184. //Distributed under the BSD license:
  12185. //Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  12186. define('uglifyjs2', ['exports', 'source-map', 'logger'], function (exports, MOZ_SourceMap, logger) {
  12187. (function(exports, global) {
  12188. global["UglifyJS"] = exports;
  12189. "use strict";
  12190. function array_to_hash(a) {
  12191. var ret = Object.create(null);
  12192. for (var i = 0; i < a.length; ++i) ret[a[i]] = true;
  12193. return ret;
  12194. }
  12195. function slice(a, start) {
  12196. return Array.prototype.slice.call(a, start || 0);
  12197. }
  12198. function characters(str) {
  12199. return str.split("");
  12200. }
  12201. function member(name, array) {
  12202. for (var i = array.length; --i >= 0; ) if (array[i] == name) return true;
  12203. return false;
  12204. }
  12205. function find_if(func, array) {
  12206. for (var i = 0, n = array.length; i < n; ++i) {
  12207. if (func(array[i])) return array[i];
  12208. }
  12209. }
  12210. function repeat_string(str, i) {
  12211. if (i <= 0) return "";
  12212. if (i == 1) return str;
  12213. var d = repeat_string(str, i >> 1);
  12214. d += d;
  12215. if (i & 1) d += str;
  12216. return d;
  12217. }
  12218. function DefaultsError(msg, defs) {
  12219. this.msg = msg;
  12220. this.defs = defs;
  12221. }
  12222. function defaults(args, defs, croak) {
  12223. if (args === true) args = {};
  12224. var ret = args || {};
  12225. if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i)) throw new DefaultsError("`" + i + "` is not a supported option", defs);
  12226. for (var i in defs) if (defs.hasOwnProperty(i)) {
  12227. ret[i] = args && args.hasOwnProperty(i) ? args[i] : defs[i];
  12228. }
  12229. return ret;
  12230. }
  12231. function merge(obj, ext) {
  12232. for (var i in ext) if (ext.hasOwnProperty(i)) {
  12233. obj[i] = ext[i];
  12234. }
  12235. return obj;
  12236. }
  12237. function noop() {}
  12238. var MAP = function() {
  12239. function MAP(a, f, backwards) {
  12240. var ret = [], top = [], i;
  12241. function doit() {
  12242. var val = f(a[i], i);
  12243. var is_last = val instanceof Last;
  12244. if (is_last) val = val.v;
  12245. if (val instanceof AtTop) {
  12246. val = val.v;
  12247. if (val instanceof Splice) {
  12248. top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
  12249. } else {
  12250. top.push(val);
  12251. }
  12252. } else if (val !== skip) {
  12253. if (val instanceof Splice) {
  12254. ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
  12255. } else {
  12256. ret.push(val);
  12257. }
  12258. }
  12259. return is_last;
  12260. }
  12261. if (a instanceof Array) {
  12262. if (backwards) {
  12263. for (i = a.length; --i >= 0; ) if (doit()) break;
  12264. ret.reverse();
  12265. top.reverse();
  12266. } else {
  12267. for (i = 0; i < a.length; ++i) if (doit()) break;
  12268. }
  12269. } else {
  12270. for (i in a) if (a.hasOwnProperty(i)) if (doit()) break;
  12271. }
  12272. return top.concat(ret);
  12273. }
  12274. MAP.at_top = function(val) {
  12275. return new AtTop(val);
  12276. };
  12277. MAP.splice = function(val) {
  12278. return new Splice(val);
  12279. };
  12280. MAP.last = function(val) {
  12281. return new Last(val);
  12282. };
  12283. var skip = MAP.skip = {};
  12284. function AtTop(val) {
  12285. this.v = val;
  12286. }
  12287. function Splice(val) {
  12288. this.v = val;
  12289. }
  12290. function Last(val) {
  12291. this.v = val;
  12292. }
  12293. return MAP;
  12294. }();
  12295. function push_uniq(array, el) {
  12296. if (array.indexOf(el) < 0) array.push(el);
  12297. }
  12298. function string_template(text, props) {
  12299. return text.replace(/\{(.+?)\}/g, function(str, p) {
  12300. return props[p];
  12301. });
  12302. }
  12303. function remove(array, el) {
  12304. for (var i = array.length; --i >= 0; ) {
  12305. if (array[i] === el) array.splice(i, 1);
  12306. }
  12307. }
  12308. function mergeSort(array, cmp) {
  12309. if (array.length < 2) return array.slice();
  12310. function merge(a, b) {
  12311. var r = [], ai = 0, bi = 0, i = 0;
  12312. while (ai < a.length && bi < b.length) {
  12313. cmp(a[ai], b[bi]) <= 0 ? r[i++] = a[ai++] : r[i++] = b[bi++];
  12314. }
  12315. if (ai < a.length) r.push.apply(r, a.slice(ai));
  12316. if (bi < b.length) r.push.apply(r, b.slice(bi));
  12317. return r;
  12318. }
  12319. function _ms(a) {
  12320. if (a.length <= 1) return a;
  12321. var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
  12322. left = _ms(left);
  12323. right = _ms(right);
  12324. return merge(left, right);
  12325. }
  12326. return _ms(array);
  12327. }
  12328. function set_difference(a, b) {
  12329. return a.filter(function(el) {
  12330. return b.indexOf(el) < 0;
  12331. });
  12332. }
  12333. function set_intersection(a, b) {
  12334. return a.filter(function(el) {
  12335. return b.indexOf(el) >= 0;
  12336. });
  12337. }
  12338. function makePredicate(words) {
  12339. if (!(words instanceof Array)) words = words.split(" ");
  12340. var f = "", cats = [];
  12341. out: for (var i = 0; i < words.length; ++i) {
  12342. for (var j = 0; j < cats.length; ++j) if (cats[j][0].length == words[i].length) {
  12343. cats[j].push(words[i]);
  12344. continue out;
  12345. }
  12346. cats.push([ words[i] ]);
  12347. }
  12348. function compareTo(arr) {
  12349. if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
  12350. f += "switch(str){";
  12351. for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
  12352. f += "return true}return false;";
  12353. }
  12354. if (cats.length > 3) {
  12355. cats.sort(function(a, b) {
  12356. return b.length - a.length;
  12357. });
  12358. f += "switch(str.length){";
  12359. for (var i = 0; i < cats.length; ++i) {
  12360. var cat = cats[i];
  12361. f += "case " + cat[0].length + ":";
  12362. compareTo(cat);
  12363. }
  12364. f += "}";
  12365. } else {
  12366. compareTo(words);
  12367. }
  12368. return new Function("str", f);
  12369. }
  12370. function Dictionary() {
  12371. this._values = Object.create(null);
  12372. this._size = 0;
  12373. }
  12374. Dictionary.prototype = {
  12375. set: function(key, val) {
  12376. if (!this.has(key)) ++this._size;
  12377. this._values["$" + key] = val;
  12378. return this;
  12379. },
  12380. add: function(key, val) {
  12381. if (this.has(key)) {
  12382. this.get(key).push(val);
  12383. } else {
  12384. this.set(key, [ val ]);
  12385. }
  12386. return this;
  12387. },
  12388. get: function(key) {
  12389. return this._values["$" + key];
  12390. },
  12391. del: function(key) {
  12392. if (this.has(key)) {
  12393. --this._size;
  12394. delete this._values["$" + key];
  12395. }
  12396. return this;
  12397. },
  12398. has: function(key) {
  12399. return "$" + key in this._values;
  12400. },
  12401. each: function(f) {
  12402. for (var i in this._values) f(this._values[i], i.substr(1));
  12403. },
  12404. size: function() {
  12405. return this._size;
  12406. },
  12407. map: function(f) {
  12408. var ret = [];
  12409. for (var i in this._values) ret.push(f(this._values[i], i.substr(1)));
  12410. return ret;
  12411. }
  12412. };
  12413. "use strict";
  12414. function DEFNODE(type, props, methods, base) {
  12415. if (arguments.length < 4) base = AST_Node;
  12416. if (!props) props = []; else props = props.split(/\s+/);
  12417. var self_props = props;
  12418. if (base && base.PROPS) props = props.concat(base.PROPS);
  12419. var code = "return function AST_" + type + "(props){ if (props) { ";
  12420. for (var i = props.length; --i >= 0; ) {
  12421. code += "this." + props[i] + " = props." + props[i] + ";";
  12422. }
  12423. var proto = base && new base();
  12424. if (proto && proto.initialize || methods && methods.initialize) code += "this.initialize();";
  12425. code += "}}";
  12426. var ctor = new Function(code)();
  12427. if (proto) {
  12428. ctor.prototype = proto;
  12429. ctor.BASE = base;
  12430. }
  12431. if (base) base.SUBCLASSES.push(ctor);
  12432. ctor.prototype.CTOR = ctor;
  12433. ctor.PROPS = props || null;
  12434. ctor.SELF_PROPS = self_props;
  12435. ctor.SUBCLASSES = [];
  12436. if (type) {
  12437. ctor.prototype.TYPE = ctor.TYPE = type;
  12438. }
  12439. if (methods) for (i in methods) if (methods.hasOwnProperty(i)) {
  12440. if (/^\$/.test(i)) {
  12441. ctor[i.substr(1)] = methods[i];
  12442. } else {
  12443. ctor.prototype[i] = methods[i];
  12444. }
  12445. }
  12446. ctor.DEFMETHOD = function(name, method) {
  12447. this.prototype[name] = method;
  12448. };
  12449. return ctor;
  12450. }
  12451. var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", {}, null);
  12452. var AST_Node = DEFNODE("Node", "start end", {
  12453. clone: function() {
  12454. return new this.CTOR(this);
  12455. },
  12456. $documentation: "Base class of all AST nodes",
  12457. $propdoc: {
  12458. start: "[AST_Token] The first token of this node",
  12459. end: "[AST_Token] The last token of this node"
  12460. },
  12461. _walk: function(visitor) {
  12462. return visitor._visit(this);
  12463. },
  12464. walk: function(visitor) {
  12465. return this._walk(visitor);
  12466. }
  12467. }, null);
  12468. AST_Node.warn_function = null;
  12469. AST_Node.warn = function(txt, props) {
  12470. if (AST_Node.warn_function) AST_Node.warn_function(string_template(txt, props));
  12471. };
  12472. var AST_Statement = DEFNODE("Statement", null, {
  12473. $documentation: "Base class of all statements"
  12474. });
  12475. var AST_Debugger = DEFNODE("Debugger", null, {
  12476. $documentation: "Represents a debugger statement"
  12477. }, AST_Statement);
  12478. var AST_Directive = DEFNODE("Directive", "value scope", {
  12479. $documentation: 'Represents a directive, like "use strict";',
  12480. $propdoc: {
  12481. value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
  12482. scope: "[AST_Scope/S] The scope that this directive affects"
  12483. }
  12484. }, AST_Statement);
  12485. var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
  12486. $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
  12487. $propdoc: {
  12488. body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
  12489. },
  12490. _walk: function(visitor) {
  12491. return visitor._visit(this, function() {
  12492. this.body._walk(visitor);
  12493. });
  12494. }
  12495. }, AST_Statement);
  12496. function walk_body(node, visitor) {
  12497. if (node.body instanceof AST_Statement) {
  12498. node.body._walk(visitor);
  12499. } else node.body.forEach(function(stat) {
  12500. stat._walk(visitor);
  12501. });
  12502. }
  12503. var AST_Block = DEFNODE("Block", "body", {
  12504. $documentation: "A body of statements (usually bracketed)",
  12505. $propdoc: {
  12506. body: "[AST_Statement*] an array of statements"
  12507. },
  12508. _walk: function(visitor) {
  12509. return visitor._visit(this, function() {
  12510. walk_body(this, visitor);
  12511. });
  12512. }
  12513. }, AST_Statement);
  12514. var AST_BlockStatement = DEFNODE("BlockStatement", null, {
  12515. $documentation: "A block statement"
  12516. }, AST_Block);
  12517. var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
  12518. $documentation: "The empty statement (empty block or simply a semicolon)",
  12519. _walk: function(visitor) {
  12520. return visitor._visit(this);
  12521. }
  12522. }, AST_Statement);
  12523. var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
  12524. $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
  12525. $propdoc: {
  12526. body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
  12527. },
  12528. _walk: function(visitor) {
  12529. return visitor._visit(this, function() {
  12530. this.body._walk(visitor);
  12531. });
  12532. }
  12533. }, AST_Statement);
  12534. var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
  12535. $documentation: "Statement with a label",
  12536. $propdoc: {
  12537. label: "[AST_Label] a label definition"
  12538. },
  12539. _walk: function(visitor) {
  12540. return visitor._visit(this, function() {
  12541. this.label._walk(visitor);
  12542. this.body._walk(visitor);
  12543. });
  12544. }
  12545. }, AST_StatementWithBody);
  12546. var AST_DWLoop = DEFNODE("DWLoop", "condition", {
  12547. $documentation: "Base class for do/while statements",
  12548. $propdoc: {
  12549. condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
  12550. },
  12551. _walk: function(visitor) {
  12552. return visitor._visit(this, function() {
  12553. this.condition._walk(visitor);
  12554. this.body._walk(visitor);
  12555. });
  12556. }
  12557. }, AST_StatementWithBody);
  12558. var AST_Do = DEFNODE("Do", null, {
  12559. $documentation: "A `do` statement"
  12560. }, AST_DWLoop);
  12561. var AST_While = DEFNODE("While", null, {
  12562. $documentation: "A `while` statement"
  12563. }, AST_DWLoop);
  12564. var AST_For = DEFNODE("For", "init condition step", {
  12565. $documentation: "A `for` statement",
  12566. $propdoc: {
  12567. init: "[AST_Node?] the `for` initialization code, or null if empty",
  12568. condition: "[AST_Node?] the `for` termination clause, or null if empty",
  12569. step: "[AST_Node?] the `for` update clause, or null if empty"
  12570. },
  12571. _walk: function(visitor) {
  12572. return visitor._visit(this, function() {
  12573. if (this.init) this.init._walk(visitor);
  12574. if (this.condition) this.condition._walk(visitor);
  12575. if (this.step) this.step._walk(visitor);
  12576. this.body._walk(visitor);
  12577. });
  12578. }
  12579. }, AST_StatementWithBody);
  12580. var AST_ForIn = DEFNODE("ForIn", "init name object", {
  12581. $documentation: "A `for ... in` statement",
  12582. $propdoc: {
  12583. init: "[AST_Node] the `for/in` initialization code",
  12584. name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
  12585. object: "[AST_Node] the object that we're looping through"
  12586. },
  12587. _walk: function(visitor) {
  12588. return visitor._visit(this, function() {
  12589. this.init._walk(visitor);
  12590. this.object._walk(visitor);
  12591. this.body._walk(visitor);
  12592. });
  12593. }
  12594. }, AST_StatementWithBody);
  12595. var AST_With = DEFNODE("With", "expression", {
  12596. $documentation: "A `with` statement",
  12597. $propdoc: {
  12598. expression: "[AST_Node] the `with` expression"
  12599. },
  12600. _walk: function(visitor) {
  12601. return visitor._visit(this, function() {
  12602. this.expression._walk(visitor);
  12603. this.body._walk(visitor);
  12604. });
  12605. }
  12606. }, AST_StatementWithBody);
  12607. var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
  12608. $documentation: "Base class for all statements introducing a lexical scope",
  12609. $propdoc: {
  12610. directives: "[string*/S] an array of directives declared in this scope",
  12611. variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
  12612. functions: "[Object/S] like `variables`, but only lists function declarations",
  12613. uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
  12614. uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
  12615. parent_scope: "[AST_Scope?/S] link to the parent scope",
  12616. enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
  12617. cname: "[integer/S] current index for mangling variables (used internally by the mangler)"
  12618. }
  12619. }, AST_Block);
  12620. var AST_Toplevel = DEFNODE("Toplevel", "globals", {
  12621. $documentation: "The toplevel scope",
  12622. $propdoc: {
  12623. globals: "[Object/S] a map of name -> SymbolDef for all undeclared names"
  12624. },
  12625. wrap_commonjs: function(name, export_all) {
  12626. var self = this;
  12627. var to_export = [];
  12628. if (export_all) {
  12629. self.figure_out_scope();
  12630. self.walk(new TreeWalker(function(node) {
  12631. if (node instanceof AST_SymbolDeclaration && node.definition().global) {
  12632. if (!find_if(function(n) {
  12633. return n.name == node.name;
  12634. }, to_export)) to_export.push(node);
  12635. }
  12636. }));
  12637. }
  12638. var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))";
  12639. wrapped_tl = parse(wrapped_tl);
  12640. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node) {
  12641. if (node instanceof AST_SimpleStatement) {
  12642. node = node.body;
  12643. if (node instanceof AST_String) switch (node.getValue()) {
  12644. case "$ORIG":
  12645. return MAP.splice(self.body);
  12646. case "$EXPORTS":
  12647. var body = [];
  12648. to_export.forEach(function(sym) {
  12649. body.push(new AST_SimpleStatement({
  12650. body: new AST_Assign({
  12651. left: new AST_Sub({
  12652. expression: new AST_SymbolRef({
  12653. name: "exports"
  12654. }),
  12655. property: new AST_String({
  12656. value: sym.name
  12657. })
  12658. }),
  12659. operator: "=",
  12660. right: new AST_SymbolRef(sym)
  12661. })
  12662. }));
  12663. });
  12664. return MAP.splice(body);
  12665. }
  12666. }
  12667. }));
  12668. return wrapped_tl;
  12669. }
  12670. }, AST_Scope);
  12671. var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
  12672. $documentation: "Base class for functions",
  12673. $propdoc: {
  12674. name: "[AST_SymbolDeclaration?] the name of this function",
  12675. argnames: "[AST_SymbolFunarg*] array of function arguments",
  12676. uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
  12677. },
  12678. _walk: function(visitor) {
  12679. return visitor._visit(this, function() {
  12680. if (this.name) this.name._walk(visitor);
  12681. this.argnames.forEach(function(arg) {
  12682. arg._walk(visitor);
  12683. });
  12684. walk_body(this, visitor);
  12685. });
  12686. }
  12687. }, AST_Scope);
  12688. var AST_Accessor = DEFNODE("Accessor", null, {
  12689. $documentation: "A setter/getter function"
  12690. }, AST_Lambda);
  12691. var AST_Function = DEFNODE("Function", null, {
  12692. $documentation: "A function expression"
  12693. }, AST_Lambda);
  12694. var AST_Defun = DEFNODE("Defun", null, {
  12695. $documentation: "A function definition"
  12696. }, AST_Lambda);
  12697. var AST_Jump = DEFNODE("Jump", null, {
  12698. $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
  12699. }, AST_Statement);
  12700. var AST_Exit = DEFNODE("Exit", "value", {
  12701. $documentation: "Base class for “exits” (`return` and `throw`)",
  12702. $propdoc: {
  12703. value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
  12704. },
  12705. _walk: function(visitor) {
  12706. return visitor._visit(this, this.value && function() {
  12707. this.value._walk(visitor);
  12708. });
  12709. }
  12710. }, AST_Jump);
  12711. var AST_Return = DEFNODE("Return", null, {
  12712. $documentation: "A `return` statement"
  12713. }, AST_Exit);
  12714. var AST_Throw = DEFNODE("Throw", null, {
  12715. $documentation: "A `throw` statement"
  12716. }, AST_Exit);
  12717. var AST_LoopControl = DEFNODE("LoopControl", "label", {
  12718. $documentation: "Base class for loop control statements (`break` and `continue`)",
  12719. $propdoc: {
  12720. label: "[AST_LabelRef?] the label, or null if none"
  12721. },
  12722. _walk: function(visitor) {
  12723. return visitor._visit(this, this.label && function() {
  12724. this.label._walk(visitor);
  12725. });
  12726. }
  12727. }, AST_Jump);
  12728. var AST_Break = DEFNODE("Break", null, {
  12729. $documentation: "A `break` statement"
  12730. }, AST_LoopControl);
  12731. var AST_Continue = DEFNODE("Continue", null, {
  12732. $documentation: "A `continue` statement"
  12733. }, AST_LoopControl);
  12734. var AST_If = DEFNODE("If", "condition alternative", {
  12735. $documentation: "A `if` statement",
  12736. $propdoc: {
  12737. condition: "[AST_Node] the `if` condition",
  12738. alternative: "[AST_Statement?] the `else` part, or null if not present"
  12739. },
  12740. _walk: function(visitor) {
  12741. return visitor._visit(this, function() {
  12742. this.condition._walk(visitor);
  12743. this.body._walk(visitor);
  12744. if (this.alternative) this.alternative._walk(visitor);
  12745. });
  12746. }
  12747. }, AST_StatementWithBody);
  12748. var AST_Switch = DEFNODE("Switch", "expression", {
  12749. $documentation: "A `switch` statement",
  12750. $propdoc: {
  12751. expression: "[AST_Node] the `switch` “discriminant”"
  12752. },
  12753. _walk: function(visitor) {
  12754. return visitor._visit(this, function() {
  12755. this.expression._walk(visitor);
  12756. walk_body(this, visitor);
  12757. });
  12758. }
  12759. }, AST_Block);
  12760. var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
  12761. $documentation: "Base class for `switch` branches"
  12762. }, AST_Block);
  12763. var AST_Default = DEFNODE("Default", null, {
  12764. $documentation: "A `default` switch branch"
  12765. }, AST_SwitchBranch);
  12766. var AST_Case = DEFNODE("Case", "expression", {
  12767. $documentation: "A `case` switch branch",
  12768. $propdoc: {
  12769. expression: "[AST_Node] the `case` expression"
  12770. },
  12771. _walk: function(visitor) {
  12772. return visitor._visit(this, function() {
  12773. this.expression._walk(visitor);
  12774. walk_body(this, visitor);
  12775. });
  12776. }
  12777. }, AST_SwitchBranch);
  12778. var AST_Try = DEFNODE("Try", "bcatch bfinally", {
  12779. $documentation: "A `try` statement",
  12780. $propdoc: {
  12781. bcatch: "[AST_Catch?] the catch block, or null if not present",
  12782. bfinally: "[AST_Finally?] the finally block, or null if not present"
  12783. },
  12784. _walk: function(visitor) {
  12785. return visitor._visit(this, function() {
  12786. walk_body(this, visitor);
  12787. if (this.bcatch) this.bcatch._walk(visitor);
  12788. if (this.bfinally) this.bfinally._walk(visitor);
  12789. });
  12790. }
  12791. }, AST_Block);
  12792. var AST_Catch = DEFNODE("Catch", "argname", {
  12793. $documentation: "A `catch` node; only makes sense as part of a `try` statement",
  12794. $propdoc: {
  12795. argname: "[AST_SymbolCatch] symbol for the exception"
  12796. },
  12797. _walk: function(visitor) {
  12798. return visitor._visit(this, function() {
  12799. this.argname._walk(visitor);
  12800. walk_body(this, visitor);
  12801. });
  12802. }
  12803. }, AST_Block);
  12804. var AST_Finally = DEFNODE("Finally", null, {
  12805. $documentation: "A `finally` node; only makes sense as part of a `try` statement"
  12806. }, AST_Block);
  12807. var AST_Definitions = DEFNODE("Definitions", "definitions", {
  12808. $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
  12809. $propdoc: {
  12810. definitions: "[AST_VarDef*] array of variable definitions"
  12811. },
  12812. _walk: function(visitor) {
  12813. return visitor._visit(this, function() {
  12814. this.definitions.forEach(function(def) {
  12815. def._walk(visitor);
  12816. });
  12817. });
  12818. }
  12819. }, AST_Statement);
  12820. var AST_Var = DEFNODE("Var", null, {
  12821. $documentation: "A `var` statement"
  12822. }, AST_Definitions);
  12823. var AST_Const = DEFNODE("Const", null, {
  12824. $documentation: "A `const` statement"
  12825. }, AST_Definitions);
  12826. var AST_VarDef = DEFNODE("VarDef", "name value", {
  12827. $documentation: "A variable declaration; only appears in a AST_Definitions node",
  12828. $propdoc: {
  12829. name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
  12830. value: "[AST_Node?] initializer, or null of there's no initializer"
  12831. },
  12832. _walk: function(visitor) {
  12833. return visitor._visit(this, function() {
  12834. this.name._walk(visitor);
  12835. if (this.value) this.value._walk(visitor);
  12836. });
  12837. }
  12838. });
  12839. var AST_Call = DEFNODE("Call", "expression args", {
  12840. $documentation: "A function call expression",
  12841. $propdoc: {
  12842. expression: "[AST_Node] expression to invoke as function",
  12843. args: "[AST_Node*] array of arguments"
  12844. },
  12845. _walk: function(visitor) {
  12846. return visitor._visit(this, function() {
  12847. this.expression._walk(visitor);
  12848. this.args.forEach(function(arg) {
  12849. arg._walk(visitor);
  12850. });
  12851. });
  12852. }
  12853. });
  12854. var AST_New = DEFNODE("New", null, {
  12855. $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
  12856. }, AST_Call);
  12857. var AST_Seq = DEFNODE("Seq", "car cdr", {
  12858. $documentation: "A sequence expression (two comma-separated expressions)",
  12859. $propdoc: {
  12860. car: "[AST_Node] first element in sequence",
  12861. cdr: "[AST_Node] second element in sequence"
  12862. },
  12863. $cons: function(x, y) {
  12864. var seq = new AST_Seq(x);
  12865. seq.car = x;
  12866. seq.cdr = y;
  12867. return seq;
  12868. },
  12869. $from_array: function(array) {
  12870. if (array.length == 0) return null;
  12871. if (array.length == 1) return array[0].clone();
  12872. var list = null;
  12873. for (var i = array.length; --i >= 0; ) {
  12874. list = AST_Seq.cons(array[i], list);
  12875. }
  12876. var p = list;
  12877. while (p) {
  12878. if (p.cdr && !p.cdr.cdr) {
  12879. p.cdr = p.cdr.car;
  12880. break;
  12881. }
  12882. p = p.cdr;
  12883. }
  12884. return list;
  12885. },
  12886. to_array: function() {
  12887. var p = this, a = [];
  12888. while (p) {
  12889. a.push(p.car);
  12890. if (p.cdr && !(p.cdr instanceof AST_Seq)) {
  12891. a.push(p.cdr);
  12892. break;
  12893. }
  12894. p = p.cdr;
  12895. }
  12896. return a;
  12897. },
  12898. add: function(node) {
  12899. var p = this;
  12900. while (p) {
  12901. if (!(p.cdr instanceof AST_Seq)) {
  12902. var cell = AST_Seq.cons(p.cdr, node);
  12903. return p.cdr = cell;
  12904. }
  12905. p = p.cdr;
  12906. }
  12907. },
  12908. _walk: function(visitor) {
  12909. return visitor._visit(this, function() {
  12910. this.car._walk(visitor);
  12911. if (this.cdr) this.cdr._walk(visitor);
  12912. });
  12913. }
  12914. });
  12915. var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
  12916. $documentation: 'Base class for property access expressions, i.e. `a.foo` or `a["foo"]`',
  12917. $propdoc: {
  12918. expression: "[AST_Node] the “container” expression",
  12919. 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"
  12920. }
  12921. });
  12922. var AST_Dot = DEFNODE("Dot", null, {
  12923. $documentation: "A dotted property access expression",
  12924. _walk: function(visitor) {
  12925. return visitor._visit(this, function() {
  12926. this.expression._walk(visitor);
  12927. });
  12928. }
  12929. }, AST_PropAccess);
  12930. var AST_Sub = DEFNODE("Sub", null, {
  12931. $documentation: 'Index-style property access, i.e. `a["foo"]`',
  12932. _walk: function(visitor) {
  12933. return visitor._visit(this, function() {
  12934. this.expression._walk(visitor);
  12935. this.property._walk(visitor);
  12936. });
  12937. }
  12938. }, AST_PropAccess);
  12939. var AST_Unary = DEFNODE("Unary", "operator expression", {
  12940. $documentation: "Base class for unary expressions",
  12941. $propdoc: {
  12942. operator: "[string] the operator",
  12943. expression: "[AST_Node] expression that this unary operator applies to"
  12944. },
  12945. _walk: function(visitor) {
  12946. return visitor._visit(this, function() {
  12947. this.expression._walk(visitor);
  12948. });
  12949. }
  12950. });
  12951. var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
  12952. $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
  12953. }, AST_Unary);
  12954. var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
  12955. $documentation: "Unary postfix expression, i.e. `i++`"
  12956. }, AST_Unary);
  12957. var AST_Binary = DEFNODE("Binary", "left operator right", {
  12958. $documentation: "Binary expression, i.e. `a + b`",
  12959. $propdoc: {
  12960. left: "[AST_Node] left-hand side expression",
  12961. operator: "[string] the operator",
  12962. right: "[AST_Node] right-hand side expression"
  12963. },
  12964. _walk: function(visitor) {
  12965. return visitor._visit(this, function() {
  12966. this.left._walk(visitor);
  12967. this.right._walk(visitor);
  12968. });
  12969. }
  12970. });
  12971. var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
  12972. $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
  12973. $propdoc: {
  12974. condition: "[AST_Node]",
  12975. consequent: "[AST_Node]",
  12976. alternative: "[AST_Node]"
  12977. },
  12978. _walk: function(visitor) {
  12979. return visitor._visit(this, function() {
  12980. this.condition._walk(visitor);
  12981. this.consequent._walk(visitor);
  12982. this.alternative._walk(visitor);
  12983. });
  12984. }
  12985. });
  12986. var AST_Assign = DEFNODE("Assign", null, {
  12987. $documentation: "An assignment expression — `a = b + 5`"
  12988. }, AST_Binary);
  12989. var AST_Array = DEFNODE("Array", "elements", {
  12990. $documentation: "An array literal",
  12991. $propdoc: {
  12992. elements: "[AST_Node*] array of elements"
  12993. },
  12994. _walk: function(visitor) {
  12995. return visitor._visit(this, function() {
  12996. this.elements.forEach(function(el) {
  12997. el._walk(visitor);
  12998. });
  12999. });
  13000. }
  13001. });
  13002. var AST_Object = DEFNODE("Object", "properties", {
  13003. $documentation: "An object literal",
  13004. $propdoc: {
  13005. properties: "[AST_ObjectProperty*] array of properties"
  13006. },
  13007. _walk: function(visitor) {
  13008. return visitor._visit(this, function() {
  13009. this.properties.forEach(function(prop) {
  13010. prop._walk(visitor);
  13011. });
  13012. });
  13013. }
  13014. });
  13015. var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
  13016. $documentation: "Base class for literal object properties",
  13017. $propdoc: {
  13018. key: "[string] the property name; it's always a plain string in our AST, no matter if it was a string, number or identifier in original code",
  13019. value: "[AST_Node] property value. For setters and getters this is an AST_Function."
  13020. },
  13021. _walk: function(visitor) {
  13022. return visitor._visit(this, function() {
  13023. this.value._walk(visitor);
  13024. });
  13025. }
  13026. });
  13027. var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, {
  13028. $documentation: "A key: value object property"
  13029. }, AST_ObjectProperty);
  13030. var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
  13031. $documentation: "An object setter property"
  13032. }, AST_ObjectProperty);
  13033. var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
  13034. $documentation: "An object getter property"
  13035. }, AST_ObjectProperty);
  13036. var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
  13037. $propdoc: {
  13038. name: "[string] name of this symbol",
  13039. scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
  13040. thedef: "[SymbolDef/S] the definition of this symbol"
  13041. },
  13042. $documentation: "Base class for all symbols"
  13043. });
  13044. var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
  13045. $documentation: "The name of a property accessor (setter/getter function)"
  13046. }, AST_Symbol);
  13047. var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
  13048. $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
  13049. $propdoc: {
  13050. init: "[AST_Node*/S] array of initializers for this declaration."
  13051. }
  13052. }, AST_Symbol);
  13053. var AST_SymbolVar = DEFNODE("SymbolVar", null, {
  13054. $documentation: "Symbol defining a variable"
  13055. }, AST_SymbolDeclaration);
  13056. var AST_SymbolConst = DEFNODE("SymbolConst", null, {
  13057. $documentation: "A constant declaration"
  13058. }, AST_SymbolDeclaration);
  13059. var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
  13060. $documentation: "Symbol naming a function argument"
  13061. }, AST_SymbolVar);
  13062. var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
  13063. $documentation: "Symbol defining a function"
  13064. }, AST_SymbolDeclaration);
  13065. var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
  13066. $documentation: "Symbol naming a function expression"
  13067. }, AST_SymbolDeclaration);
  13068. var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
  13069. $documentation: "Symbol naming the exception in catch"
  13070. }, AST_SymbolDeclaration);
  13071. var AST_Label = DEFNODE("Label", "references", {
  13072. $documentation: "Symbol naming a label (declaration)",
  13073. $propdoc: {
  13074. references: "[AST_LabelRef*] a list of nodes referring to this label"
  13075. }
  13076. }, AST_Symbol);
  13077. var AST_SymbolRef = DEFNODE("SymbolRef", null, {
  13078. $documentation: "Reference to some symbol (not definition/declaration)"
  13079. }, AST_Symbol);
  13080. var AST_LabelRef = DEFNODE("LabelRef", null, {
  13081. $documentation: "Reference to a label symbol"
  13082. }, AST_Symbol);
  13083. var AST_This = DEFNODE("This", null, {
  13084. $documentation: "The `this` symbol"
  13085. }, AST_Symbol);
  13086. var AST_Constant = DEFNODE("Constant", null, {
  13087. $documentation: "Base class for all constants",
  13088. getValue: function() {
  13089. return this.value;
  13090. }
  13091. });
  13092. var AST_String = DEFNODE("String", "value", {
  13093. $documentation: "A string literal",
  13094. $propdoc: {
  13095. value: "[string] the contents of this string"
  13096. }
  13097. }, AST_Constant);
  13098. var AST_Number = DEFNODE("Number", "value", {
  13099. $documentation: "A number literal",
  13100. $propdoc: {
  13101. value: "[number] the numeric value"
  13102. }
  13103. }, AST_Constant);
  13104. var AST_RegExp = DEFNODE("RegExp", "value", {
  13105. $documentation: "A regexp literal",
  13106. $propdoc: {
  13107. value: "[RegExp] the actual regexp"
  13108. }
  13109. }, AST_Constant);
  13110. var AST_Atom = DEFNODE("Atom", null, {
  13111. $documentation: "Base class for atoms"
  13112. }, AST_Constant);
  13113. var AST_Null = DEFNODE("Null", null, {
  13114. $documentation: "The `null` atom",
  13115. value: null
  13116. }, AST_Atom);
  13117. var AST_NaN = DEFNODE("NaN", null, {
  13118. $documentation: "The impossible value",
  13119. value: 0 / 0
  13120. }, AST_Atom);
  13121. var AST_Undefined = DEFNODE("Undefined", null, {
  13122. $documentation: "The `undefined` value",
  13123. value: function() {}()
  13124. }, AST_Atom);
  13125. var AST_Infinity = DEFNODE("Infinity", null, {
  13126. $documentation: "The `Infinity` value",
  13127. value: 1 / 0
  13128. }, AST_Atom);
  13129. var AST_Boolean = DEFNODE("Boolean", null, {
  13130. $documentation: "Base class for booleans"
  13131. }, AST_Atom);
  13132. var AST_False = DEFNODE("False", null, {
  13133. $documentation: "The `false` atom",
  13134. value: false
  13135. }, AST_Boolean);
  13136. var AST_True = DEFNODE("True", null, {
  13137. $documentation: "The `true` atom",
  13138. value: true
  13139. }, AST_Boolean);
  13140. function TreeWalker(callback) {
  13141. this.visit = callback;
  13142. this.stack = [];
  13143. }
  13144. TreeWalker.prototype = {
  13145. _visit: function(node, descend) {
  13146. this.stack.push(node);
  13147. var ret = this.visit(node, descend ? function() {
  13148. descend.call(node);
  13149. } : noop);
  13150. if (!ret && descend) {
  13151. descend.call(node);
  13152. }
  13153. this.stack.pop();
  13154. return ret;
  13155. },
  13156. parent: function(n) {
  13157. return this.stack[this.stack.length - 2 - (n || 0)];
  13158. },
  13159. push: function(node) {
  13160. this.stack.push(node);
  13161. },
  13162. pop: function() {
  13163. return this.stack.pop();
  13164. },
  13165. self: function() {
  13166. return this.stack[this.stack.length - 1];
  13167. },
  13168. find_parent: function(type) {
  13169. var stack = this.stack;
  13170. for (var i = stack.length; --i >= 0; ) {
  13171. var x = stack[i];
  13172. if (x instanceof type) return x;
  13173. }
  13174. },
  13175. in_boolean_context: function() {
  13176. var stack = this.stack;
  13177. var i = stack.length, self = stack[--i];
  13178. while (i > 0) {
  13179. var p = stack[--i];
  13180. if (p instanceof AST_If && p.condition === self || p instanceof AST_Conditional && p.condition === self || p instanceof AST_DWLoop && p.condition === self || p instanceof AST_For && p.condition === self || p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self) {
  13181. return true;
  13182. }
  13183. if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||"))) return false;
  13184. self = p;
  13185. }
  13186. },
  13187. loopcontrol_target: function(label) {
  13188. var stack = this.stack;
  13189. if (label) {
  13190. for (var i = stack.length; --i >= 0; ) {
  13191. var x = stack[i];
  13192. if (x instanceof AST_LabeledStatement && x.label.name == label.name) {
  13193. return x.body;
  13194. }
  13195. }
  13196. } else {
  13197. for (var i = stack.length; --i >= 0; ) {
  13198. var x = stack[i];
  13199. if (x instanceof AST_Switch || x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) return x;
  13200. }
  13201. }
  13202. }
  13203. };
  13204. "use strict";
  13205. 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";
  13206. var KEYWORDS_ATOM = "false null true";
  13207. 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" + " " + KEYWORDS_ATOM + " " + KEYWORDS;
  13208. var KEYWORDS_BEFORE_EXPRESSION = "return new delete throw else case";
  13209. KEYWORDS = makePredicate(KEYWORDS);
  13210. RESERVED_WORDS = makePredicate(RESERVED_WORDS);
  13211. KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
  13212. KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
  13213. var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^"));
  13214. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  13215. var RE_OCT_NUMBER = /^0[0-7]+$/;
  13216. var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
  13217. var OPERATORS = makePredicate([ "in", "instanceof", "typeof", "new", "void", "delete", "++", "--", "+", "-", "!", "~", "&", "|", "^", "*", "/", "%", ">>", "<<", ">>>", "<", ">", "<=", ">=", "==", "===", "!=", "!==", "?", "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=", "&&", "||" ]);
  13218. 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"));
  13219. var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:"));
  13220. var PUNC_CHARS = makePredicate(characters("[]{}(),;:"));
  13221. var REGEXP_MODIFIERS = makePredicate(characters("gmsiy"));
  13222. var UNICODE = {
  13223. 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]"),
  13224. 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]"),
  13225. 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]"),
  13226. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
  13227. };
  13228. function is_letter(code) {
  13229. return code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 170 && UNICODE.letter.test(String.fromCharCode(code));
  13230. }
  13231. function is_digit(code) {
  13232. return code >= 48 && code <= 57;
  13233. }
  13234. function is_alphanumeric_char(code) {
  13235. return is_digit(code) || is_letter(code);
  13236. }
  13237. function is_unicode_combining_mark(ch) {
  13238. return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
  13239. }
  13240. function is_unicode_connector_punctuation(ch) {
  13241. return UNICODE.connector_punctuation.test(ch);
  13242. }
  13243. function is_identifier(name) {
  13244. return /^[a-z_$][a-z0-9_$]*$/i.test(name) && !RESERVED_WORDS(name);
  13245. }
  13246. function is_identifier_start(code) {
  13247. return code == 36 || code == 95 || is_letter(code);
  13248. }
  13249. function is_identifier_char(ch) {
  13250. var code = ch.charCodeAt(0);
  13251. return is_identifier_start(code) || is_digit(code) || code == 8204 || code == 8205 || is_unicode_combining_mark(ch) || is_unicode_connector_punctuation(ch);
  13252. }
  13253. function parse_js_number(num) {
  13254. if (RE_HEX_NUMBER.test(num)) {
  13255. return parseInt(num.substr(2), 16);
  13256. } else if (RE_OCT_NUMBER.test(num)) {
  13257. return parseInt(num.substr(1), 8);
  13258. } else if (RE_DEC_NUMBER.test(num)) {
  13259. return parseFloat(num);
  13260. }
  13261. }
  13262. function JS_Parse_Error(message, line, col, pos) {
  13263. this.message = message;
  13264. this.line = line;
  13265. this.col = col;
  13266. this.pos = pos;
  13267. this.stack = new Error().stack;
  13268. }
  13269. JS_Parse_Error.prototype.toString = function() {
  13270. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  13271. };
  13272. function js_error(message, filename, line, col, pos) {
  13273. AST_Node.warn("ERROR: {message} [{file}:{line},{col}]", {
  13274. message: message,
  13275. file: filename,
  13276. line: line,
  13277. col: col
  13278. });
  13279. throw new JS_Parse_Error(message, line, col, pos);
  13280. }
  13281. function is_token(token, type, val) {
  13282. return token.type == type && (val == null || token.value == val);
  13283. }
  13284. var EX_EOF = {};
  13285. function tokenizer($TEXT, filename) {
  13286. var S = {
  13287. text: $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/\uFEFF/g, ""),
  13288. filename: filename,
  13289. pos: 0,
  13290. tokpos: 0,
  13291. line: 1,
  13292. tokline: 0,
  13293. col: 0,
  13294. tokcol: 0,
  13295. newline_before: false,
  13296. regex_allowed: false,
  13297. comments_before: []
  13298. };
  13299. function peek() {
  13300. return S.text.charAt(S.pos);
  13301. }
  13302. function next(signal_eof, in_string) {
  13303. var ch = S.text.charAt(S.pos++);
  13304. if (signal_eof && !ch) throw EX_EOF;
  13305. if (ch == "\n") {
  13306. S.newline_before = S.newline_before || !in_string;
  13307. ++S.line;
  13308. S.col = 0;
  13309. } else {
  13310. ++S.col;
  13311. }
  13312. return ch;
  13313. }
  13314. function find(what, signal_eof) {
  13315. var pos = S.text.indexOf(what, S.pos);
  13316. if (signal_eof && pos == -1) throw EX_EOF;
  13317. return pos;
  13318. }
  13319. function start_token() {
  13320. S.tokline = S.line;
  13321. S.tokcol = S.col;
  13322. S.tokpos = S.pos;
  13323. }
  13324. function token(type, value, is_comment) {
  13325. S.regex_allowed = type == "operator" && !UNARY_POSTFIX[value] || type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value) || type == "punc" && PUNC_BEFORE_EXPRESSION(value);
  13326. var ret = {
  13327. type: type,
  13328. value: value,
  13329. line: S.tokline,
  13330. col: S.tokcol,
  13331. pos: S.tokpos,
  13332. endpos: S.pos,
  13333. nlb: S.newline_before,
  13334. file: filename
  13335. };
  13336. if (!is_comment) {
  13337. ret.comments_before = S.comments_before;
  13338. S.comments_before = [];
  13339. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  13340. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  13341. }
  13342. }
  13343. S.newline_before = false;
  13344. return new AST_Token(ret);
  13345. }
  13346. function skip_whitespace() {
  13347. while (WHITESPACE_CHARS(peek())) next();
  13348. }
  13349. function read_while(pred) {
  13350. var ret = "", ch, i = 0;
  13351. while ((ch = peek()) && pred(ch, i++)) ret += next();
  13352. return ret;
  13353. }
  13354. function parse_error(err) {
  13355. js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
  13356. }
  13357. function read_num(prefix) {
  13358. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  13359. var num = read_while(function(ch, i) {
  13360. var code = ch.charCodeAt(0);
  13361. switch (code) {
  13362. case 120:
  13363. case 88:
  13364. return has_x ? false : has_x = true;
  13365. case 101:
  13366. case 69:
  13367. return has_x ? true : has_e ? false : has_e = after_e = true;
  13368. case 45:
  13369. return after_e || i == 0 && !prefix;
  13370. case 43:
  13371. return after_e;
  13372. case after_e = false, 46:
  13373. return !has_dot && !has_x && !has_e ? has_dot = true : false;
  13374. }
  13375. return is_alphanumeric_char(code);
  13376. });
  13377. if (prefix) num = prefix + num;
  13378. var valid = parse_js_number(num);
  13379. if (!isNaN(valid)) {
  13380. return token("num", valid);
  13381. } else {
  13382. parse_error("Invalid syntax: " + num);
  13383. }
  13384. }
  13385. function read_escaped_char(in_string) {
  13386. var ch = next(true, in_string);
  13387. switch (ch.charCodeAt(0)) {
  13388. case 110:
  13389. return "\n";
  13390. case 114:
  13391. return "\r";
  13392. case 116:
  13393. return " ";
  13394. case 98:
  13395. return "\b";
  13396. case 118:
  13397. return " ";
  13398. case 102:
  13399. return "\f";
  13400. case 48:
  13401. return "\0";
  13402. case 120:
  13403. return String.fromCharCode(hex_bytes(2));
  13404. case 117:
  13405. return String.fromCharCode(hex_bytes(4));
  13406. case 10:
  13407. return "";
  13408. default:
  13409. return ch;
  13410. }
  13411. }
  13412. function hex_bytes(n) {
  13413. var num = 0;
  13414. for (;n > 0; --n) {
  13415. var digit = parseInt(next(true), 16);
  13416. if (isNaN(digit)) parse_error("Invalid hex-character pattern in string");
  13417. num = num << 4 | digit;
  13418. }
  13419. return num;
  13420. }
  13421. var read_string = with_eof_error("Unterminated string constant", function() {
  13422. var quote = next(), ret = "";
  13423. for (;;) {
  13424. var ch = next(true);
  13425. if (ch == "\\") {
  13426. var octal_len = 0, first = null;
  13427. ch = read_while(function(ch) {
  13428. if (ch >= "0" && ch <= "7") {
  13429. if (!first) {
  13430. first = ch;
  13431. return ++octal_len;
  13432. } else if (first <= "3" && octal_len <= 2) return ++octal_len; else if (first >= "4" && octal_len <= 1) return ++octal_len;
  13433. }
  13434. return false;
  13435. });
  13436. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8)); else ch = read_escaped_char(true);
  13437. } else if (ch == quote) break;
  13438. ret += ch;
  13439. }
  13440. return token("string", ret);
  13441. });
  13442. function read_line_comment() {
  13443. next();
  13444. var i = find("\n"), ret;
  13445. if (i == -1) {
  13446. ret = S.text.substr(S.pos);
  13447. S.pos = S.text.length;
  13448. } else {
  13449. ret = S.text.substring(S.pos, i);
  13450. S.pos = i;
  13451. }
  13452. return token("comment1", ret, true);
  13453. }
  13454. var read_multiline_comment = with_eof_error("Unterminated multiline comment", function() {
  13455. next();
  13456. var i = find("*/", true);
  13457. var text = S.text.substring(S.pos, i);
  13458. var a = text.split("\n"), n = a.length;
  13459. S.pos = i + 2;
  13460. S.line += n - 1;
  13461. if (n > 1) S.col = a[n - 1].length; else S.col += a[n - 1].length;
  13462. S.col += 2;
  13463. S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  13464. return token("comment2", text, true);
  13465. });
  13466. function read_name() {
  13467. var backslash = false, name = "", ch, escaped = false, hex;
  13468. while ((ch = peek()) != null) {
  13469. if (!backslash) {
  13470. if (ch == "\\") escaped = backslash = true, next(); else if (is_identifier_char(ch)) name += next(); else break;
  13471. } else {
  13472. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  13473. ch = read_escaped_char();
  13474. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  13475. name += ch;
  13476. backslash = false;
  13477. }
  13478. }
  13479. if (KEYWORDS(name) && escaped) {
  13480. hex = name.charCodeAt(0).toString(16).toUpperCase();
  13481. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  13482. }
  13483. return name;
  13484. }
  13485. var read_regexp = with_eof_error("Unterminated regular expression", function(regexp) {
  13486. var prev_backslash = false, ch, in_class = false;
  13487. while (ch = next(true)) if (prev_backslash) {
  13488. regexp += "\\" + ch;
  13489. prev_backslash = false;
  13490. } else if (ch == "[") {
  13491. in_class = true;
  13492. regexp += ch;
  13493. } else if (ch == "]" && in_class) {
  13494. in_class = false;
  13495. regexp += ch;
  13496. } else if (ch == "/" && !in_class) {
  13497. break;
  13498. } else if (ch == "\\") {
  13499. prev_backslash = true;
  13500. } else {
  13501. regexp += ch;
  13502. }
  13503. var mods = read_name();
  13504. return token("regexp", new RegExp(regexp, mods));
  13505. });
  13506. function read_operator(prefix) {
  13507. function grow(op) {
  13508. if (!peek()) return op;
  13509. var bigger = op + peek();
  13510. if (OPERATORS(bigger)) {
  13511. next();
  13512. return grow(bigger);
  13513. } else {
  13514. return op;
  13515. }
  13516. }
  13517. return token("operator", grow(prefix || next()));
  13518. }
  13519. function handle_slash() {
  13520. next();
  13521. var regex_allowed = S.regex_allowed;
  13522. switch (peek()) {
  13523. case "/":
  13524. S.comments_before.push(read_line_comment());
  13525. S.regex_allowed = regex_allowed;
  13526. return next_token();
  13527. case "*":
  13528. S.comments_before.push(read_multiline_comment());
  13529. S.regex_allowed = regex_allowed;
  13530. return next_token();
  13531. }
  13532. return S.regex_allowed ? read_regexp("") : read_operator("/");
  13533. }
  13534. function handle_dot() {
  13535. next();
  13536. return is_digit(peek().charCodeAt(0)) ? read_num(".") : token("punc", ".");
  13537. }
  13538. function read_word() {
  13539. var word = read_name();
  13540. return KEYWORDS_ATOM(word) ? token("atom", word) : !KEYWORDS(word) ? token("name", word) : OPERATORS(word) ? token("operator", word) : token("keyword", word);
  13541. }
  13542. function with_eof_error(eof_error, cont) {
  13543. return function(x) {
  13544. try {
  13545. return cont(x);
  13546. } catch (ex) {
  13547. if (ex === EX_EOF) parse_error(eof_error); else throw ex;
  13548. }
  13549. };
  13550. }
  13551. function next_token(force_regexp) {
  13552. if (force_regexp != null) return read_regexp(force_regexp);
  13553. skip_whitespace();
  13554. start_token();
  13555. var ch = peek();
  13556. if (!ch) return token("eof");
  13557. var code = ch.charCodeAt(0);
  13558. switch (code) {
  13559. case 34:
  13560. case 39:
  13561. return read_string();
  13562. case 46:
  13563. return handle_dot();
  13564. case 47:
  13565. return handle_slash();
  13566. }
  13567. if (is_digit(code)) return read_num();
  13568. if (PUNC_CHARS(ch)) return token("punc", next());
  13569. if (OPERATOR_CHARS(ch)) return read_operator();
  13570. if (code == 92 || is_identifier_start(code)) return read_word();
  13571. parse_error("Unexpected character '" + ch + "'");
  13572. }
  13573. next_token.context = function(nc) {
  13574. if (nc) S = nc;
  13575. return S;
  13576. };
  13577. return next_token;
  13578. }
  13579. var UNARY_PREFIX = makePredicate([ "typeof", "void", "delete", "--", "++", "!", "~", "-", "+" ]);
  13580. var UNARY_POSTFIX = makePredicate([ "--", "++" ]);
  13581. var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]);
  13582. var PRECEDENCE = function(a, ret) {
  13583. for (var i = 0, n = 1; i < a.length; ++i, ++n) {
  13584. var b = a[i];
  13585. for (var j = 0; j < b.length; ++j) {
  13586. ret[b[j]] = n;
  13587. }
  13588. }
  13589. return ret;
  13590. }([ [ "||" ], [ "&&" ], [ "|" ], [ "^" ], [ "&" ], [ "==", "===", "!=", "!==" ], [ "<", ">", "<=", ">=", "in", "instanceof" ], [ ">>", "<<", ">>>" ], [ "+", "-" ], [ "*", "/", "%" ] ], {});
  13591. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  13592. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  13593. function parse($TEXT, options) {
  13594. options = defaults(options, {
  13595. strict: false,
  13596. filename: null,
  13597. toplevel: null
  13598. });
  13599. var S = {
  13600. input: typeof $TEXT == "string" ? tokenizer($TEXT, options.filename) : $TEXT,
  13601. token: null,
  13602. prev: null,
  13603. peeked: null,
  13604. in_function: 0,
  13605. in_directives: true,
  13606. in_loop: 0,
  13607. labels: []
  13608. };
  13609. S.token = next();
  13610. function is(type, value) {
  13611. return is_token(S.token, type, value);
  13612. }
  13613. function peek() {
  13614. return S.peeked || (S.peeked = S.input());
  13615. }
  13616. function next() {
  13617. S.prev = S.token;
  13618. if (S.peeked) {
  13619. S.token = S.peeked;
  13620. S.peeked = null;
  13621. } else {
  13622. S.token = S.input();
  13623. }
  13624. S.in_directives = S.in_directives && (S.token.type == "string" || is("punc", ";"));
  13625. return S.token;
  13626. }
  13627. function prev() {
  13628. return S.prev;
  13629. }
  13630. function croak(msg, line, col, pos) {
  13631. var ctx = S.input.context();
  13632. js_error(msg, ctx.filename, line != null ? line : ctx.tokline, col != null ? col : ctx.tokcol, pos != null ? pos : ctx.tokpos);
  13633. }
  13634. function token_error(token, msg) {
  13635. croak(msg, token.line, token.col);
  13636. }
  13637. function unexpected(token) {
  13638. if (token == null) token = S.token;
  13639. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  13640. }
  13641. function expect_token(type, val) {
  13642. if (is(type, val)) {
  13643. return next();
  13644. }
  13645. token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");
  13646. }
  13647. function expect(punc) {
  13648. return expect_token("punc", punc);
  13649. }
  13650. function can_insert_semicolon() {
  13651. return !options.strict && (S.token.nlb || is("eof") || is("punc", "}"));
  13652. }
  13653. function semicolon() {
  13654. if (is("punc", ";")) next(); else if (!can_insert_semicolon()) unexpected();
  13655. }
  13656. function parenthesised() {
  13657. expect("(");
  13658. var exp = expression(true);
  13659. expect(")");
  13660. return exp;
  13661. }
  13662. function embed_tokens(parser) {
  13663. return function() {
  13664. var start = S.token;
  13665. var expr = parser();
  13666. var end = prev();
  13667. expr.start = start;
  13668. expr.end = end;
  13669. return expr;
  13670. };
  13671. }
  13672. var statement = embed_tokens(function() {
  13673. var tmp;
  13674. if (is("operator", "/") || is("operator", "/=")) {
  13675. S.peeked = null;
  13676. S.token = S.input(S.token.value.substr(1));
  13677. }
  13678. switch (S.token.type) {
  13679. case "string":
  13680. var dir = S.in_directives, stat = simple_statement();
  13681. if (dir && stat.body instanceof AST_String && !is("punc", ",")) return new AST_Directive({
  13682. value: stat.body.value
  13683. });
  13684. return stat;
  13685. case "num":
  13686. case "regexp":
  13687. case "operator":
  13688. case "atom":
  13689. return simple_statement();
  13690. case "name":
  13691. return is_token(peek(), "punc", ":") ? labeled_statement() : simple_statement();
  13692. case "punc":
  13693. switch (S.token.value) {
  13694. case "{":
  13695. return new AST_BlockStatement({
  13696. start: S.token,
  13697. body: block_(),
  13698. end: prev()
  13699. });
  13700. case "[":
  13701. case "(":
  13702. return simple_statement();
  13703. case ";":
  13704. next();
  13705. return new AST_EmptyStatement();
  13706. default:
  13707. unexpected();
  13708. }
  13709. case "keyword":
  13710. switch (tmp = S.token.value, next(), tmp) {
  13711. case "break":
  13712. return break_cont(AST_Break);
  13713. case "continue":
  13714. return break_cont(AST_Continue);
  13715. case "debugger":
  13716. semicolon();
  13717. return new AST_Debugger();
  13718. case "do":
  13719. return new AST_Do({
  13720. body: in_loop(statement),
  13721. condition: (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(),
  13722. tmp)
  13723. });
  13724. case "while":
  13725. return new AST_While({
  13726. condition: parenthesised(),
  13727. body: in_loop(statement)
  13728. });
  13729. case "for":
  13730. return for_();
  13731. case "function":
  13732. return function_(true);
  13733. case "if":
  13734. return if_();
  13735. case "return":
  13736. if (S.in_function == 0) croak("'return' outside of function");
  13737. return new AST_Return({
  13738. value: is("punc", ";") ? (next(), null) : can_insert_semicolon() ? null : (tmp = expression(true),
  13739. semicolon(), tmp)
  13740. });
  13741. case "switch":
  13742. return new AST_Switch({
  13743. expression: parenthesised(),
  13744. body: in_loop(switch_body_)
  13745. });
  13746. case "throw":
  13747. if (S.token.nlb) croak("Illegal newline after 'throw'");
  13748. return new AST_Throw({
  13749. value: (tmp = expression(true), semicolon(), tmp)
  13750. });
  13751. case "try":
  13752. return try_();
  13753. case "var":
  13754. return tmp = var_(), semicolon(), tmp;
  13755. case "const":
  13756. return tmp = const_(), semicolon(), tmp;
  13757. case "with":
  13758. return new AST_With({
  13759. expression: parenthesised(),
  13760. body: statement()
  13761. });
  13762. default:
  13763. unexpected();
  13764. }
  13765. }
  13766. });
  13767. function labeled_statement() {
  13768. var label = as_symbol(AST_Label);
  13769. if (find_if(function(l) {
  13770. return l.name == label.name;
  13771. }, S.labels)) {
  13772. croak("Label " + label.name + " defined twice");
  13773. }
  13774. expect(":");
  13775. S.labels.push(label);
  13776. var stat = statement();
  13777. S.labels.pop();
  13778. return new AST_LabeledStatement({
  13779. body: stat,
  13780. label: label
  13781. });
  13782. }
  13783. function simple_statement(tmp) {
  13784. return new AST_SimpleStatement({
  13785. body: (tmp = expression(true), semicolon(), tmp)
  13786. });
  13787. }
  13788. function break_cont(type) {
  13789. var label = null;
  13790. if (!can_insert_semicolon()) {
  13791. label = as_symbol(AST_LabelRef, true);
  13792. }
  13793. if (label != null) {
  13794. if (!find_if(function(l) {
  13795. return l.name == label.name;
  13796. }, S.labels)) croak("Undefined label " + label.name);
  13797. } else if (S.in_loop == 0) croak(type.TYPE + " not inside a loop or switch");
  13798. semicolon();
  13799. return new type({
  13800. label: label
  13801. });
  13802. }
  13803. function for_() {
  13804. expect("(");
  13805. var init = null;
  13806. if (!is("punc", ";")) {
  13807. init = is("keyword", "var") ? (next(), var_(true)) : expression(true, true);
  13808. if (is("operator", "in")) {
  13809. if (init instanceof AST_Var && init.definitions.length > 1) croak("Only one variable declaration allowed in for..in loop");
  13810. next();
  13811. return for_in(init);
  13812. }
  13813. }
  13814. return regular_for(init);
  13815. }
  13816. function regular_for(init) {
  13817. expect(";");
  13818. var test = is("punc", ";") ? null : expression(true);
  13819. expect(";");
  13820. var step = is("punc", ")") ? null : expression(true);
  13821. expect(")");
  13822. return new AST_For({
  13823. init: init,
  13824. condition: test,
  13825. step: step,
  13826. body: in_loop(statement)
  13827. });
  13828. }
  13829. function for_in(init) {
  13830. var lhs = init instanceof AST_Var ? init.definitions[0].name : null;
  13831. var obj = expression(true);
  13832. expect(")");
  13833. return new AST_ForIn({
  13834. init: init,
  13835. name: lhs,
  13836. object: obj,
  13837. body: in_loop(statement)
  13838. });
  13839. }
  13840. var function_ = function(in_statement, ctor) {
  13841. var is_accessor = ctor === AST_Accessor;
  13842. var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : is_accessor ? AST_SymbolAccessor : AST_SymbolLambda) : is_accessor && (is("string") || is("num")) ? as_atom_node() : null;
  13843. if (in_statement && !name) unexpected();
  13844. expect("(");
  13845. if (!ctor) ctor = in_statement ? AST_Defun : AST_Function;
  13846. return new ctor({
  13847. name: name,
  13848. argnames: function(first, a) {
  13849. while (!is("punc", ")")) {
  13850. if (first) first = false; else expect(",");
  13851. a.push(as_symbol(AST_SymbolFunarg));
  13852. }
  13853. next();
  13854. return a;
  13855. }(true, []),
  13856. body: function(loop, labels) {
  13857. ++S.in_function;
  13858. S.in_directives = true;
  13859. S.in_loop = 0;
  13860. S.labels = [];
  13861. var a = block_();
  13862. --S.in_function;
  13863. S.in_loop = loop;
  13864. S.labels = labels;
  13865. return a;
  13866. }(S.in_loop, S.labels)
  13867. });
  13868. };
  13869. function if_() {
  13870. var cond = parenthesised(), body = statement(), belse = null;
  13871. if (is("keyword", "else")) {
  13872. next();
  13873. belse = statement();
  13874. }
  13875. return new AST_If({
  13876. condition: cond,
  13877. body: body,
  13878. alternative: belse
  13879. });
  13880. }
  13881. function block_() {
  13882. expect("{");
  13883. var a = [];
  13884. while (!is("punc", "}")) {
  13885. if (is("eof")) unexpected();
  13886. a.push(statement());
  13887. }
  13888. next();
  13889. return a;
  13890. }
  13891. function switch_body_() {
  13892. expect("{");
  13893. var a = [], cur = null, branch = null, tmp;
  13894. while (!is("punc", "}")) {
  13895. if (is("eof")) unexpected();
  13896. if (is("keyword", "case")) {
  13897. if (branch) branch.end = prev();
  13898. cur = [];
  13899. branch = new AST_Case({
  13900. start: (tmp = S.token, next(), tmp),
  13901. expression: expression(true),
  13902. body: cur
  13903. });
  13904. a.push(branch);
  13905. expect(":");
  13906. } else if (is("keyword", "default")) {
  13907. if (branch) branch.end = prev();
  13908. cur = [];
  13909. branch = new AST_Default({
  13910. start: (tmp = S.token, next(), expect(":"), tmp),
  13911. body: cur
  13912. });
  13913. a.push(branch);
  13914. } else {
  13915. if (!cur) unexpected();
  13916. cur.push(statement());
  13917. }
  13918. }
  13919. if (branch) branch.end = prev();
  13920. next();
  13921. return a;
  13922. }
  13923. function try_() {
  13924. var body = block_(), bcatch = null, bfinally = null;
  13925. if (is("keyword", "catch")) {
  13926. var start = S.token;
  13927. next();
  13928. expect("(");
  13929. var name = as_symbol(AST_SymbolCatch);
  13930. expect(")");
  13931. bcatch = new AST_Catch({
  13932. start: start,
  13933. argname: name,
  13934. body: block_(),
  13935. end: prev()
  13936. });
  13937. }
  13938. if (is("keyword", "finally")) {
  13939. var start = S.token;
  13940. next();
  13941. bfinally = new AST_Finally({
  13942. start: start,
  13943. body: block_(),
  13944. end: prev()
  13945. });
  13946. }
  13947. if (!bcatch && !bfinally) croak("Missing catch/finally blocks");
  13948. return new AST_Try({
  13949. body: body,
  13950. bcatch: bcatch,
  13951. bfinally: bfinally
  13952. });
  13953. }
  13954. function vardefs(no_in, in_const) {
  13955. var a = [];
  13956. for (;;) {
  13957. a.push(new AST_VarDef({
  13958. start: S.token,
  13959. name: as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),
  13960. value: is("operator", "=") ? (next(), expression(false, no_in)) : null,
  13961. end: prev()
  13962. }));
  13963. if (!is("punc", ",")) break;
  13964. next();
  13965. }
  13966. return a;
  13967. }
  13968. var var_ = function(no_in) {
  13969. return new AST_Var({
  13970. start: prev(),
  13971. definitions: vardefs(no_in, false),
  13972. end: prev()
  13973. });
  13974. };
  13975. var const_ = function() {
  13976. return new AST_Const({
  13977. start: prev(),
  13978. definitions: vardefs(false, true),
  13979. end: prev()
  13980. });
  13981. };
  13982. var new_ = function() {
  13983. var start = S.token;
  13984. expect_token("operator", "new");
  13985. var newexp = expr_atom(false), args;
  13986. if (is("punc", "(")) {
  13987. next();
  13988. args = expr_list(")");
  13989. } else {
  13990. args = [];
  13991. }
  13992. return subscripts(new AST_New({
  13993. start: start,
  13994. expression: newexp,
  13995. args: args,
  13996. end: prev()
  13997. }), true);
  13998. };
  13999. function as_atom_node() {
  14000. var tok = S.token, ret;
  14001. switch (tok.type) {
  14002. case "name":
  14003. return as_symbol(AST_SymbolRef);
  14004. case "num":
  14005. ret = new AST_Number({
  14006. start: tok,
  14007. end: tok,
  14008. value: tok.value
  14009. });
  14010. break;
  14011. case "string":
  14012. ret = new AST_String({
  14013. start: tok,
  14014. end: tok,
  14015. value: tok.value
  14016. });
  14017. break;
  14018. case "regexp":
  14019. ret = new AST_RegExp({
  14020. start: tok,
  14021. end: tok,
  14022. value: tok.value
  14023. });
  14024. break;
  14025. case "atom":
  14026. switch (tok.value) {
  14027. case "false":
  14028. ret = new AST_False({
  14029. start: tok,
  14030. end: tok
  14031. });
  14032. break;
  14033. case "true":
  14034. ret = new AST_True({
  14035. start: tok,
  14036. end: tok
  14037. });
  14038. break;
  14039. case "null":
  14040. ret = new AST_Null({
  14041. start: tok,
  14042. end: tok
  14043. });
  14044. break;
  14045. }
  14046. break;
  14047. }
  14048. next();
  14049. return ret;
  14050. }
  14051. var expr_atom = function(allow_calls) {
  14052. if (is("operator", "new")) {
  14053. return new_();
  14054. }
  14055. var start = S.token;
  14056. if (is("punc")) {
  14057. switch (start.value) {
  14058. case "(":
  14059. next();
  14060. var ex = expression(true);
  14061. ex.start = start;
  14062. ex.end = S.token;
  14063. expect(")");
  14064. return subscripts(ex, allow_calls);
  14065. case "[":
  14066. return subscripts(array_(), allow_calls);
  14067. case "{":
  14068. return subscripts(object_(), allow_calls);
  14069. }
  14070. unexpected();
  14071. }
  14072. if (is("keyword", "function")) {
  14073. next();
  14074. var func = function_(false);
  14075. func.start = start;
  14076. func.end = prev();
  14077. return subscripts(func, allow_calls);
  14078. }
  14079. if (ATOMIC_START_TOKEN[S.token.type]) {
  14080. return subscripts(as_atom_node(), allow_calls);
  14081. }
  14082. unexpected();
  14083. };
  14084. function expr_list(closing, allow_trailing_comma, allow_empty) {
  14085. var first = true, a = [];
  14086. while (!is("punc", closing)) {
  14087. if (first) first = false; else expect(",");
  14088. if (allow_trailing_comma && is("punc", closing)) break;
  14089. if (is("punc", ",") && allow_empty) {
  14090. a.push(new AST_Undefined({
  14091. start: S.token,
  14092. end: S.token
  14093. }));
  14094. } else {
  14095. a.push(expression(false));
  14096. }
  14097. }
  14098. next();
  14099. return a;
  14100. }
  14101. var array_ = embed_tokens(function() {
  14102. expect("[");
  14103. return new AST_Array({
  14104. elements: expr_list("]", !options.strict, true)
  14105. });
  14106. });
  14107. var object_ = embed_tokens(function() {
  14108. expect("{");
  14109. var first = true, a = [];
  14110. while (!is("punc", "}")) {
  14111. if (first) first = false; else expect(",");
  14112. if (!options.strict && is("punc", "}")) break;
  14113. var start = S.token;
  14114. var type = start.type;
  14115. var name = as_property_name();
  14116. if (type == "name" && !is("punc", ":")) {
  14117. if (name == "get") {
  14118. a.push(new AST_ObjectGetter({
  14119. start: start,
  14120. key: name,
  14121. value: function_(false, AST_Accessor),
  14122. end: prev()
  14123. }));
  14124. continue;
  14125. }
  14126. if (name == "set") {
  14127. a.push(new AST_ObjectSetter({
  14128. start: start,
  14129. key: name,
  14130. value: function_(false, AST_Accessor),
  14131. end: prev()
  14132. }));
  14133. continue;
  14134. }
  14135. }
  14136. expect(":");
  14137. a.push(new AST_ObjectKeyVal({
  14138. start: start,
  14139. key: name,
  14140. value: expression(false),
  14141. end: prev()
  14142. }));
  14143. }
  14144. next();
  14145. return new AST_Object({
  14146. properties: a
  14147. });
  14148. });
  14149. function as_property_name() {
  14150. var tmp = S.token;
  14151. next();
  14152. switch (tmp.type) {
  14153. case "num":
  14154. case "string":
  14155. case "name":
  14156. case "operator":
  14157. case "keyword":
  14158. case "atom":
  14159. return tmp.value;
  14160. default:
  14161. unexpected();
  14162. }
  14163. }
  14164. function as_name() {
  14165. var tmp = S.token;
  14166. next();
  14167. switch (tmp.type) {
  14168. case "name":
  14169. case "operator":
  14170. case "keyword":
  14171. case "atom":
  14172. return tmp.value;
  14173. default:
  14174. unexpected();
  14175. }
  14176. }
  14177. function as_symbol(type, noerror) {
  14178. if (!is("name")) {
  14179. if (!noerror) croak("Name expected");
  14180. return null;
  14181. }
  14182. var name = S.token.value;
  14183. var sym = new (name == "this" ? AST_This : type)({
  14184. name: String(S.token.value),
  14185. start: S.token,
  14186. end: S.token
  14187. });
  14188. next();
  14189. return sym;
  14190. }
  14191. var subscripts = function(expr, allow_calls) {
  14192. var start = expr.start;
  14193. if (is("punc", ".")) {
  14194. next();
  14195. return subscripts(new AST_Dot({
  14196. start: start,
  14197. expression: expr,
  14198. property: as_name(),
  14199. end: prev()
  14200. }), allow_calls);
  14201. }
  14202. if (is("punc", "[")) {
  14203. next();
  14204. var prop = expression(true);
  14205. expect("]");
  14206. return subscripts(new AST_Sub({
  14207. start: start,
  14208. expression: expr,
  14209. property: prop,
  14210. end: prev()
  14211. }), allow_calls);
  14212. }
  14213. if (allow_calls && is("punc", "(")) {
  14214. next();
  14215. return subscripts(new AST_Call({
  14216. start: start,
  14217. expression: expr,
  14218. args: expr_list(")"),
  14219. end: prev()
  14220. }), true);
  14221. }
  14222. return expr;
  14223. };
  14224. var maybe_unary = function(allow_calls) {
  14225. var start = S.token;
  14226. if (is("operator") && UNARY_PREFIX(start.value)) {
  14227. next();
  14228. var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls));
  14229. ex.start = start;
  14230. ex.end = prev();
  14231. return ex;
  14232. }
  14233. var val = expr_atom(allow_calls);
  14234. while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {
  14235. val = make_unary(AST_UnaryPostfix, S.token.value, val);
  14236. val.start = start;
  14237. val.end = S.token;
  14238. next();
  14239. }
  14240. return val;
  14241. };
  14242. function make_unary(ctor, op, expr) {
  14243. if ((op == "++" || op == "--") && !is_assignable(expr)) croak("Invalid use of " + op + " operator");
  14244. return new ctor({
  14245. operator: op,
  14246. expression: expr
  14247. });
  14248. }
  14249. var expr_op = function(left, min_prec, no_in) {
  14250. var op = is("operator") ? S.token.value : null;
  14251. if (op == "in" && no_in) op = null;
  14252. var prec = op != null ? PRECEDENCE[op] : null;
  14253. if (prec != null && prec > min_prec) {
  14254. next();
  14255. var right = expr_op(maybe_unary(true), prec, no_in);
  14256. return expr_op(new AST_Binary({
  14257. start: left.start,
  14258. left: left,
  14259. operator: op,
  14260. right: right,
  14261. end: right.end
  14262. }), min_prec, no_in);
  14263. }
  14264. return left;
  14265. };
  14266. function expr_ops(no_in) {
  14267. return expr_op(maybe_unary(true), 0, no_in);
  14268. }
  14269. var maybe_conditional = function(no_in) {
  14270. var start = S.token;
  14271. var expr = expr_ops(no_in);
  14272. if (is("operator", "?")) {
  14273. next();
  14274. var yes = expression(false);
  14275. expect(":");
  14276. return new AST_Conditional({
  14277. start: start,
  14278. condition: expr,
  14279. consequent: yes,
  14280. alternative: expression(false, no_in),
  14281. end: peek()
  14282. });
  14283. }
  14284. return expr;
  14285. };
  14286. function is_assignable(expr) {
  14287. if (!options.strict) return true;
  14288. switch (expr[0] + "") {
  14289. case "dot":
  14290. case "sub":
  14291. case "new":
  14292. case "call":
  14293. return true;
  14294. case "name":
  14295. return expr[1] != "this";
  14296. }
  14297. }
  14298. var maybe_assign = function(no_in) {
  14299. var start = S.token;
  14300. var left = maybe_conditional(no_in), val = S.token.value;
  14301. if (is("operator") && ASSIGNMENT(val)) {
  14302. if (is_assignable(left)) {
  14303. next();
  14304. return new AST_Assign({
  14305. start: start,
  14306. left: left,
  14307. operator: val,
  14308. right: maybe_assign(no_in),
  14309. end: peek()
  14310. });
  14311. }
  14312. croak("Invalid assignment");
  14313. }
  14314. return left;
  14315. };
  14316. var expression = function(commas, no_in) {
  14317. var start = S.token;
  14318. var expr = maybe_assign(no_in);
  14319. if (commas && is("punc", ",")) {
  14320. next();
  14321. return new AST_Seq({
  14322. start: start,
  14323. car: expr,
  14324. cdr: expression(true, no_in),
  14325. end: peek()
  14326. });
  14327. }
  14328. return expr;
  14329. };
  14330. function in_loop(cont) {
  14331. ++S.in_loop;
  14332. var ret = cont();
  14333. --S.in_loop;
  14334. return ret;
  14335. }
  14336. return function() {
  14337. var start = S.token;
  14338. var body = [];
  14339. while (!is("eof")) body.push(statement());
  14340. var end = prev();
  14341. var toplevel = options.toplevel;
  14342. if (toplevel) {
  14343. toplevel.body = toplevel.body.concat(body);
  14344. toplevel.end = end;
  14345. } else {
  14346. toplevel = new AST_Toplevel({
  14347. start: start,
  14348. body: body,
  14349. end: end
  14350. });
  14351. }
  14352. return toplevel;
  14353. }();
  14354. }
  14355. "use strict";
  14356. function TreeTransformer(before, after) {
  14357. TreeWalker.call(this);
  14358. this.before = before;
  14359. this.after = after;
  14360. }
  14361. TreeTransformer.prototype = new TreeWalker();
  14362. (function(undefined) {
  14363. function _(node, descend) {
  14364. node.DEFMETHOD("transform", function(tw, in_list) {
  14365. var x, y;
  14366. tw.push(this);
  14367. if (tw.before) x = tw.before(this, descend, in_list);
  14368. if (x === undefined) {
  14369. if (!tw.after) {
  14370. x = this;
  14371. descend(x, tw);
  14372. } else {
  14373. tw.stack[tw.stack.length - 1] = x = this.clone();
  14374. descend(x, tw);
  14375. y = tw.after(x, in_list);
  14376. if (y !== undefined) x = y;
  14377. }
  14378. }
  14379. tw.pop();
  14380. return x;
  14381. });
  14382. }
  14383. function do_list(list, tw) {
  14384. return MAP(list, function(node) {
  14385. return node.transform(tw, true);
  14386. });
  14387. }
  14388. _(AST_Node, noop);
  14389. _(AST_LabeledStatement, function(self, tw) {
  14390. self.label = self.label.transform(tw);
  14391. self.body = self.body.transform(tw);
  14392. });
  14393. _(AST_SimpleStatement, function(self, tw) {
  14394. self.body = self.body.transform(tw);
  14395. });
  14396. _(AST_Block, function(self, tw) {
  14397. self.body = do_list(self.body, tw);
  14398. });
  14399. _(AST_DWLoop, function(self, tw) {
  14400. self.condition = self.condition.transform(tw);
  14401. self.body = self.body.transform(tw);
  14402. });
  14403. _(AST_For, function(self, tw) {
  14404. if (self.init) self.init = self.init.transform(tw);
  14405. if (self.condition) self.condition = self.condition.transform(tw);
  14406. if (self.step) self.step = self.step.transform(tw);
  14407. self.body = self.body.transform(tw);
  14408. });
  14409. _(AST_ForIn, function(self, tw) {
  14410. self.init = self.init.transform(tw);
  14411. self.object = self.object.transform(tw);
  14412. self.body = self.body.transform(tw);
  14413. });
  14414. _(AST_With, function(self, tw) {
  14415. self.expression = self.expression.transform(tw);
  14416. self.body = self.body.transform(tw);
  14417. });
  14418. _(AST_Exit, function(self, tw) {
  14419. if (self.value) self.value = self.value.transform(tw);
  14420. });
  14421. _(AST_LoopControl, function(self, tw) {
  14422. if (self.label) self.label = self.label.transform(tw);
  14423. });
  14424. _(AST_If, function(self, tw) {
  14425. self.condition = self.condition.transform(tw);
  14426. self.body = self.body.transform(tw);
  14427. if (self.alternative) self.alternative = self.alternative.transform(tw);
  14428. });
  14429. _(AST_Switch, function(self, tw) {
  14430. self.expression = self.expression.transform(tw);
  14431. self.body = do_list(self.body, tw);
  14432. });
  14433. _(AST_Case, function(self, tw) {
  14434. self.expression = self.expression.transform(tw);
  14435. self.body = do_list(self.body, tw);
  14436. });
  14437. _(AST_Try, function(self, tw) {
  14438. self.body = do_list(self.body, tw);
  14439. if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
  14440. if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
  14441. });
  14442. _(AST_Catch, function(self, tw) {
  14443. self.argname = self.argname.transform(tw);
  14444. self.body = do_list(self.body, tw);
  14445. });
  14446. _(AST_Definitions, function(self, tw) {
  14447. self.definitions = do_list(self.definitions, tw);
  14448. });
  14449. _(AST_VarDef, function(self, tw) {
  14450. if (self.value) self.value = self.value.transform(tw);
  14451. });
  14452. _(AST_Lambda, function(self, tw) {
  14453. if (self.name) self.name = self.name.transform(tw);
  14454. self.argnames = do_list(self.argnames, tw);
  14455. self.body = do_list(self.body, tw);
  14456. });
  14457. _(AST_Call, function(self, tw) {
  14458. self.expression = self.expression.transform(tw);
  14459. self.args = do_list(self.args, tw);
  14460. });
  14461. _(AST_Seq, function(self, tw) {
  14462. self.car = self.car.transform(tw);
  14463. self.cdr = self.cdr.transform(tw);
  14464. });
  14465. _(AST_Dot, function(self, tw) {
  14466. self.expression = self.expression.transform(tw);
  14467. });
  14468. _(AST_Sub, function(self, tw) {
  14469. self.expression = self.expression.transform(tw);
  14470. self.property = self.property.transform(tw);
  14471. });
  14472. _(AST_Unary, function(self, tw) {
  14473. self.expression = self.expression.transform(tw);
  14474. });
  14475. _(AST_Binary, function(self, tw) {
  14476. self.left = self.left.transform(tw);
  14477. self.right = self.right.transform(tw);
  14478. });
  14479. _(AST_Conditional, function(self, tw) {
  14480. self.condition = self.condition.transform(tw);
  14481. self.consequent = self.consequent.transform(tw);
  14482. self.alternative = self.alternative.transform(tw);
  14483. });
  14484. _(AST_Array, function(self, tw) {
  14485. self.elements = do_list(self.elements, tw);
  14486. });
  14487. _(AST_Object, function(self, tw) {
  14488. self.properties = do_list(self.properties, tw);
  14489. });
  14490. _(AST_ObjectProperty, function(self, tw) {
  14491. self.value = self.value.transform(tw);
  14492. });
  14493. })();
  14494. "use strict";
  14495. function SymbolDef(scope, index, orig) {
  14496. this.name = orig.name;
  14497. this.orig = [ orig ];
  14498. this.scope = scope;
  14499. this.references = [];
  14500. this.global = false;
  14501. this.mangled_name = null;
  14502. this.undeclared = false;
  14503. this.constant = false;
  14504. this.index = index;
  14505. }
  14506. SymbolDef.prototype = {
  14507. unmangleable: function(options) {
  14508. return this.global || this.undeclared || !(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with);
  14509. },
  14510. mangle: function(options) {
  14511. if (!this.mangled_name && !this.unmangleable(options)) this.mangled_name = this.scope.next_mangled(options);
  14512. }
  14513. };
  14514. AST_Toplevel.DEFMETHOD("figure_out_scope", function() {
  14515. var self = this;
  14516. var scope = self.parent_scope = null;
  14517. var labels = new Dictionary();
  14518. var nesting = 0;
  14519. var tw = new TreeWalker(function(node, descend) {
  14520. if (node instanceof AST_Scope) {
  14521. node.init_scope_vars(nesting);
  14522. var save_scope = node.parent_scope = scope;
  14523. var save_labels = labels;
  14524. ++nesting;
  14525. scope = node;
  14526. labels = new Dictionary();
  14527. descend();
  14528. labels = save_labels;
  14529. scope = save_scope;
  14530. --nesting;
  14531. return true;
  14532. }
  14533. if (node instanceof AST_Directive) {
  14534. node.scope = scope;
  14535. push_uniq(scope.directives, node.value);
  14536. return true;
  14537. }
  14538. if (node instanceof AST_With) {
  14539. for (var s = scope; s; s = s.parent_scope) s.uses_with = true;
  14540. return;
  14541. }
  14542. if (node instanceof AST_LabeledStatement) {
  14543. var l = node.label;
  14544. if (labels.has(l.name)) throw new Error(string_template("Label {name} defined twice", l));
  14545. labels.set(l.name, l);
  14546. descend();
  14547. labels.del(l.name);
  14548. return true;
  14549. }
  14550. if (node instanceof AST_Symbol) {
  14551. node.scope = scope;
  14552. }
  14553. if (node instanceof AST_Label) {
  14554. node.thedef = node;
  14555. node.init_scope_vars();
  14556. }
  14557. if (node instanceof AST_SymbolLambda) {
  14558. (node.scope = scope.parent_scope).def_function(node);
  14559. } else if (node instanceof AST_SymbolDefun) {
  14560. (node.scope = scope.parent_scope).def_function(node);
  14561. } else if (node instanceof AST_SymbolVar || node instanceof AST_SymbolConst) {
  14562. var def = scope.def_variable(node);
  14563. def.constant = node instanceof AST_SymbolConst;
  14564. def = tw.parent();
  14565. } else if (node instanceof AST_SymbolCatch) {
  14566. scope.def_variable(node);
  14567. }
  14568. if (node instanceof AST_LabelRef) {
  14569. var sym = labels.get(node.name);
  14570. if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
  14571. name: node.name,
  14572. line: node.start.line,
  14573. col: node.start.col
  14574. }));
  14575. node.thedef = sym;
  14576. }
  14577. });
  14578. self.walk(tw);
  14579. var func = null;
  14580. var globals = self.globals = new Dictionary();
  14581. var tw = new TreeWalker(function(node, descend) {
  14582. if (node instanceof AST_Lambda) {
  14583. var prev_func = func;
  14584. func = node;
  14585. descend();
  14586. func = prev_func;
  14587. return true;
  14588. }
  14589. if (node instanceof AST_LabelRef) {
  14590. node.reference();
  14591. return true;
  14592. }
  14593. if (node instanceof AST_SymbolRef) {
  14594. var name = node.name;
  14595. var sym = node.scope.find_variable(name);
  14596. if (!sym) {
  14597. var g;
  14598. if (globals.has(name)) {
  14599. g = globals.get(name);
  14600. } else {
  14601. g = new SymbolDef(self, globals.size(), node);
  14602. g.undeclared = true;
  14603. globals.set(name, g);
  14604. }
  14605. node.thedef = g;
  14606. if (name == "eval" && tw.parent() instanceof AST_Call) {
  14607. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) s.uses_eval = true;
  14608. }
  14609. if (name == "arguments") {
  14610. func.uses_arguments = true;
  14611. }
  14612. } else {
  14613. node.thedef = sym;
  14614. }
  14615. node.reference();
  14616. return true;
  14617. }
  14618. });
  14619. self.walk(tw);
  14620. });
  14621. AST_Scope.DEFMETHOD("init_scope_vars", function(nesting) {
  14622. this.directives = [];
  14623. this.variables = new Dictionary();
  14624. this.functions = new Dictionary();
  14625. this.uses_with = false;
  14626. this.uses_eval = false;
  14627. this.parent_scope = null;
  14628. this.enclosed = [];
  14629. this.cname = -1;
  14630. this.nesting = nesting;
  14631. });
  14632. AST_Scope.DEFMETHOD("strict", function() {
  14633. return this.has_directive("use strict");
  14634. });
  14635. AST_Lambda.DEFMETHOD("init_scope_vars", function() {
  14636. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  14637. this.uses_arguments = false;
  14638. });
  14639. AST_SymbolRef.DEFMETHOD("reference", function() {
  14640. var def = this.definition();
  14641. def.references.push(this);
  14642. var s = this.scope;
  14643. while (s) {
  14644. push_uniq(s.enclosed, def);
  14645. if (s === def.scope) break;
  14646. s = s.parent_scope;
  14647. }
  14648. this.frame = this.scope.nesting - def.scope.nesting;
  14649. });
  14650. AST_Label.DEFMETHOD("init_scope_vars", function() {
  14651. this.references = [];
  14652. });
  14653. AST_LabelRef.DEFMETHOD("reference", function() {
  14654. this.thedef.references.push(this);
  14655. });
  14656. AST_Scope.DEFMETHOD("find_variable", function(name) {
  14657. if (name instanceof AST_Symbol) name = name.name;
  14658. return this.variables.get(name) || this.parent_scope && this.parent_scope.find_variable(name);
  14659. });
  14660. AST_Scope.DEFMETHOD("has_directive", function(value) {
  14661. return this.parent_scope && this.parent_scope.has_directive(value) || (this.directives.indexOf(value) >= 0 ? this : null);
  14662. });
  14663. AST_Scope.DEFMETHOD("def_function", function(symbol) {
  14664. this.functions.set(symbol.name, this.def_variable(symbol));
  14665. });
  14666. AST_Scope.DEFMETHOD("def_variable", function(symbol) {
  14667. var def;
  14668. if (!this.variables.has(symbol.name)) {
  14669. def = new SymbolDef(this, this.variables.size(), symbol);
  14670. this.variables.set(symbol.name, def);
  14671. def.global = !this.parent_scope;
  14672. } else {
  14673. def = this.variables.get(symbol.name);
  14674. def.orig.push(symbol);
  14675. }
  14676. return symbol.thedef = def;
  14677. });
  14678. AST_Scope.DEFMETHOD("next_mangled", function(options) {
  14679. var ext = this.enclosed, n = ext.length;
  14680. out: while (true) {
  14681. var m = base54(++this.cname);
  14682. if (!is_identifier(m)) continue;
  14683. for (var i = n; --i >= 0; ) {
  14684. var sym = ext[i];
  14685. var name = sym.mangled_name || sym.unmangleable(options) && sym.name;
  14686. if (m == name) continue out;
  14687. }
  14688. return m;
  14689. }
  14690. });
  14691. AST_Scope.DEFMETHOD("references", function(sym) {
  14692. if (sym instanceof AST_Symbol) sym = sym.definition();
  14693. return this.enclosed.indexOf(sym) < 0 ? null : sym;
  14694. });
  14695. AST_Symbol.DEFMETHOD("unmangleable", function(options) {
  14696. return this.definition().unmangleable(options);
  14697. });
  14698. AST_SymbolAccessor.DEFMETHOD("unmangleable", function() {
  14699. return true;
  14700. });
  14701. AST_Label.DEFMETHOD("unmangleable", function() {
  14702. return false;
  14703. });
  14704. AST_Symbol.DEFMETHOD("unreferenced", function() {
  14705. return this.definition().references.length == 0 && !(this.scope.uses_eval || this.scope.uses_with);
  14706. });
  14707. AST_Symbol.DEFMETHOD("undeclared", function() {
  14708. return this.definition().undeclared;
  14709. });
  14710. AST_LabelRef.DEFMETHOD("undeclared", function() {
  14711. return false;
  14712. });
  14713. AST_Label.DEFMETHOD("undeclared", function() {
  14714. return false;
  14715. });
  14716. AST_Symbol.DEFMETHOD("definition", function() {
  14717. return this.thedef;
  14718. });
  14719. AST_Symbol.DEFMETHOD("global", function() {
  14720. return this.definition().global;
  14721. });
  14722. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) {
  14723. return defaults(options, {
  14724. except: [],
  14725. eval: false,
  14726. sort: false
  14727. });
  14728. });
  14729. AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
  14730. options = this._default_mangler_options(options);
  14731. var lname = -1;
  14732. var to_mangle = [];
  14733. var tw = new TreeWalker(function(node, descend) {
  14734. if (node instanceof AST_LabeledStatement) {
  14735. var save_nesting = lname;
  14736. descend();
  14737. lname = save_nesting;
  14738. return true;
  14739. }
  14740. if (node instanceof AST_Scope) {
  14741. var p = tw.parent(), a = [];
  14742. node.variables.each(function(symbol) {
  14743. if (options.except.indexOf(symbol.name) < 0) {
  14744. a.push(symbol);
  14745. }
  14746. });
  14747. if (options.sort) a.sort(function(a, b) {
  14748. return b.references.length - a.references.length;
  14749. });
  14750. to_mangle.push.apply(to_mangle, a);
  14751. return;
  14752. }
  14753. if (node instanceof AST_Label) {
  14754. var name;
  14755. do name = base54(++lname); while (!is_identifier(name));
  14756. node.mangled_name = name;
  14757. return true;
  14758. }
  14759. });
  14760. this.walk(tw);
  14761. to_mangle.forEach(function(def) {
  14762. def.mangle(options);
  14763. });
  14764. });
  14765. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) {
  14766. options = this._default_mangler_options(options);
  14767. var tw = new TreeWalker(function(node) {
  14768. if (node instanceof AST_Constant) base54.consider(node.print_to_string()); else if (node instanceof AST_Return) base54.consider("return"); else if (node instanceof AST_Throw) base54.consider("throw"); else if (node instanceof AST_Continue) base54.consider("continue"); else if (node instanceof AST_Break) base54.consider("break"); else if (node instanceof AST_Debugger) base54.consider("debugger"); else if (node instanceof AST_Directive) base54.consider(node.value); else if (node instanceof AST_While) base54.consider("while"); else if (node instanceof AST_Do) base54.consider("do while"); else if (node instanceof AST_If) {
  14769. base54.consider("if");
  14770. if (node.alternative) base54.consider("else");
  14771. } else if (node instanceof AST_Var) base54.consider("var"); else if (node instanceof AST_Const) base54.consider("const"); else if (node instanceof AST_Lambda) base54.consider("function"); else if (node instanceof AST_For) base54.consider("for"); else if (node instanceof AST_ForIn) base54.consider("for in"); else if (node instanceof AST_Switch) base54.consider("switch"); else if (node instanceof AST_Case) base54.consider("case"); else if (node instanceof AST_Default) base54.consider("default"); else if (node instanceof AST_With) base54.consider("with"); else if (node instanceof AST_ObjectSetter) base54.consider("set" + node.key); else if (node instanceof AST_ObjectGetter) base54.consider("get" + node.key); else if (node instanceof AST_ObjectKeyVal) base54.consider(node.key); else if (node instanceof AST_New) base54.consider("new"); else if (node instanceof AST_This) base54.consider("this"); else if (node instanceof AST_Try) base54.consider("try"); else if (node instanceof AST_Catch) base54.consider("catch"); else if (node instanceof AST_Finally) base54.consider("finally"); else if (node instanceof AST_Symbol && node.unmangleable(options)) base54.consider(node.name); else if (node instanceof AST_Unary || node instanceof AST_Binary) base54.consider(node.operator); else if (node instanceof AST_Dot) base54.consider(node.property);
  14772. });
  14773. this.walk(tw);
  14774. base54.sort();
  14775. });
  14776. var base54 = function() {
  14777. var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
  14778. var chars, frequency;
  14779. function reset() {
  14780. frequency = Object.create(null);
  14781. chars = string.split("").map(function(ch) {
  14782. return ch.charCodeAt(0);
  14783. });
  14784. chars.forEach(function(ch) {
  14785. frequency[ch] = 0;
  14786. });
  14787. }
  14788. base54.consider = function(str) {
  14789. for (var i = str.length; --i >= 0; ) {
  14790. var code = str.charCodeAt(i);
  14791. if (code in frequency) ++frequency[code];
  14792. }
  14793. };
  14794. base54.sort = function() {
  14795. chars = mergeSort(chars, function(a, b) {
  14796. if (is_digit(a) && !is_digit(b)) return 1;
  14797. if (is_digit(b) && !is_digit(a)) return -1;
  14798. return frequency[b] - frequency[a];
  14799. });
  14800. };
  14801. base54.reset = reset;
  14802. reset();
  14803. base54.get = function() {
  14804. return chars;
  14805. };
  14806. base54.freq = function() {
  14807. return frequency;
  14808. };
  14809. function base54(num) {
  14810. var ret = "", base = 54;
  14811. do {
  14812. ret += String.fromCharCode(chars[num % base]);
  14813. num = Math.floor(num / base);
  14814. base = 64;
  14815. } while (num > 0);
  14816. return ret;
  14817. }
  14818. return base54;
  14819. }();
  14820. AST_Toplevel.DEFMETHOD("scope_warnings", function(options) {
  14821. options = defaults(options, {
  14822. undeclared: false,
  14823. unreferenced: true,
  14824. assign_to_global: true,
  14825. func_arguments: true,
  14826. nested_defuns: true,
  14827. eval: true
  14828. });
  14829. var tw = new TreeWalker(function(node) {
  14830. if (options.undeclared && node instanceof AST_SymbolRef && node.undeclared()) {
  14831. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
  14832. name: node.name,
  14833. file: node.start.file,
  14834. line: node.start.line,
  14835. col: node.start.col
  14836. });
  14837. }
  14838. if (options.assign_to_global) {
  14839. var sym = null;
  14840. if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) sym = node.left; else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef) sym = node.init;
  14841. if (sym && (sym.undeclared() || sym.global() && sym.scope !== sym.definition().scope)) {
  14842. AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
  14843. msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
  14844. name: sym.name,
  14845. file: sym.start.file,
  14846. line: sym.start.line,
  14847. col: sym.start.col
  14848. });
  14849. }
  14850. }
  14851. if (options.eval && node instanceof AST_SymbolRef && node.undeclared() && node.name == "eval") {
  14852. AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
  14853. }
  14854. if (options.unreferenced && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label) && node.unreferenced()) {
  14855. AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
  14856. type: node instanceof AST_Label ? "Label" : "Symbol",
  14857. name: node.name,
  14858. file: node.start.file,
  14859. line: node.start.line,
  14860. col: node.start.col
  14861. });
  14862. }
  14863. if (options.func_arguments && node instanceof AST_Lambda && node.uses_arguments) {
  14864. AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
  14865. name: node.name ? node.name.name : "anonymous",
  14866. file: node.start.file,
  14867. line: node.start.line,
  14868. col: node.start.col
  14869. });
  14870. }
  14871. if (options.nested_defuns && node instanceof AST_Defun && !(tw.parent() instanceof AST_Scope)) {
  14872. AST_Node.warn('Function {name} declared in nested statement "{type}" [{file}:{line},{col}]', {
  14873. name: node.name.name,
  14874. type: tw.parent().TYPE,
  14875. file: node.start.file,
  14876. line: node.start.line,
  14877. col: node.start.col
  14878. });
  14879. }
  14880. });
  14881. this.walk(tw);
  14882. });
  14883. "use strict";
  14884. function OutputStream(options) {
  14885. options = defaults(options, {
  14886. indent_start: 0,
  14887. indent_level: 4,
  14888. quote_keys: false,
  14889. space_colon: true,
  14890. ascii_only: false,
  14891. inline_script: false,
  14892. width: 80,
  14893. max_line_len: 32e3,
  14894. ie_proof: true,
  14895. beautify: false,
  14896. source_map: null,
  14897. bracketize: false,
  14898. semicolons: true,
  14899. comments: false,
  14900. preserve_line: false
  14901. }, true);
  14902. var indentation = 0;
  14903. var current_col = 0;
  14904. var current_line = 1;
  14905. var current_pos = 0;
  14906. var OUTPUT = "";
  14907. function to_ascii(str) {
  14908. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  14909. var code = ch.charCodeAt(0).toString(16);
  14910. while (code.length < 4) code = "0" + code;
  14911. return "\\u" + code;
  14912. });
  14913. }
  14914. function make_string(str) {
  14915. var dq = 0, sq = 0;
  14916. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s) {
  14917. switch (s) {
  14918. case "\\":
  14919. return "\\\\";
  14920. case "\b":
  14921. return "\\b";
  14922. case "\f":
  14923. return "\\f";
  14924. case "\n":
  14925. return "\\n";
  14926. case "\r":
  14927. return "\\r";
  14928. case "\u2028":
  14929. return "\\u2028";
  14930. case "\u2029":
  14931. return "\\u2029";
  14932. case '"':
  14933. ++dq;
  14934. return '"';
  14935. case "'":
  14936. ++sq;
  14937. return "'";
  14938. case "\0":
  14939. return "\\0";
  14940. }
  14941. return s;
  14942. });
  14943. if (options.ascii_only) str = to_ascii(str);
  14944. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'"; else return '"' + str.replace(/\x22/g, '\\"') + '"';
  14945. }
  14946. function encode_string(str) {
  14947. var ret = make_string(str);
  14948. if (options.inline_script) ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  14949. return ret;
  14950. }
  14951. function make_name(name) {
  14952. name = name.toString();
  14953. if (options.ascii_only) name = to_ascii(name);
  14954. return name;
  14955. }
  14956. function make_indent(back) {
  14957. return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
  14958. }
  14959. var might_need_space = false;
  14960. var might_need_semicolon = false;
  14961. var last = null;
  14962. function last_char() {
  14963. return last.charAt(last.length - 1);
  14964. }
  14965. function maybe_newline() {
  14966. if (options.max_line_len && current_col > options.max_line_len) print("\n");
  14967. }
  14968. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  14969. function print(str) {
  14970. str = String(str);
  14971. var ch = str.charAt(0);
  14972. if (might_need_semicolon) {
  14973. if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) {
  14974. if (options.semicolons || requireSemicolonChars(ch)) {
  14975. OUTPUT += ";";
  14976. current_col++;
  14977. current_pos++;
  14978. } else {
  14979. OUTPUT += "\n";
  14980. current_pos++;
  14981. current_line++;
  14982. current_col = 0;
  14983. }
  14984. if (!options.beautify) might_need_space = false;
  14985. }
  14986. might_need_semicolon = false;
  14987. maybe_newline();
  14988. }
  14989. if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
  14990. var target_line = stack[stack.length - 1].start.line;
  14991. while (current_line < target_line) {
  14992. OUTPUT += "\n";
  14993. current_pos++;
  14994. current_line++;
  14995. current_col = 0;
  14996. might_need_space = false;
  14997. }
  14998. }
  14999. if (might_need_space) {
  15000. var prev = last_char();
  15001. if (is_identifier_char(prev) && (is_identifier_char(ch) || ch == "\\") || /^[\+\-\/]$/.test(ch) && ch == prev) {
  15002. OUTPUT += " ";
  15003. current_col++;
  15004. current_pos++;
  15005. }
  15006. might_need_space = false;
  15007. }
  15008. var a = str.split(/\r?\n/), n = a.length - 1;
  15009. current_line += n;
  15010. if (n == 0) {
  15011. current_col += a[n].length;
  15012. } else {
  15013. current_col = a[n].length;
  15014. }
  15015. current_pos += str.length;
  15016. last = str;
  15017. OUTPUT += str;
  15018. }
  15019. var space = options.beautify ? function() {
  15020. print(" ");
  15021. } : function() {
  15022. might_need_space = true;
  15023. };
  15024. var indent = options.beautify ? function(half) {
  15025. if (options.beautify) {
  15026. print(make_indent(half ? .5 : 0));
  15027. }
  15028. } : noop;
  15029. var with_indent = options.beautify ? function(col, cont) {
  15030. if (col === true) col = next_indent();
  15031. var save_indentation = indentation;
  15032. indentation = col;
  15033. var ret = cont();
  15034. indentation = save_indentation;
  15035. return ret;
  15036. } : function(col, cont) {
  15037. return cont();
  15038. };
  15039. var newline = options.beautify ? function() {
  15040. print("\n");
  15041. } : noop;
  15042. var semicolon = options.beautify ? function() {
  15043. print(";");
  15044. } : function() {
  15045. might_need_semicolon = true;
  15046. };
  15047. function force_semicolon() {
  15048. might_need_semicolon = false;
  15049. print(";");
  15050. }
  15051. function next_indent() {
  15052. return indentation + options.indent_level;
  15053. }
  15054. function with_block(cont) {
  15055. var ret;
  15056. print("{");
  15057. newline();
  15058. with_indent(next_indent(), function() {
  15059. ret = cont();
  15060. });
  15061. indent();
  15062. print("}");
  15063. return ret;
  15064. }
  15065. function with_parens(cont) {
  15066. print("(");
  15067. var ret = cont();
  15068. print(")");
  15069. return ret;
  15070. }
  15071. function with_square(cont) {
  15072. print("[");
  15073. var ret = cont();
  15074. print("]");
  15075. return ret;
  15076. }
  15077. function comma() {
  15078. print(",");
  15079. space();
  15080. }
  15081. function colon() {
  15082. print(":");
  15083. if (options.space_colon) space();
  15084. }
  15085. var add_mapping = options.source_map ? function(token, name) {
  15086. try {
  15087. if (token) options.source_map.add(token.file || "?", current_line, current_col, token.line, token.col, !name && token.type == "name" ? token.value : name);
  15088. } catch (ex) {
  15089. AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
  15090. file: token.file,
  15091. line: token.line,
  15092. col: token.col,
  15093. cline: current_line,
  15094. ccol: current_col,
  15095. name: name || ""
  15096. });
  15097. }
  15098. } : noop;
  15099. function get() {
  15100. return OUTPUT;
  15101. }
  15102. var stack = [];
  15103. return {
  15104. get: get,
  15105. toString: get,
  15106. indent: indent,
  15107. indentation: function() {
  15108. return indentation;
  15109. },
  15110. current_width: function() {
  15111. return current_col - indentation;
  15112. },
  15113. should_break: function() {
  15114. return options.width && this.current_width() >= options.width;
  15115. },
  15116. newline: newline,
  15117. print: print,
  15118. space: space,
  15119. comma: comma,
  15120. colon: colon,
  15121. last: function() {
  15122. return last;
  15123. },
  15124. semicolon: semicolon,
  15125. force_semicolon: force_semicolon,
  15126. to_ascii: to_ascii,
  15127. print_name: function(name) {
  15128. print(make_name(name));
  15129. },
  15130. print_string: function(str) {
  15131. print(encode_string(str));
  15132. },
  15133. next_indent: next_indent,
  15134. with_indent: with_indent,
  15135. with_block: with_block,
  15136. with_parens: with_parens,
  15137. with_square: with_square,
  15138. add_mapping: add_mapping,
  15139. option: function(opt) {
  15140. return options[opt];
  15141. },
  15142. line: function() {
  15143. return current_line;
  15144. },
  15145. col: function() {
  15146. return current_col;
  15147. },
  15148. pos: function() {
  15149. return current_pos;
  15150. },
  15151. push_node: function(node) {
  15152. stack.push(node);
  15153. },
  15154. pop_node: function() {
  15155. return stack.pop();
  15156. },
  15157. stack: function() {
  15158. return stack;
  15159. },
  15160. parent: function(n) {
  15161. return stack[stack.length - 2 - (n || 0)];
  15162. }
  15163. };
  15164. }
  15165. (function() {
  15166. function DEFPRINT(nodetype, generator) {
  15167. nodetype.DEFMETHOD("_codegen", generator);
  15168. }
  15169. AST_Node.DEFMETHOD("print", function(stream, force_parens) {
  15170. var self = this, generator = self._codegen;
  15171. stream.push_node(self);
  15172. if (force_parens || self.needs_parens(stream)) {
  15173. stream.with_parens(function() {
  15174. self.add_comments(stream);
  15175. self.add_source_map(stream);
  15176. generator(self, stream);
  15177. });
  15178. } else {
  15179. self.add_comments(stream);
  15180. self.add_source_map(stream);
  15181. generator(self, stream);
  15182. }
  15183. stream.pop_node();
  15184. });
  15185. AST_Node.DEFMETHOD("print_to_string", function(options) {
  15186. var s = OutputStream(options);
  15187. this.print(s);
  15188. return s.get();
  15189. });
  15190. AST_Node.DEFMETHOD("add_comments", function(output) {
  15191. var c = output.option("comments"), self = this;
  15192. if (c) {
  15193. var start = self.start;
  15194. if (start && !start._comments_dumped) {
  15195. start._comments_dumped = true;
  15196. var comments = start.comments_before;
  15197. if (c.test) {
  15198. comments = comments.filter(function(comment) {
  15199. return c.test(comment.value);
  15200. });
  15201. } else if (typeof c == "function") {
  15202. comments = comments.filter(function(comment) {
  15203. return c(self, comment);
  15204. });
  15205. }
  15206. comments.forEach(function(c) {
  15207. if (c.type == "comment1") {
  15208. output.print("//" + c.value + "\n");
  15209. output.indent();
  15210. } else if (c.type == "comment2") {
  15211. output.print("/*" + c.value + "*/");
  15212. if (start.nlb) {
  15213. output.print("\n");
  15214. output.indent();
  15215. } else {
  15216. output.space();
  15217. }
  15218. }
  15219. });
  15220. }
  15221. }
  15222. });
  15223. function PARENS(nodetype, func) {
  15224. nodetype.DEFMETHOD("needs_parens", func);
  15225. }
  15226. PARENS(AST_Node, function() {
  15227. return false;
  15228. });
  15229. PARENS(AST_Function, function(output) {
  15230. return first_in_statement(output);
  15231. });
  15232. PARENS(AST_Object, function(output) {
  15233. return first_in_statement(output);
  15234. });
  15235. PARENS(AST_Unary, function(output) {
  15236. var p = output.parent();
  15237. return p instanceof AST_PropAccess && p.expression === this;
  15238. });
  15239. PARENS(AST_Seq, function(output) {
  15240. var p = output.parent();
  15241. return p instanceof AST_Call || p instanceof AST_Unary || p instanceof AST_Binary || p instanceof AST_VarDef || p instanceof AST_Dot || p instanceof AST_Array || p instanceof AST_ObjectProperty || p instanceof AST_Conditional;
  15242. });
  15243. PARENS(AST_Binary, function(output) {
  15244. var p = output.parent();
  15245. if (p instanceof AST_Call && p.expression === this) return true;
  15246. if (p instanceof AST_Unary) return true;
  15247. if (p instanceof AST_PropAccess && p.expression === this) return true;
  15248. if (p instanceof AST_Binary) {
  15249. var po = p.operator, pp = PRECEDENCE[po];
  15250. var so = this.operator, sp = PRECEDENCE[so];
  15251. if (pp > sp || pp == sp && this === p.right && !(so == po && (so == "*" || so == "&&" || so == "||"))) {
  15252. return true;
  15253. }
  15254. }
  15255. });
  15256. PARENS(AST_PropAccess, function(output) {
  15257. var p = output.parent();
  15258. if (p instanceof AST_New && p.expression === this) {
  15259. try {
  15260. this.walk(new TreeWalker(function(node) {
  15261. if (node instanceof AST_Call) throw p;
  15262. }));
  15263. } catch (ex) {
  15264. if (ex !== p) throw ex;
  15265. return true;
  15266. }
  15267. }
  15268. });
  15269. PARENS(AST_Call, function(output) {
  15270. var p = output.parent();
  15271. return p instanceof AST_New && p.expression === this;
  15272. });
  15273. PARENS(AST_New, function(output) {
  15274. var p = output.parent();
  15275. if (no_constructor_parens(this, output) && (p instanceof AST_Dot || p instanceof AST_Call && p.expression === this)) return true;
  15276. });
  15277. function assign_and_conditional_paren_rules(output) {
  15278. var p = output.parent();
  15279. if (p instanceof AST_Unary) return true;
  15280. if (p instanceof AST_Binary && !(p instanceof AST_Assign)) return true;
  15281. if (p instanceof AST_Call && p.expression === this) return true;
  15282. if (p instanceof AST_Conditional && p.condition === this) return true;
  15283. if (p instanceof AST_PropAccess && p.expression === this) return true;
  15284. }
  15285. PARENS(AST_Assign, assign_and_conditional_paren_rules);
  15286. PARENS(AST_Conditional, assign_and_conditional_paren_rules);
  15287. DEFPRINT(AST_Directive, function(self, output) {
  15288. output.print_string(self.value);
  15289. output.semicolon();
  15290. });
  15291. DEFPRINT(AST_Debugger, function(self, output) {
  15292. output.print("debugger");
  15293. output.semicolon();
  15294. });
  15295. function display_body(body, is_toplevel, output) {
  15296. var last = body.length - 1;
  15297. body.forEach(function(stmt, i) {
  15298. if (!(stmt instanceof AST_EmptyStatement)) {
  15299. output.indent();
  15300. stmt.print(output);
  15301. if (!(i == last && is_toplevel)) {
  15302. output.newline();
  15303. if (is_toplevel) output.newline();
  15304. }
  15305. }
  15306. });
  15307. }
  15308. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) {
  15309. force_statement(this.body, output);
  15310. });
  15311. DEFPRINT(AST_Statement, function(self, output) {
  15312. self.body.print(output);
  15313. output.semicolon();
  15314. });
  15315. DEFPRINT(AST_Toplevel, function(self, output) {
  15316. display_body(self.body, true, output);
  15317. output.print("");
  15318. });
  15319. DEFPRINT(AST_LabeledStatement, function(self, output) {
  15320. self.label.print(output);
  15321. output.colon();
  15322. self.body.print(output);
  15323. });
  15324. DEFPRINT(AST_SimpleStatement, function(self, output) {
  15325. self.body.print(output);
  15326. output.semicolon();
  15327. });
  15328. function print_bracketed(body, output) {
  15329. if (body.length > 0) output.with_block(function() {
  15330. display_body(body, false, output);
  15331. }); else output.print("{}");
  15332. }
  15333. DEFPRINT(AST_BlockStatement, function(self, output) {
  15334. print_bracketed(self.body, output);
  15335. });
  15336. DEFPRINT(AST_EmptyStatement, function(self, output) {
  15337. output.semicolon();
  15338. });
  15339. DEFPRINT(AST_Do, function(self, output) {
  15340. output.print("do");
  15341. output.space();
  15342. self._do_print_body(output);
  15343. output.space();
  15344. output.print("while");
  15345. output.space();
  15346. output.with_parens(function() {
  15347. self.condition.print(output);
  15348. });
  15349. output.semicolon();
  15350. });
  15351. DEFPRINT(AST_While, function(self, output) {
  15352. output.print("while");
  15353. output.space();
  15354. output.with_parens(function() {
  15355. self.condition.print(output);
  15356. });
  15357. output.space();
  15358. self._do_print_body(output);
  15359. });
  15360. DEFPRINT(AST_For, function(self, output) {
  15361. output.print("for");
  15362. output.space();
  15363. output.with_parens(function() {
  15364. if (self.init) {
  15365. if (self.init instanceof AST_Definitions) {
  15366. self.init.print(output);
  15367. } else {
  15368. parenthesize_for_noin(self.init, output, true);
  15369. }
  15370. output.print(";");
  15371. output.space();
  15372. } else {
  15373. output.print(";");
  15374. }
  15375. if (self.condition) {
  15376. self.condition.print(output);
  15377. output.print(";");
  15378. output.space();
  15379. } else {
  15380. output.print(";");
  15381. }
  15382. if (self.step) {
  15383. self.step.print(output);
  15384. }
  15385. });
  15386. output.space();
  15387. self._do_print_body(output);
  15388. });
  15389. DEFPRINT(AST_ForIn, function(self, output) {
  15390. output.print("for");
  15391. output.space();
  15392. output.with_parens(function() {
  15393. self.init.print(output);
  15394. output.space();
  15395. output.print("in");
  15396. output.space();
  15397. self.object.print(output);
  15398. });
  15399. output.space();
  15400. self._do_print_body(output);
  15401. });
  15402. DEFPRINT(AST_With, function(self, output) {
  15403. output.print("with");
  15404. output.space();
  15405. output.with_parens(function() {
  15406. self.expression.print(output);
  15407. });
  15408. output.space();
  15409. self._do_print_body(output);
  15410. });
  15411. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) {
  15412. var self = this;
  15413. if (!nokeyword) {
  15414. output.print("function");
  15415. }
  15416. if (self.name) {
  15417. output.space();
  15418. self.name.print(output);
  15419. }
  15420. output.with_parens(function() {
  15421. self.argnames.forEach(function(arg, i) {
  15422. if (i) output.comma();
  15423. arg.print(output);
  15424. });
  15425. });
  15426. output.space();
  15427. print_bracketed(self.body, output);
  15428. });
  15429. DEFPRINT(AST_Lambda, function(self, output) {
  15430. self._do_print(output);
  15431. });
  15432. AST_Exit.DEFMETHOD("_do_print", function(output, kind) {
  15433. output.print(kind);
  15434. if (this.value) {
  15435. output.space();
  15436. this.value.print(output);
  15437. }
  15438. output.semicolon();
  15439. });
  15440. DEFPRINT(AST_Return, function(self, output) {
  15441. self._do_print(output, "return");
  15442. });
  15443. DEFPRINT(AST_Throw, function(self, output) {
  15444. self._do_print(output, "throw");
  15445. });
  15446. AST_LoopControl.DEFMETHOD("_do_print", function(output, kind) {
  15447. output.print(kind);
  15448. if (this.label) {
  15449. output.space();
  15450. this.label.print(output);
  15451. }
  15452. output.semicolon();
  15453. });
  15454. DEFPRINT(AST_Break, function(self, output) {
  15455. self._do_print(output, "break");
  15456. });
  15457. DEFPRINT(AST_Continue, function(self, output) {
  15458. self._do_print(output, "continue");
  15459. });
  15460. function make_then(self, output) {
  15461. if (output.option("bracketize")) {
  15462. make_block(self.body, output);
  15463. return;
  15464. }
  15465. if (!self.body) return output.force_semicolon();
  15466. if (self.body instanceof AST_Do && output.option("ie_proof")) {
  15467. make_block(self.body, output);
  15468. return;
  15469. }
  15470. var b = self.body;
  15471. while (true) {
  15472. if (b instanceof AST_If) {
  15473. if (!b.alternative) {
  15474. make_block(self.body, output);
  15475. return;
  15476. }
  15477. b = b.alternative;
  15478. } else if (b instanceof AST_StatementWithBody) {
  15479. b = b.body;
  15480. } else break;
  15481. }
  15482. force_statement(self.body, output);
  15483. }
  15484. DEFPRINT(AST_If, function(self, output) {
  15485. output.print("if");
  15486. output.space();
  15487. output.with_parens(function() {
  15488. self.condition.print(output);
  15489. });
  15490. output.space();
  15491. if (self.alternative) {
  15492. make_then(self, output);
  15493. output.space();
  15494. output.print("else");
  15495. output.space();
  15496. force_statement(self.alternative, output);
  15497. } else {
  15498. self._do_print_body(output);
  15499. }
  15500. });
  15501. DEFPRINT(AST_Switch, function(self, output) {
  15502. output.print("switch");
  15503. output.space();
  15504. output.with_parens(function() {
  15505. self.expression.print(output);
  15506. });
  15507. output.space();
  15508. if (self.body.length > 0) output.with_block(function() {
  15509. self.body.forEach(function(stmt, i) {
  15510. if (i) output.newline();
  15511. output.indent(true);
  15512. stmt.print(output);
  15513. });
  15514. }); else output.print("{}");
  15515. });
  15516. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) {
  15517. if (this.body.length > 0) {
  15518. output.newline();
  15519. this.body.forEach(function(stmt) {
  15520. output.indent();
  15521. stmt.print(output);
  15522. output.newline();
  15523. });
  15524. }
  15525. });
  15526. DEFPRINT(AST_Default, function(self, output) {
  15527. output.print("default:");
  15528. self._do_print_body(output);
  15529. });
  15530. DEFPRINT(AST_Case, function(self, output) {
  15531. output.print("case");
  15532. output.space();
  15533. self.expression.print(output);
  15534. output.print(":");
  15535. self._do_print_body(output);
  15536. });
  15537. DEFPRINT(AST_Try, function(self, output) {
  15538. output.print("try");
  15539. output.space();
  15540. print_bracketed(self.body, output);
  15541. if (self.bcatch) {
  15542. output.space();
  15543. self.bcatch.print(output);
  15544. }
  15545. if (self.bfinally) {
  15546. output.space();
  15547. self.bfinally.print(output);
  15548. }
  15549. });
  15550. DEFPRINT(AST_Catch, function(self, output) {
  15551. output.print("catch");
  15552. output.space();
  15553. output.with_parens(function() {
  15554. self.argname.print(output);
  15555. });
  15556. output.space();
  15557. print_bracketed(self.body, output);
  15558. });
  15559. DEFPRINT(AST_Finally, function(self, output) {
  15560. output.print("finally");
  15561. output.space();
  15562. print_bracketed(self.body, output);
  15563. });
  15564. AST_Definitions.DEFMETHOD("_do_print", function(output, kind) {
  15565. output.print(kind);
  15566. output.space();
  15567. this.definitions.forEach(function(def, i) {
  15568. if (i) output.comma();
  15569. def.print(output);
  15570. });
  15571. var p = output.parent();
  15572. var in_for = p instanceof AST_For || p instanceof AST_ForIn;
  15573. var avoid_semicolon = in_for && p.init === this;
  15574. if (!avoid_semicolon) output.semicolon();
  15575. });
  15576. DEFPRINT(AST_Var, function(self, output) {
  15577. self._do_print(output, "var");
  15578. });
  15579. DEFPRINT(AST_Const, function(self, output) {
  15580. self._do_print(output, "const");
  15581. });
  15582. function parenthesize_for_noin(node, output, noin) {
  15583. if (!noin) node.print(output); else try {
  15584. node.walk(new TreeWalker(function(node) {
  15585. if (node instanceof AST_Binary && node.operator == "in") throw output;
  15586. }));
  15587. node.print(output);
  15588. } catch (ex) {
  15589. if (ex !== output) throw ex;
  15590. node.print(output, true);
  15591. }
  15592. }
  15593. DEFPRINT(AST_VarDef, function(self, output) {
  15594. self.name.print(output);
  15595. if (self.value) {
  15596. output.space();
  15597. output.print("=");
  15598. output.space();
  15599. var p = output.parent(1);
  15600. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  15601. parenthesize_for_noin(self.value, output, noin);
  15602. }
  15603. });
  15604. DEFPRINT(AST_Call, function(self, output) {
  15605. self.expression.print(output);
  15606. if (self instanceof AST_New && no_constructor_parens(self, output)) return;
  15607. output.with_parens(function() {
  15608. self.args.forEach(function(expr, i) {
  15609. if (i) output.comma();
  15610. expr.print(output);
  15611. });
  15612. });
  15613. });
  15614. DEFPRINT(AST_New, function(self, output) {
  15615. output.print("new");
  15616. output.space();
  15617. AST_Call.prototype._codegen(self, output);
  15618. });
  15619. AST_Seq.DEFMETHOD("_do_print", function(output) {
  15620. this.car.print(output);
  15621. if (this.cdr) {
  15622. output.comma();
  15623. if (output.should_break()) {
  15624. output.newline();
  15625. output.indent();
  15626. }
  15627. this.cdr.print(output);
  15628. }
  15629. });
  15630. DEFPRINT(AST_Seq, function(self, output) {
  15631. self._do_print(output);
  15632. });
  15633. DEFPRINT(AST_Dot, function(self, output) {
  15634. var expr = self.expression;
  15635. expr.print(output);
  15636. if (expr instanceof AST_Number) {
  15637. if (!/[xa-f.]/i.test(output.last())) {
  15638. output.print(".");
  15639. }
  15640. }
  15641. output.print(".");
  15642. output.add_mapping(self.end);
  15643. output.print_name(self.property);
  15644. });
  15645. DEFPRINT(AST_Sub, function(self, output) {
  15646. self.expression.print(output);
  15647. output.print("[");
  15648. self.property.print(output);
  15649. output.print("]");
  15650. });
  15651. DEFPRINT(AST_UnaryPrefix, function(self, output) {
  15652. var op = self.operator;
  15653. output.print(op);
  15654. if (/^[a-z]/i.test(op)) output.space();
  15655. self.expression.print(output);
  15656. });
  15657. DEFPRINT(AST_UnaryPostfix, function(self, output) {
  15658. self.expression.print(output);
  15659. output.print(self.operator);
  15660. });
  15661. DEFPRINT(AST_Binary, function(self, output) {
  15662. self.left.print(output);
  15663. output.space();
  15664. output.print(self.operator);
  15665. output.space();
  15666. self.right.print(output);
  15667. });
  15668. DEFPRINT(AST_Conditional, function(self, output) {
  15669. self.condition.print(output);
  15670. output.space();
  15671. output.print("?");
  15672. output.space();
  15673. self.consequent.print(output);
  15674. output.space();
  15675. output.colon();
  15676. self.alternative.print(output);
  15677. });
  15678. DEFPRINT(AST_Array, function(self, output) {
  15679. output.with_square(function() {
  15680. var a = self.elements, len = a.length;
  15681. if (len > 0) output.space();
  15682. a.forEach(function(exp, i) {
  15683. if (i) output.comma();
  15684. if (!(exp instanceof AST_Undefined)) exp.print(output);
  15685. });
  15686. if (len > 0) output.space();
  15687. });
  15688. });
  15689. DEFPRINT(AST_Object, function(self, output) {
  15690. if (self.properties.length > 0) output.with_block(function() {
  15691. self.properties.forEach(function(prop, i) {
  15692. if (i) {
  15693. output.print(",");
  15694. output.newline();
  15695. }
  15696. output.indent();
  15697. prop.print(output);
  15698. });
  15699. output.newline();
  15700. }); else output.print("{}");
  15701. });
  15702. DEFPRINT(AST_ObjectKeyVal, function(self, output) {
  15703. var key = self.key;
  15704. if (output.option("quote_keys")) {
  15705. output.print_string(key);
  15706. } else if ((typeof key == "number" || !output.option("beautify") && +key + "" == key) && parseFloat(key) >= 0) {
  15707. output.print(make_num(key));
  15708. } else if (!is_identifier(key)) {
  15709. output.print_string(key);
  15710. } else {
  15711. output.print_name(key);
  15712. }
  15713. output.colon();
  15714. self.value.print(output);
  15715. });
  15716. DEFPRINT(AST_ObjectSetter, function(self, output) {
  15717. output.print("set");
  15718. self.value._do_print(output, true);
  15719. });
  15720. DEFPRINT(AST_ObjectGetter, function(self, output) {
  15721. output.print("get");
  15722. self.value._do_print(output, true);
  15723. });
  15724. DEFPRINT(AST_Symbol, function(self, output) {
  15725. var def = self.definition();
  15726. output.print_name(def ? def.mangled_name || def.name : self.name);
  15727. });
  15728. DEFPRINT(AST_Undefined, function(self, output) {
  15729. output.print("void 0");
  15730. });
  15731. DEFPRINT(AST_Infinity, function(self, output) {
  15732. output.print("1/0");
  15733. });
  15734. DEFPRINT(AST_NaN, function(self, output) {
  15735. output.print("0/0");
  15736. });
  15737. DEFPRINT(AST_This, function(self, output) {
  15738. output.print("this");
  15739. });
  15740. DEFPRINT(AST_Constant, function(self, output) {
  15741. output.print(self.getValue());
  15742. });
  15743. DEFPRINT(AST_String, function(self, output) {
  15744. output.print_string(self.getValue());
  15745. });
  15746. DEFPRINT(AST_Number, function(self, output) {
  15747. output.print(make_num(self.getValue()));
  15748. });
  15749. DEFPRINT(AST_RegExp, function(self, output) {
  15750. var str = self.getValue().toString();
  15751. if (output.option("ascii_only")) str = output.to_ascii(str);
  15752. output.print(str);
  15753. });
  15754. function force_statement(stat, output) {
  15755. if (output.option("bracketize")) {
  15756. if (!stat || stat instanceof AST_EmptyStatement) output.print("{}"); else if (stat instanceof AST_BlockStatement) stat.print(output); else output.with_block(function() {
  15757. output.indent();
  15758. stat.print(output);
  15759. output.newline();
  15760. });
  15761. } else {
  15762. if (!stat || stat instanceof AST_EmptyStatement) output.force_semicolon(); else stat.print(output);
  15763. }
  15764. }
  15765. function first_in_statement(output) {
  15766. var a = output.stack(), i = a.length, node = a[--i], p = a[--i];
  15767. while (i > 0) {
  15768. if (p instanceof AST_Statement && p.body === node) return true;
  15769. if (p instanceof AST_Seq && p.car === node || p instanceof AST_Call && p.expression === node || p instanceof AST_Dot && p.expression === node || p instanceof AST_Sub && p.expression === node || p instanceof AST_Conditional && p.condition === node || p instanceof AST_Binary && p.left === node || p instanceof AST_UnaryPostfix && p.expression === node) {
  15770. node = p;
  15771. p = a[--i];
  15772. } else {
  15773. return false;
  15774. }
  15775. }
  15776. }
  15777. function no_constructor_parens(self, output) {
  15778. return self.args.length == 0 && !output.option("beautify");
  15779. }
  15780. function best_of(a) {
  15781. var best = a[0], len = best.length;
  15782. for (var i = 1; i < a.length; ++i) {
  15783. if (a[i].length < len) {
  15784. best = a[i];
  15785. len = best.length;
  15786. }
  15787. }
  15788. return best;
  15789. }
  15790. function make_num(num) {
  15791. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace("e+", "e") ], m;
  15792. if (Math.floor(num) === num) {
  15793. if (num >= 0) {
  15794. a.push("0x" + num.toString(16).toLowerCase(), "0" + num.toString(8));
  15795. } else {
  15796. a.push("-0x" + (-num).toString(16).toLowerCase(), "-0" + (-num).toString(8));
  15797. }
  15798. if (m = /^(.*?)(0+)$/.exec(num)) {
  15799. a.push(m[1] + "e" + m[2].length);
  15800. }
  15801. } else if (m = /^0?\.(0+)(.*)$/.exec(num)) {
  15802. a.push(m[2] + "e-" + (m[1].length + m[2].length), str.substr(str.indexOf(".")));
  15803. }
  15804. return best_of(a);
  15805. }
  15806. function make_block(stmt, output) {
  15807. if (stmt instanceof AST_BlockStatement) {
  15808. stmt.print(output);
  15809. return;
  15810. }
  15811. output.with_block(function() {
  15812. output.indent();
  15813. stmt.print(output);
  15814. output.newline();
  15815. });
  15816. }
  15817. function DEFMAP(nodetype, generator) {
  15818. nodetype.DEFMETHOD("add_source_map", function(stream) {
  15819. generator(this, stream);
  15820. });
  15821. }
  15822. DEFMAP(AST_Node, noop);
  15823. function basic_sourcemap_gen(self, output) {
  15824. output.add_mapping(self.start);
  15825. }
  15826. DEFMAP(AST_Directive, basic_sourcemap_gen);
  15827. DEFMAP(AST_Debugger, basic_sourcemap_gen);
  15828. DEFMAP(AST_Symbol, basic_sourcemap_gen);
  15829. DEFMAP(AST_Jump, basic_sourcemap_gen);
  15830. DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);
  15831. DEFMAP(AST_LabeledStatement, noop);
  15832. DEFMAP(AST_Lambda, basic_sourcemap_gen);
  15833. DEFMAP(AST_Switch, basic_sourcemap_gen);
  15834. DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);
  15835. DEFMAP(AST_BlockStatement, basic_sourcemap_gen);
  15836. DEFMAP(AST_Toplevel, noop);
  15837. DEFMAP(AST_New, basic_sourcemap_gen);
  15838. DEFMAP(AST_Try, basic_sourcemap_gen);
  15839. DEFMAP(AST_Catch, basic_sourcemap_gen);
  15840. DEFMAP(AST_Finally, basic_sourcemap_gen);
  15841. DEFMAP(AST_Definitions, basic_sourcemap_gen);
  15842. DEFMAP(AST_Constant, basic_sourcemap_gen);
  15843. DEFMAP(AST_ObjectProperty, function(self, output) {
  15844. output.add_mapping(self.start, self.key);
  15845. });
  15846. })();
  15847. "use strict";
  15848. function Compressor(options, false_by_default) {
  15849. if (!(this instanceof Compressor)) return new Compressor(options, false_by_default);
  15850. TreeTransformer.call(this, this.before, this.after);
  15851. this.options = defaults(options, {
  15852. sequences: !false_by_default,
  15853. properties: !false_by_default,
  15854. dead_code: !false_by_default,
  15855. drop_debugger: !false_by_default,
  15856. unsafe: !false_by_default,
  15857. unsafe_comps: false,
  15858. conditionals: !false_by_default,
  15859. comparisons: !false_by_default,
  15860. evaluate: !false_by_default,
  15861. booleans: !false_by_default,
  15862. loops: !false_by_default,
  15863. unused: !false_by_default,
  15864. hoist_funs: !false_by_default,
  15865. hoist_vars: false,
  15866. if_return: !false_by_default,
  15867. join_vars: !false_by_default,
  15868. cascade: !false_by_default,
  15869. side_effects: !false_by_default,
  15870. warnings: true,
  15871. global_defs: {}
  15872. }, true);
  15873. }
  15874. Compressor.prototype = new TreeTransformer();
  15875. merge(Compressor.prototype, {
  15876. option: function(key) {
  15877. return this.options[key];
  15878. },
  15879. warn: function() {
  15880. if (this.options.warnings) AST_Node.warn.apply(AST_Node, arguments);
  15881. },
  15882. before: function(node, descend, in_list) {
  15883. if (node._squeezed) return node;
  15884. if (node instanceof AST_Scope) {
  15885. node.drop_unused(this);
  15886. node = node.hoist_declarations(this);
  15887. }
  15888. descend(node, this);
  15889. node = node.optimize(this);
  15890. if (node instanceof AST_Scope) {
  15891. var save_warnings = this.options.warnings;
  15892. this.options.warnings = false;
  15893. node.drop_unused(this);
  15894. this.options.warnings = save_warnings;
  15895. }
  15896. node._squeezed = true;
  15897. return node;
  15898. }
  15899. });
  15900. (function() {
  15901. function OPT(node, optimizer) {
  15902. node.DEFMETHOD("optimize", function(compressor) {
  15903. var self = this;
  15904. if (self._optimized) return self;
  15905. var opt = optimizer(self, compressor);
  15906. opt._optimized = true;
  15907. if (opt === self) return opt;
  15908. return opt.transform(compressor);
  15909. });
  15910. }
  15911. OPT(AST_Node, function(self, compressor) {
  15912. return self;
  15913. });
  15914. AST_Node.DEFMETHOD("equivalent_to", function(node) {
  15915. return this.print_to_string() == node.print_to_string();
  15916. });
  15917. function make_node(ctor, orig, props) {
  15918. if (!props) props = {};
  15919. if (orig) {
  15920. if (!props.start) props.start = orig.start;
  15921. if (!props.end) props.end = orig.end;
  15922. }
  15923. return new ctor(props);
  15924. }
  15925. function make_node_from_constant(compressor, val, orig) {
  15926. if (val instanceof AST_Node) return val.transform(compressor);
  15927. switch (typeof val) {
  15928. case "string":
  15929. return make_node(AST_String, orig, {
  15930. value: val
  15931. }).optimize(compressor);
  15932. case "number":
  15933. return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, {
  15934. value: val
  15935. }).optimize(compressor);
  15936. case "boolean":
  15937. return make_node(val ? AST_True : AST_False, orig);
  15938. case "undefined":
  15939. return make_node(AST_Undefined, orig).optimize(compressor);
  15940. default:
  15941. if (val === null) {
  15942. return make_node(AST_Null, orig).optimize(compressor);
  15943. }
  15944. if (val instanceof RegExp) {
  15945. return make_node(AST_RegExp, orig).optimize(compressor);
  15946. }
  15947. throw new Error(string_template("Can't handle constant of type: {type}", {
  15948. type: typeof val
  15949. }));
  15950. }
  15951. }
  15952. function as_statement_array(thing) {
  15953. if (thing === null) return [];
  15954. if (thing instanceof AST_BlockStatement) return thing.body;
  15955. if (thing instanceof AST_EmptyStatement) return [];
  15956. if (thing instanceof AST_Statement) return [ thing ];
  15957. throw new Error("Can't convert thing to statement array");
  15958. }
  15959. function is_empty(thing) {
  15960. if (thing === null) return true;
  15961. if (thing instanceof AST_EmptyStatement) return true;
  15962. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  15963. return false;
  15964. }
  15965. function loop_body(x) {
  15966. if (x instanceof AST_Switch) return x;
  15967. if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
  15968. return x.body instanceof AST_BlockStatement ? x.body : x;
  15969. }
  15970. return x;
  15971. }
  15972. function tighten_body(statements, compressor) {
  15973. var CHANGED;
  15974. do {
  15975. CHANGED = false;
  15976. statements = eliminate_spurious_blocks(statements);
  15977. if (compressor.option("dead_code")) {
  15978. statements = eliminate_dead_code(statements, compressor);
  15979. }
  15980. if (compressor.option("if_return")) {
  15981. statements = handle_if_return(statements, compressor);
  15982. }
  15983. if (compressor.option("sequences")) {
  15984. statements = sequencesize(statements, compressor);
  15985. }
  15986. if (compressor.option("join_vars")) {
  15987. statements = join_consecutive_vars(statements, compressor);
  15988. }
  15989. } while (CHANGED);
  15990. return statements;
  15991. function eliminate_spurious_blocks(statements) {
  15992. var seen_dirs = [];
  15993. return statements.reduce(function(a, stat) {
  15994. if (stat instanceof AST_BlockStatement) {
  15995. CHANGED = true;
  15996. a.push.apply(a, eliminate_spurious_blocks(stat.body));
  15997. } else if (stat instanceof AST_EmptyStatement) {
  15998. CHANGED = true;
  15999. } else if (stat instanceof AST_Directive) {
  16000. if (seen_dirs.indexOf(stat.value) < 0) {
  16001. a.push(stat);
  16002. seen_dirs.push(stat.value);
  16003. } else {
  16004. CHANGED = true;
  16005. }
  16006. } else {
  16007. a.push(stat);
  16008. }
  16009. return a;
  16010. }, []);
  16011. }
  16012. function handle_if_return(statements, compressor) {
  16013. var self = compressor.self();
  16014. var in_lambda = self instanceof AST_Lambda;
  16015. var ret = [];
  16016. loop: for (var i = statements.length; --i >= 0; ) {
  16017. var stat = statements[i];
  16018. switch (true) {
  16019. case in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0:
  16020. CHANGED = true;
  16021. continue loop;
  16022. case stat instanceof AST_If:
  16023. if (stat.body instanceof AST_Return) {
  16024. if ((in_lambda && ret.length == 0 || ret[0] instanceof AST_Return && !ret[0].value) && !stat.body.value && !stat.alternative) {
  16025. CHANGED = true;
  16026. var cond = make_node(AST_SimpleStatement, stat.condition, {
  16027. body: stat.condition
  16028. });
  16029. ret.unshift(cond);
  16030. continue loop;
  16031. }
  16032. if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
  16033. CHANGED = true;
  16034. stat = stat.clone();
  16035. stat.alternative = ret[0];
  16036. ret[0] = stat.transform(compressor);
  16037. continue loop;
  16038. }
  16039. if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) {
  16040. CHANGED = true;
  16041. stat = stat.clone();
  16042. stat.alternative = ret[0] || make_node(AST_Return, stat, {
  16043. value: make_node(AST_Undefined, stat)
  16044. });
  16045. ret[0] = stat.transform(compressor);
  16046. continue loop;
  16047. }
  16048. if (!stat.body.value && in_lambda) {
  16049. CHANGED = true;
  16050. stat = stat.clone();
  16051. stat.condition = stat.condition.negate(compressor);
  16052. stat.body = make_node(AST_BlockStatement, stat, {
  16053. body: as_statement_array(stat.alternative).concat(ret)
  16054. });
  16055. stat.alternative = null;
  16056. ret = [ stat.transform(compressor) ];
  16057. continue loop;
  16058. }
  16059. if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {
  16060. CHANGED = true;
  16061. ret.push(make_node(AST_Return, ret[0], {
  16062. value: make_node(AST_Undefined, ret[0])
  16063. }).transform(compressor));
  16064. ret = as_statement_array(stat.alternative).concat(ret);
  16065. ret.unshift(stat);
  16066. continue loop;
  16067. }
  16068. }
  16069. var ab = aborts(stat.body);
  16070. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  16071. if (ab && (ab instanceof AST_Return && !ab.value && in_lambda || ab instanceof AST_Continue && self === loop_body(lct) || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct)) {
  16072. if (ab.label) {
  16073. remove(ab.label.thedef.references, ab.label);
  16074. }
  16075. CHANGED = true;
  16076. var body = as_statement_array(stat.body).slice(0, -1);
  16077. stat = stat.clone();
  16078. stat.condition = stat.condition.negate(compressor);
  16079. stat.body = make_node(AST_BlockStatement, stat, {
  16080. body: ret
  16081. });
  16082. stat.alternative = make_node(AST_BlockStatement, stat, {
  16083. body: body
  16084. });
  16085. ret = [ stat.transform(compressor) ];
  16086. continue loop;
  16087. }
  16088. var ab = aborts(stat.alternative);
  16089. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  16090. if (ab && (ab instanceof AST_Return && !ab.value && in_lambda || ab instanceof AST_Continue && self === loop_body(lct) || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct)) {
  16091. if (ab.label) {
  16092. remove(ab.label.thedef.references, ab.label);
  16093. }
  16094. CHANGED = true;
  16095. stat = stat.clone();
  16096. stat.body = make_node(AST_BlockStatement, stat.body, {
  16097. body: as_statement_array(stat.body).concat(ret)
  16098. });
  16099. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  16100. body: as_statement_array(stat.alternative).slice(0, -1)
  16101. });
  16102. ret = [ stat.transform(compressor) ];
  16103. continue loop;
  16104. }
  16105. ret.unshift(stat);
  16106. break;
  16107. default:
  16108. ret.unshift(stat);
  16109. break;
  16110. }
  16111. }
  16112. return ret;
  16113. }
  16114. function eliminate_dead_code(statements, compressor) {
  16115. var has_quit = false;
  16116. var orig = statements.length;
  16117. var self = compressor.self();
  16118. statements = statements.reduce(function(a, stat) {
  16119. if (has_quit) {
  16120. extract_declarations_from_unreachable_code(compressor, stat, a);
  16121. } else {
  16122. if (stat instanceof AST_LoopControl) {
  16123. var lct = compressor.loopcontrol_target(stat.label);
  16124. if (stat instanceof AST_Break && lct instanceof AST_BlockStatement && loop_body(lct) === self || stat instanceof AST_Continue && loop_body(lct) === self) {
  16125. if (stat.label) {
  16126. remove(stat.label.thedef.references, stat.label);
  16127. }
  16128. } else {
  16129. a.push(stat);
  16130. }
  16131. } else {
  16132. a.push(stat);
  16133. }
  16134. if (aborts(stat)) has_quit = true;
  16135. }
  16136. return a;
  16137. }, []);
  16138. CHANGED = statements.length != orig;
  16139. return statements;
  16140. }
  16141. function sequencesize(statements, compressor) {
  16142. if (statements.length < 2) return statements;
  16143. var seq = [], ret = [];
  16144. function push_seq() {
  16145. seq = AST_Seq.from_array(seq);
  16146. if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
  16147. body: seq
  16148. }));
  16149. seq = [];
  16150. }
  16151. statements.forEach(function(stat) {
  16152. if (stat instanceof AST_SimpleStatement) seq.push(stat.body); else push_seq(), ret.push(stat);
  16153. });
  16154. push_seq();
  16155. ret = sequencesize_2(ret, compressor);
  16156. CHANGED = ret.length != statements.length;
  16157. return ret;
  16158. }
  16159. function sequencesize_2(statements, compressor) {
  16160. function cons_seq(right) {
  16161. ret.pop();
  16162. var left = prev.body;
  16163. if (left instanceof AST_Seq) {
  16164. left.add(right);
  16165. } else {
  16166. left = AST_Seq.cons(left, right);
  16167. }
  16168. return left.transform(compressor);
  16169. }
  16170. var ret = [], prev = null;
  16171. statements.forEach(function(stat) {
  16172. if (prev) {
  16173. if (stat instanceof AST_For) {
  16174. var opera = {};
  16175. try {
  16176. prev.body.walk(new TreeWalker(function(node) {
  16177. if (node instanceof AST_Binary && node.operator == "in") throw opera;
  16178. }));
  16179. if (stat.init && !(stat.init instanceof AST_Definitions)) {
  16180. stat.init = cons_seq(stat.init);
  16181. } else if (!stat.init) {
  16182. stat.init = prev.body;
  16183. ret.pop();
  16184. }
  16185. } catch (ex) {
  16186. if (ex !== opera) throw ex;
  16187. }
  16188. } else if (stat instanceof AST_If) {
  16189. stat.condition = cons_seq(stat.condition);
  16190. } else if (stat instanceof AST_With) {
  16191. stat.expression = cons_seq(stat.expression);
  16192. } else if (stat instanceof AST_Exit && stat.value) {
  16193. stat.value = cons_seq(stat.value);
  16194. } else if (stat instanceof AST_Exit) {
  16195. stat.value = cons_seq(make_node(AST_Undefined, stat));
  16196. } else if (stat instanceof AST_Switch) {
  16197. stat.expression = cons_seq(stat.expression);
  16198. }
  16199. }
  16200. ret.push(stat);
  16201. prev = stat instanceof AST_SimpleStatement ? stat : null;
  16202. });
  16203. return ret;
  16204. }
  16205. function join_consecutive_vars(statements, compressor) {
  16206. var prev = null;
  16207. return statements.reduce(function(a, stat) {
  16208. if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
  16209. prev.definitions = prev.definitions.concat(stat.definitions);
  16210. CHANGED = true;
  16211. } else if (stat instanceof AST_For && prev instanceof AST_Definitions && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  16212. CHANGED = true;
  16213. a.pop();
  16214. if (stat.init) {
  16215. stat.init.definitions = prev.definitions.concat(stat.init.definitions);
  16216. } else {
  16217. stat.init = prev;
  16218. }
  16219. a.push(stat);
  16220. prev = stat;
  16221. } else {
  16222. prev = stat;
  16223. a.push(stat);
  16224. }
  16225. return a;
  16226. }, []);
  16227. }
  16228. }
  16229. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  16230. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  16231. stat.walk(new TreeWalker(function(node) {
  16232. if (node instanceof AST_Definitions) {
  16233. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  16234. node.remove_initializers();
  16235. target.push(node);
  16236. return true;
  16237. }
  16238. if (node instanceof AST_Defun) {
  16239. target.push(node);
  16240. return true;
  16241. }
  16242. if (node instanceof AST_Scope) {
  16243. return true;
  16244. }
  16245. }));
  16246. }
  16247. (function(def) {
  16248. var unary_bool = [ "!", "delete" ];
  16249. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  16250. def(AST_Node, function() {
  16251. return false;
  16252. });
  16253. def(AST_UnaryPrefix, function() {
  16254. return member(this.operator, unary_bool);
  16255. });
  16256. def(AST_Binary, function() {
  16257. return member(this.operator, binary_bool) || (this.operator == "&&" || this.operator == "||") && this.left.is_boolean() && this.right.is_boolean();
  16258. });
  16259. def(AST_Conditional, function() {
  16260. return this.consequent.is_boolean() && this.alternative.is_boolean();
  16261. });
  16262. def(AST_Assign, function() {
  16263. return this.operator == "=" && this.right.is_boolean();
  16264. });
  16265. def(AST_Seq, function() {
  16266. return this.cdr.is_boolean();
  16267. });
  16268. def(AST_True, function() {
  16269. return true;
  16270. });
  16271. def(AST_False, function() {
  16272. return true;
  16273. });
  16274. })(function(node, func) {
  16275. node.DEFMETHOD("is_boolean", func);
  16276. });
  16277. (function(def) {
  16278. def(AST_Node, function() {
  16279. return false;
  16280. });
  16281. def(AST_String, function() {
  16282. return true;
  16283. });
  16284. def(AST_UnaryPrefix, function() {
  16285. return this.operator == "typeof";
  16286. });
  16287. def(AST_Binary, function(compressor) {
  16288. return this.operator == "+" && (this.left.is_string(compressor) || this.right.is_string(compressor));
  16289. });
  16290. def(AST_Assign, function(compressor) {
  16291. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  16292. });
  16293. def(AST_Seq, function(compressor) {
  16294. return this.cdr.is_string(compressor);
  16295. });
  16296. def(AST_Conditional, function(compressor) {
  16297. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  16298. });
  16299. def(AST_Call, function(compressor) {
  16300. return compressor.option("unsafe") && this.expression instanceof AST_SymbolRef && this.expression.name == "String" && this.expression.undeclared();
  16301. });
  16302. })(function(node, func) {
  16303. node.DEFMETHOD("is_string", func);
  16304. });
  16305. function best_of(ast1, ast2) {
  16306. return ast1.print_to_string().length > ast2.print_to_string().length ? ast2 : ast1;
  16307. }
  16308. (function(def) {
  16309. AST_Node.DEFMETHOD("evaluate", function(compressor) {
  16310. if (!compressor.option("evaluate")) return [ this ];
  16311. try {
  16312. var val = this._eval(), ast = make_node_from_constant(compressor, val, this);
  16313. return [ best_of(ast, this), val ];
  16314. } catch (ex) {
  16315. if (ex !== def) throw ex;
  16316. return [ this ];
  16317. }
  16318. });
  16319. def(AST_Statement, function() {
  16320. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  16321. });
  16322. def(AST_Function, function() {
  16323. return [ this ];
  16324. });
  16325. function ev(node) {
  16326. return node._eval();
  16327. }
  16328. def(AST_Node, function() {
  16329. throw def;
  16330. });
  16331. def(AST_Constant, function() {
  16332. return this.getValue();
  16333. });
  16334. def(AST_UnaryPrefix, function() {
  16335. var e = this.expression;
  16336. switch (this.operator) {
  16337. case "!":
  16338. return !ev(e);
  16339. case "typeof":
  16340. return typeof ev(e);
  16341. case "void":
  16342. return void ev(e);
  16343. case "~":
  16344. return ~ev(e);
  16345. case "-":
  16346. return -ev(e);
  16347. case "+":
  16348. return +ev(e);
  16349. }
  16350. throw def;
  16351. });
  16352. def(AST_Binary, function() {
  16353. var left = this.left, right = this.right;
  16354. switch (this.operator) {
  16355. case "&&":
  16356. return ev(left) && ev(right);
  16357. case "||":
  16358. return ev(left) || ev(right);
  16359. case "|":
  16360. return ev(left) | ev(right);
  16361. case "&":
  16362. return ev(left) & ev(right);
  16363. case "^":
  16364. return ev(left) ^ ev(right);
  16365. case "+":
  16366. return ev(left) + ev(right);
  16367. case "*":
  16368. return ev(left) * ev(right);
  16369. case "/":
  16370. return ev(left) / ev(right);
  16371. case "%":
  16372. return ev(left) % ev(right);
  16373. case "-":
  16374. return ev(left) - ev(right);
  16375. case "<<":
  16376. return ev(left) << ev(right);
  16377. case ">>":
  16378. return ev(left) >> ev(right);
  16379. case ">>>":
  16380. return ev(left) >>> ev(right);
  16381. case "==":
  16382. return ev(left) == ev(right);
  16383. case "===":
  16384. return ev(left) === ev(right);
  16385. case "!=":
  16386. return ev(left) != ev(right);
  16387. case "!==":
  16388. return ev(left) !== ev(right);
  16389. case "<":
  16390. return ev(left) < ev(right);
  16391. case "<=":
  16392. return ev(left) <= ev(right);
  16393. case ">":
  16394. return ev(left) > ev(right);
  16395. case ">=":
  16396. return ev(left) >= ev(right);
  16397. case "in":
  16398. return ev(left) in ev(right);
  16399. case "instanceof":
  16400. return ev(left) instanceof ev(right);
  16401. }
  16402. throw def;
  16403. });
  16404. def(AST_Conditional, function() {
  16405. return ev(this.condition) ? ev(this.consequent) : ev(this.alternative);
  16406. });
  16407. def(AST_SymbolRef, function() {
  16408. var d = this.definition();
  16409. if (d && d.constant) {
  16410. var orig = d.orig[0];
  16411. if (orig) orig = orig.init[0];
  16412. orig = orig && orig.value;
  16413. if (orig) return ev(orig);
  16414. }
  16415. throw def;
  16416. });
  16417. })(function(node, func) {
  16418. node.DEFMETHOD("_eval", func);
  16419. });
  16420. (function(def) {
  16421. function basic_negation(exp) {
  16422. return make_node(AST_UnaryPrefix, exp, {
  16423. operator: "!",
  16424. expression: exp
  16425. });
  16426. }
  16427. def(AST_Node, function() {
  16428. return basic_negation(this);
  16429. });
  16430. def(AST_Statement, function() {
  16431. throw new Error("Cannot negate a statement");
  16432. });
  16433. def(AST_Function, function() {
  16434. return basic_negation(this);
  16435. });
  16436. def(AST_UnaryPrefix, function() {
  16437. if (this.operator == "!") return this.expression;
  16438. return basic_negation(this);
  16439. });
  16440. def(AST_Seq, function(compressor) {
  16441. var self = this.clone();
  16442. self.cdr = self.cdr.negate(compressor);
  16443. return self;
  16444. });
  16445. def(AST_Conditional, function(compressor) {
  16446. var self = this.clone();
  16447. self.consequent = self.consequent.negate(compressor);
  16448. self.alternative = self.alternative.negate(compressor);
  16449. return best_of(basic_negation(this), self);
  16450. });
  16451. def(AST_Binary, function(compressor) {
  16452. var self = this.clone(), op = this.operator;
  16453. if (compressor.option("unsafe_comps")) {
  16454. switch (op) {
  16455. case "<=":
  16456. self.operator = ">";
  16457. return self;
  16458. case "<":
  16459. self.operator = ">=";
  16460. return self;
  16461. case ">=":
  16462. self.operator = "<";
  16463. return self;
  16464. case ">":
  16465. self.operator = "<=";
  16466. return self;
  16467. }
  16468. }
  16469. switch (op) {
  16470. case "==":
  16471. self.operator = "!=";
  16472. return self;
  16473. case "!=":
  16474. self.operator = "==";
  16475. return self;
  16476. case "===":
  16477. self.operator = "!==";
  16478. return self;
  16479. case "!==":
  16480. self.operator = "===";
  16481. return self;
  16482. case "&&":
  16483. self.operator = "||";
  16484. self.left = self.left.negate(compressor);
  16485. self.right = self.right.negate(compressor);
  16486. return best_of(basic_negation(this), self);
  16487. case "||":
  16488. self.operator = "&&";
  16489. self.left = self.left.negate(compressor);
  16490. self.right = self.right.negate(compressor);
  16491. return best_of(basic_negation(this), self);
  16492. }
  16493. return basic_negation(this);
  16494. });
  16495. })(function(node, func) {
  16496. node.DEFMETHOD("negate", function(compressor) {
  16497. return func.call(this, compressor);
  16498. });
  16499. });
  16500. (function(def) {
  16501. def(AST_Node, function() {
  16502. return true;
  16503. });
  16504. def(AST_EmptyStatement, function() {
  16505. return false;
  16506. });
  16507. def(AST_Constant, function() {
  16508. return false;
  16509. });
  16510. def(AST_This, function() {
  16511. return false;
  16512. });
  16513. def(AST_Block, function() {
  16514. for (var i = this.body.length; --i >= 0; ) {
  16515. if (this.body[i].has_side_effects()) return true;
  16516. }
  16517. return false;
  16518. });
  16519. def(AST_SimpleStatement, function() {
  16520. return this.body.has_side_effects();
  16521. });
  16522. def(AST_Defun, function() {
  16523. return true;
  16524. });
  16525. def(AST_Function, function() {
  16526. return false;
  16527. });
  16528. def(AST_Binary, function() {
  16529. return this.left.has_side_effects() || this.right.has_side_effects();
  16530. });
  16531. def(AST_Assign, function() {
  16532. return true;
  16533. });
  16534. def(AST_Conditional, function() {
  16535. return this.condition.has_side_effects() || this.consequent.has_side_effects() || this.alternative.has_side_effects();
  16536. });
  16537. def(AST_Unary, function() {
  16538. return this.operator == "delete" || this.operator == "++" || this.operator == "--" || this.expression.has_side_effects();
  16539. });
  16540. def(AST_SymbolRef, function() {
  16541. return false;
  16542. });
  16543. def(AST_Object, function() {
  16544. for (var i = this.properties.length; --i >= 0; ) if (this.properties[i].has_side_effects()) return true;
  16545. return false;
  16546. });
  16547. def(AST_ObjectProperty, function() {
  16548. return this.value.has_side_effects();
  16549. });
  16550. def(AST_Array, function() {
  16551. for (var i = this.elements.length; --i >= 0; ) if (this.elements[i].has_side_effects()) return true;
  16552. return false;
  16553. });
  16554. def(AST_PropAccess, function() {
  16555. return true;
  16556. });
  16557. def(AST_Seq, function() {
  16558. return this.car.has_side_effects() || this.cdr.has_side_effects();
  16559. });
  16560. })(function(node, func) {
  16561. node.DEFMETHOD("has_side_effects", func);
  16562. });
  16563. function aborts(thing) {
  16564. return thing && thing.aborts();
  16565. }
  16566. (function(def) {
  16567. def(AST_Statement, function() {
  16568. return null;
  16569. });
  16570. def(AST_Jump, function() {
  16571. return this;
  16572. });
  16573. function block_aborts() {
  16574. var n = this.body.length;
  16575. return n > 0 && aborts(this.body[n - 1]);
  16576. }
  16577. def(AST_BlockStatement, block_aborts);
  16578. def(AST_SwitchBranch, block_aborts);
  16579. def(AST_If, function() {
  16580. return this.alternative && aborts(this.body) && aborts(this.alternative);
  16581. });
  16582. })(function(node, func) {
  16583. node.DEFMETHOD("aborts", func);
  16584. });
  16585. OPT(AST_Directive, function(self, compressor) {
  16586. if (self.scope.has_directive(self.value) !== self.scope) {
  16587. return make_node(AST_EmptyStatement, self);
  16588. }
  16589. return self;
  16590. });
  16591. OPT(AST_Debugger, function(self, compressor) {
  16592. if (compressor.option("drop_debugger")) return make_node(AST_EmptyStatement, self);
  16593. return self;
  16594. });
  16595. OPT(AST_LabeledStatement, function(self, compressor) {
  16596. if (self.body instanceof AST_Break && compressor.loopcontrol_target(self.body.label) === self.body) {
  16597. return make_node(AST_EmptyStatement, self);
  16598. }
  16599. return self.label.references.length == 0 ? self.body : self;
  16600. });
  16601. OPT(AST_Block, function(self, compressor) {
  16602. self.body = tighten_body(self.body, compressor);
  16603. return self;
  16604. });
  16605. OPT(AST_BlockStatement, function(self, compressor) {
  16606. self.body = tighten_body(self.body, compressor);
  16607. switch (self.body.length) {
  16608. case 1:
  16609. return self.body[0];
  16610. case 0:
  16611. return make_node(AST_EmptyStatement, self);
  16612. }
  16613. return self;
  16614. });
  16615. AST_Scope.DEFMETHOD("drop_unused", function(compressor) {
  16616. var self = this;
  16617. if (compressor.option("unused") && !(self instanceof AST_Toplevel) && !self.uses_eval) {
  16618. var in_use = [];
  16619. var initializations = new Dictionary();
  16620. var scope = this;
  16621. var tw = new TreeWalker(function(node, descend) {
  16622. if (node !== self) {
  16623. if (node instanceof AST_Defun) {
  16624. initializations.add(node.name.name, node);
  16625. return true;
  16626. }
  16627. if (node instanceof AST_Definitions && scope === self) {
  16628. node.definitions.forEach(function(def) {
  16629. if (def.value) {
  16630. initializations.add(def.name.name, def.value);
  16631. if (def.value.has_side_effects()) {
  16632. def.value.walk(tw);
  16633. }
  16634. }
  16635. });
  16636. return true;
  16637. }
  16638. if (node instanceof AST_SymbolRef) {
  16639. push_uniq(in_use, node.definition());
  16640. return true;
  16641. }
  16642. if (node instanceof AST_Scope) {
  16643. var save_scope = scope;
  16644. scope = node;
  16645. descend();
  16646. scope = save_scope;
  16647. return true;
  16648. }
  16649. }
  16650. });
  16651. self.walk(tw);
  16652. for (var i = 0; i < in_use.length; ++i) {
  16653. in_use[i].orig.forEach(function(decl) {
  16654. var init = initializations.get(decl.name);
  16655. if (init) init.forEach(function(init) {
  16656. var tw = new TreeWalker(function(node) {
  16657. if (node instanceof AST_SymbolRef) {
  16658. push_uniq(in_use, node.definition());
  16659. }
  16660. });
  16661. init.walk(tw);
  16662. });
  16663. });
  16664. }
  16665. var tt = new TreeTransformer(function before(node, descend, in_list) {
  16666. if (node instanceof AST_Lambda) {
  16667. for (var a = node.argnames, i = a.length; --i >= 0; ) {
  16668. var sym = a[i];
  16669. if (sym.unreferenced()) {
  16670. a.pop();
  16671. compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", {
  16672. name: sym.name,
  16673. file: sym.start.file,
  16674. line: sym.start.line,
  16675. col: sym.start.col
  16676. });
  16677. } else break;
  16678. }
  16679. }
  16680. if (node instanceof AST_Defun && node !== self) {
  16681. if (!member(node.name.definition(), in_use)) {
  16682. compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", {
  16683. name: node.name.name,
  16684. file: node.name.start.file,
  16685. line: node.name.start.line,
  16686. col: node.name.start.col
  16687. });
  16688. return make_node(AST_EmptyStatement, node);
  16689. }
  16690. return node;
  16691. }
  16692. if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {
  16693. var def = node.definitions.filter(function(def) {
  16694. if (member(def.name.definition(), in_use)) return true;
  16695. var w = {
  16696. name: def.name.name,
  16697. file: def.name.start.file,
  16698. line: def.name.start.line,
  16699. col: def.name.start.col
  16700. };
  16701. if (def.value && def.value.has_side_effects()) {
  16702. def._unused_side_effects = true;
  16703. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
  16704. return true;
  16705. }
  16706. compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w);
  16707. return false;
  16708. });
  16709. def = mergeSort(def, function(a, b) {
  16710. if (!a.value && b.value) return -1;
  16711. if (!b.value && a.value) return 1;
  16712. return 0;
  16713. });
  16714. var side_effects = [];
  16715. for (var i = 0; i < def.length; ) {
  16716. var x = def[i];
  16717. if (x._unused_side_effects) {
  16718. side_effects.push(x.value);
  16719. def.splice(i, 1);
  16720. } else {
  16721. if (side_effects.length > 0) {
  16722. side_effects.push(x.value);
  16723. x.value = AST_Seq.from_array(side_effects);
  16724. side_effects = [];
  16725. }
  16726. ++i;
  16727. }
  16728. }
  16729. if (side_effects.length > 0) {
  16730. side_effects = make_node(AST_BlockStatement, node, {
  16731. body: [ make_node(AST_SimpleStatement, node, {
  16732. body: AST_Seq.from_array(side_effects)
  16733. }) ]
  16734. });
  16735. } else {
  16736. side_effects = null;
  16737. }
  16738. if (def.length == 0 && !side_effects) {
  16739. return make_node(AST_EmptyStatement, node);
  16740. }
  16741. if (def.length == 0) {
  16742. return side_effects;
  16743. }
  16744. node.definitions = def;
  16745. if (side_effects) {
  16746. side_effects.body.unshift(node);
  16747. node = side_effects;
  16748. }
  16749. return node;
  16750. }
  16751. if (node instanceof AST_For && node.init instanceof AST_BlockStatement) {
  16752. descend(node, this);
  16753. var body = node.init.body.slice(0, -1);
  16754. node.init = node.init.body.slice(-1)[0].body;
  16755. body.push(node);
  16756. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  16757. body: body
  16758. });
  16759. }
  16760. if (node instanceof AST_Scope && node !== self) return node;
  16761. });
  16762. self.transform(tt);
  16763. }
  16764. });
  16765. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) {
  16766. var hoist_funs = compressor.option("hoist_funs");
  16767. var hoist_vars = compressor.option("hoist_vars");
  16768. var self = this;
  16769. if (hoist_funs || hoist_vars) {
  16770. var dirs = [];
  16771. var hoisted = [];
  16772. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  16773. self.walk(new TreeWalker(function(node) {
  16774. if (node instanceof AST_Scope && node !== self) return true;
  16775. if (node instanceof AST_Var) {
  16776. ++var_decl;
  16777. return true;
  16778. }
  16779. }));
  16780. hoist_vars = hoist_vars && var_decl > 1;
  16781. var tt = new TreeTransformer(function before(node) {
  16782. if (node !== self) {
  16783. if (node instanceof AST_Directive) {
  16784. dirs.push(node);
  16785. return make_node(AST_EmptyStatement, node);
  16786. }
  16787. if (node instanceof AST_Defun && hoist_funs) {
  16788. hoisted.push(node);
  16789. return make_node(AST_EmptyStatement, node);
  16790. }
  16791. if (node instanceof AST_Var && hoist_vars) {
  16792. node.definitions.forEach(function(def) {
  16793. vars.set(def.name.name, def);
  16794. ++vars_found;
  16795. });
  16796. var seq = node.to_assignments();
  16797. var p = tt.parent();
  16798. if (p instanceof AST_ForIn && p.init === node) {
  16799. if (seq == null) return node.definitions[0].name;
  16800. return seq;
  16801. }
  16802. if (p instanceof AST_For && p.init === node) {
  16803. return seq;
  16804. }
  16805. if (!seq) return make_node(AST_EmptyStatement, node);
  16806. return make_node(AST_SimpleStatement, node, {
  16807. body: seq
  16808. });
  16809. }
  16810. if (node instanceof AST_Scope) return node;
  16811. }
  16812. });
  16813. self = self.transform(tt);
  16814. if (vars_found > 0) {
  16815. var defs = [];
  16816. vars.each(function(def, name) {
  16817. if (self instanceof AST_Lambda && find_if(function(x) {
  16818. return x.name == def.name.name;
  16819. }, self.argnames)) {
  16820. vars.del(name);
  16821. } else {
  16822. def = def.clone();
  16823. def.value = null;
  16824. defs.push(def);
  16825. vars.set(name, def);
  16826. }
  16827. });
  16828. if (defs.length > 0) {
  16829. for (var i = 0; i < self.body.length; ) {
  16830. if (self.body[i] instanceof AST_SimpleStatement) {
  16831. var expr = self.body[i].body, sym, assign;
  16832. if (expr instanceof AST_Assign && expr.operator == "=" && (sym = expr.left) instanceof AST_Symbol && vars.has(sym.name)) {
  16833. var def = vars.get(sym.name);
  16834. if (def.value) break;
  16835. def.value = expr.right;
  16836. remove(defs, def);
  16837. defs.push(def);
  16838. self.body.splice(i, 1);
  16839. continue;
  16840. }
  16841. if (expr instanceof AST_Seq && (assign = expr.car) instanceof AST_Assign && assign.operator == "=" && (sym = assign.left) instanceof AST_Symbol && vars.has(sym.name)) {
  16842. var def = vars.get(sym.name);
  16843. if (def.value) break;
  16844. def.value = assign.right;
  16845. remove(defs, def);
  16846. defs.push(def);
  16847. self.body[i].body = expr.cdr;
  16848. continue;
  16849. }
  16850. }
  16851. if (self.body[i] instanceof AST_EmptyStatement) {
  16852. self.body.splice(i, 1);
  16853. continue;
  16854. }
  16855. if (self.body[i] instanceof AST_BlockStatement) {
  16856. var tmp = [ i, 1 ].concat(self.body[i].body);
  16857. self.body.splice.apply(self.body, tmp);
  16858. continue;
  16859. }
  16860. break;
  16861. }
  16862. defs = make_node(AST_Var, self, {
  16863. definitions: defs
  16864. });
  16865. hoisted.push(defs);
  16866. }
  16867. }
  16868. self.body = dirs.concat(hoisted, self.body);
  16869. }
  16870. return self;
  16871. });
  16872. OPT(AST_SimpleStatement, function(self, compressor) {
  16873. if (compressor.option("side_effects")) {
  16874. if (!self.body.has_side_effects()) {
  16875. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  16876. return make_node(AST_EmptyStatement, self);
  16877. }
  16878. }
  16879. return self;
  16880. });
  16881. OPT(AST_DWLoop, function(self, compressor) {
  16882. var cond = self.condition.evaluate(compressor);
  16883. self.condition = cond[0];
  16884. if (!compressor.option("loops")) return self;
  16885. if (cond.length > 1) {
  16886. if (cond[1]) {
  16887. return make_node(AST_For, self, {
  16888. body: self.body
  16889. });
  16890. } else if (self instanceof AST_While) {
  16891. if (compressor.option("dead_code")) {
  16892. var a = [];
  16893. extract_declarations_from_unreachable_code(compressor, self.body, a);
  16894. return make_node(AST_BlockStatement, self, {
  16895. body: a
  16896. });
  16897. }
  16898. } else {
  16899. return self.body;
  16900. }
  16901. }
  16902. return self;
  16903. });
  16904. function if_break_in_loop(self, compressor) {
  16905. function drop_it(rest) {
  16906. rest = as_statement_array(rest);
  16907. if (self.body instanceof AST_BlockStatement) {
  16908. self.body = self.body.clone();
  16909. self.body.body = rest.concat(self.body.body.slice(1));
  16910. self.body = self.body.transform(compressor);
  16911. } else {
  16912. self.body = make_node(AST_BlockStatement, self.body, {
  16913. body: rest
  16914. }).transform(compressor);
  16915. }
  16916. if_break_in_loop(self, compressor);
  16917. }
  16918. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  16919. if (first instanceof AST_If) {
  16920. if (first.body instanceof AST_Break && compressor.loopcontrol_target(first.body.label) === self) {
  16921. if (self.condition) {
  16922. self.condition = make_node(AST_Binary, self.condition, {
  16923. left: self.condition,
  16924. operator: "&&",
  16925. right: first.condition.negate(compressor)
  16926. });
  16927. } else {
  16928. self.condition = first.condition.negate(compressor);
  16929. }
  16930. drop_it(first.alternative);
  16931. } else if (first.alternative instanceof AST_Break && compressor.loopcontrol_target(first.alternative.label) === self) {
  16932. if (self.condition) {
  16933. self.condition = make_node(AST_Binary, self.condition, {
  16934. left: self.condition,
  16935. operator: "&&",
  16936. right: first.condition
  16937. });
  16938. } else {
  16939. self.condition = first.condition;
  16940. }
  16941. drop_it(first.body);
  16942. }
  16943. }
  16944. }
  16945. OPT(AST_While, function(self, compressor) {
  16946. if (!compressor.option("loops")) return self;
  16947. self = AST_DWLoop.prototype.optimize.call(self, compressor);
  16948. if (self instanceof AST_While) {
  16949. if_break_in_loop(self, compressor);
  16950. self = make_node(AST_For, self, self).transform(compressor);
  16951. }
  16952. return self;
  16953. });
  16954. OPT(AST_For, function(self, compressor) {
  16955. var cond = self.condition;
  16956. if (cond) {
  16957. cond = cond.evaluate(compressor);
  16958. self.condition = cond[0];
  16959. }
  16960. if (!compressor.option("loops")) return self;
  16961. if (cond) {
  16962. if (cond.length > 1 && !cond[1]) {
  16963. if (compressor.option("dead_code")) {
  16964. var a = [];
  16965. if (self.init instanceof AST_Statement) {
  16966. a.push(self.init);
  16967. } else if (self.init) {
  16968. a.push(make_node(AST_SimpleStatement, self.init, {
  16969. body: self.init
  16970. }));
  16971. }
  16972. extract_declarations_from_unreachable_code(compressor, self.body, a);
  16973. return make_node(AST_BlockStatement, self, {
  16974. body: a
  16975. });
  16976. }
  16977. }
  16978. }
  16979. if_break_in_loop(self, compressor);
  16980. return self;
  16981. });
  16982. OPT(AST_If, function(self, compressor) {
  16983. if (!compressor.option("conditionals")) return self;
  16984. var cond = self.condition.evaluate(compressor);
  16985. self.condition = cond[0];
  16986. if (cond.length > 1) {
  16987. if (cond[1]) {
  16988. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  16989. if (compressor.option("dead_code")) {
  16990. var a = [];
  16991. if (self.alternative) {
  16992. extract_declarations_from_unreachable_code(compressor, self.alternative, a);
  16993. }
  16994. a.push(self.body);
  16995. return make_node(AST_BlockStatement, self, {
  16996. body: a
  16997. }).transform(compressor);
  16998. }
  16999. } else {
  17000. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  17001. if (compressor.option("dead_code")) {
  17002. var a = [];
  17003. extract_declarations_from_unreachable_code(compressor, self.body, a);
  17004. if (self.alternative) a.push(self.alternative);
  17005. return make_node(AST_BlockStatement, self, {
  17006. body: a
  17007. }).transform(compressor);
  17008. }
  17009. }
  17010. }
  17011. if (is_empty(self.alternative)) self.alternative = null;
  17012. var negated = self.condition.negate(compressor);
  17013. var negated_is_best = best_of(self.condition, negated) === negated;
  17014. if (self.alternative && negated_is_best) {
  17015. negated_is_best = false;
  17016. self.condition = negated;
  17017. var tmp = self.body;
  17018. self.body = self.alternative || make_node(AST_EmptyStatement);
  17019. self.alternative = tmp;
  17020. }
  17021. if (is_empty(self.body) && is_empty(self.alternative)) {
  17022. return make_node(AST_SimpleStatement, self.condition, {
  17023. body: self.condition
  17024. }).transform(compressor);
  17025. }
  17026. if (self.body instanceof AST_SimpleStatement && self.alternative instanceof AST_SimpleStatement) {
  17027. return make_node(AST_SimpleStatement, self, {
  17028. body: make_node(AST_Conditional, self, {
  17029. condition: self.condition,
  17030. consequent: self.body.body,
  17031. alternative: self.alternative.body
  17032. })
  17033. }).transform(compressor);
  17034. }
  17035. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  17036. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  17037. body: make_node(AST_Binary, self, {
  17038. operator: "||",
  17039. left: negated,
  17040. right: self.body.body
  17041. })
  17042. }).transform(compressor);
  17043. return make_node(AST_SimpleStatement, self, {
  17044. body: make_node(AST_Binary, self, {
  17045. operator: "&&",
  17046. left: self.condition,
  17047. right: self.body.body
  17048. })
  17049. }).transform(compressor);
  17050. }
  17051. if (self.body instanceof AST_EmptyStatement && self.alternative && self.alternative instanceof AST_SimpleStatement) {
  17052. return make_node(AST_SimpleStatement, self, {
  17053. body: make_node(AST_Binary, self, {
  17054. operator: "||",
  17055. left: self.condition,
  17056. right: self.alternative.body
  17057. })
  17058. }).transform(compressor);
  17059. }
  17060. if (self.body instanceof AST_Exit && self.alternative instanceof AST_Exit && self.body.TYPE == self.alternative.TYPE) {
  17061. return make_node(self.body.CTOR, self, {
  17062. value: make_node(AST_Conditional, self, {
  17063. condition: self.condition,
  17064. consequent: self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),
  17065. alternative: self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)
  17066. })
  17067. }).transform(compressor);
  17068. }
  17069. if (self.body instanceof AST_If && !self.body.alternative && !self.alternative) {
  17070. self.condition = make_node(AST_Binary, self.condition, {
  17071. operator: "&&",
  17072. left: self.condition,
  17073. right: self.body.condition
  17074. }).transform(compressor);
  17075. self.body = self.body.body;
  17076. }
  17077. if (aborts(self.body)) {
  17078. if (self.alternative) {
  17079. var alt = self.alternative;
  17080. self.alternative = null;
  17081. return make_node(AST_BlockStatement, self, {
  17082. body: [ self, alt ]
  17083. }).transform(compressor);
  17084. }
  17085. }
  17086. if (aborts(self.alternative)) {
  17087. var body = self.body;
  17088. self.body = self.alternative;
  17089. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  17090. self.alternative = null;
  17091. return make_node(AST_BlockStatement, self, {
  17092. body: [ self, body ]
  17093. }).transform(compressor);
  17094. }
  17095. return self;
  17096. });
  17097. OPT(AST_Switch, function(self, compressor) {
  17098. if (self.body.length == 0 && compressor.option("conditionals")) {
  17099. return make_node(AST_SimpleStatement, self, {
  17100. body: self.expression
  17101. }).transform(compressor);
  17102. }
  17103. var last_branch = self.body[self.body.length - 1];
  17104. if (last_branch) {
  17105. var stat = last_branch.body[last_branch.body.length - 1];
  17106. if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self) last_branch.body.pop();
  17107. }
  17108. var exp = self.expression.evaluate(compressor);
  17109. out: if (exp.length == 2) try {
  17110. self.expression = exp[0];
  17111. if (!compressor.option("dead_code")) break out;
  17112. var value = exp[1];
  17113. var in_if = false;
  17114. var in_block = false;
  17115. var started = false;
  17116. var stopped = false;
  17117. var ruined = false;
  17118. var tt = new TreeTransformer(function(node, descend, in_list) {
  17119. if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {
  17120. return node;
  17121. } else if (node instanceof AST_Switch && node === self) {
  17122. node = node.clone();
  17123. descend(node, this);
  17124. return ruined ? node : make_node(AST_BlockStatement, node, {
  17125. body: node.body.reduce(function(a, branch) {
  17126. return a.concat(branch.body);
  17127. }, [])
  17128. }).transform(compressor);
  17129. } else if (node instanceof AST_If || node instanceof AST_Try) {
  17130. var save = in_if;
  17131. in_if = !in_block;
  17132. descend(node, this);
  17133. in_if = save;
  17134. return node;
  17135. } else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {
  17136. var save = in_block;
  17137. in_block = true;
  17138. descend(node, this);
  17139. in_block = save;
  17140. return node;
  17141. } else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {
  17142. if (in_if) {
  17143. ruined = true;
  17144. return node;
  17145. }
  17146. if (in_block) return node;
  17147. stopped = true;
  17148. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  17149. } else if (node instanceof AST_SwitchBranch && this.parent() === self) {
  17150. if (stopped) return MAP.skip;
  17151. if (node instanceof AST_Case) {
  17152. var exp = node.expression.evaluate(compressor);
  17153. if (exp.length < 2) {
  17154. throw self;
  17155. }
  17156. if (exp[1] === value || started) {
  17157. started = true;
  17158. if (aborts(node)) stopped = true;
  17159. descend(node, this);
  17160. return node;
  17161. }
  17162. return MAP.skip;
  17163. }
  17164. descend(node, this);
  17165. return node;
  17166. }
  17167. });
  17168. tt.stack = compressor.stack.slice();
  17169. self = self.transform(tt);
  17170. } catch (ex) {
  17171. if (ex !== self) throw ex;
  17172. }
  17173. return self;
  17174. });
  17175. OPT(AST_Case, function(self, compressor) {
  17176. self.body = tighten_body(self.body, compressor);
  17177. return self;
  17178. });
  17179. OPT(AST_Try, function(self, compressor) {
  17180. self.body = tighten_body(self.body, compressor);
  17181. return self;
  17182. });
  17183. AST_Definitions.DEFMETHOD("remove_initializers", function() {
  17184. this.definitions.forEach(function(def) {
  17185. def.value = null;
  17186. });
  17187. });
  17188. AST_Definitions.DEFMETHOD("to_assignments", function() {
  17189. var assignments = this.definitions.reduce(function(a, def) {
  17190. if (def.value) {
  17191. var name = make_node(AST_SymbolRef, def.name, def.name);
  17192. a.push(make_node(AST_Assign, def, {
  17193. operator: "=",
  17194. left: name,
  17195. right: def.value
  17196. }));
  17197. }
  17198. return a;
  17199. }, []);
  17200. if (assignments.length == 0) return null;
  17201. return AST_Seq.from_array(assignments);
  17202. });
  17203. OPT(AST_Definitions, function(self, compressor) {
  17204. if (self.definitions.length == 0) return make_node(AST_EmptyStatement, self);
  17205. return self;
  17206. });
  17207. OPT(AST_Function, function(self, compressor) {
  17208. self = AST_Lambda.prototype.optimize.call(self, compressor);
  17209. if (compressor.option("unused")) {
  17210. if (self.name && self.name.unreferenced()) {
  17211. self.name = null;
  17212. }
  17213. }
  17214. return self;
  17215. });
  17216. OPT(AST_Call, function(self, compressor) {
  17217. if (compressor.option("unsafe")) {
  17218. var exp = self.expression;
  17219. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  17220. switch (exp.name) {
  17221. case "Array":
  17222. if (self.args.length != 1) {
  17223. return make_node(AST_Array, self, {
  17224. elements: self.args
  17225. });
  17226. }
  17227. break;
  17228. case "Object":
  17229. if (self.args.length == 0) {
  17230. return make_node(AST_Object, self, {
  17231. properties: []
  17232. });
  17233. }
  17234. break;
  17235. case "String":
  17236. return make_node(AST_Binary, self, {
  17237. left: self.args[0],
  17238. operator: "+",
  17239. right: make_node(AST_String, self, {
  17240. value: ""
  17241. })
  17242. });
  17243. }
  17244. } else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
  17245. return make_node(AST_Binary, self, {
  17246. left: make_node(AST_String, self, {
  17247. value: ""
  17248. }),
  17249. operator: "+",
  17250. right: exp.expression
  17251. }).transform(compressor);
  17252. }
  17253. }
  17254. if (compressor.option("side_effects")) {
  17255. if (self.expression instanceof AST_Function && self.args.length == 0 && !AST_Block.prototype.has_side_effects.call(self.expression)) {
  17256. return make_node(AST_Undefined, self).transform(compressor);
  17257. }
  17258. }
  17259. return self;
  17260. });
  17261. OPT(AST_New, function(self, compressor) {
  17262. if (compressor.option("unsafe")) {
  17263. var exp = self.expression;
  17264. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  17265. switch (exp.name) {
  17266. case "Object":
  17267. case "RegExp":
  17268. case "Function":
  17269. case "Error":
  17270. case "Array":
  17271. return make_node(AST_Call, self, self).transform(compressor);
  17272. }
  17273. }
  17274. }
  17275. return self;
  17276. });
  17277. OPT(AST_Seq, function(self, compressor) {
  17278. if (!compressor.option("side_effects")) return self;
  17279. if (!self.car.has_side_effects()) {
  17280. var p;
  17281. if (!(self.cdr instanceof AST_SymbolRef && self.cdr.name == "eval" && self.cdr.undeclared() && (p = compressor.parent()) instanceof AST_Call && p.expression === self)) {
  17282. return self.cdr;
  17283. }
  17284. }
  17285. if (compressor.option("cascade")) {
  17286. if (self.car instanceof AST_Assign && !self.car.left.has_side_effects() && self.car.left.equivalent_to(self.cdr)) {
  17287. return self.car;
  17288. }
  17289. if (!self.car.has_side_effects() && !self.cdr.has_side_effects() && self.car.equivalent_to(self.cdr)) {
  17290. return self.car;
  17291. }
  17292. }
  17293. return self;
  17294. });
  17295. AST_Unary.DEFMETHOD("lift_sequences", function(compressor) {
  17296. if (compressor.option("sequences")) {
  17297. if (this.expression instanceof AST_Seq) {
  17298. var seq = this.expression;
  17299. var x = seq.to_array();
  17300. this.expression = x.pop();
  17301. x.push(this);
  17302. seq = AST_Seq.from_array(x).transform(compressor);
  17303. return seq;
  17304. }
  17305. }
  17306. return this;
  17307. });
  17308. OPT(AST_UnaryPostfix, function(self, compressor) {
  17309. return self.lift_sequences(compressor);
  17310. });
  17311. OPT(AST_UnaryPrefix, function(self, compressor) {
  17312. self = self.lift_sequences(compressor);
  17313. var e = self.expression;
  17314. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  17315. switch (self.operator) {
  17316. case "!":
  17317. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  17318. return e.expression;
  17319. }
  17320. break;
  17321. case "typeof":
  17322. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  17323. return make_node(AST_True, self);
  17324. }
  17325. if (e instanceof AST_Binary && self.operator == "!") {
  17326. self = best_of(self, e.negate(compressor));
  17327. }
  17328. }
  17329. return self.evaluate(compressor)[0];
  17330. });
  17331. AST_Binary.DEFMETHOD("lift_sequences", function(compressor) {
  17332. if (compressor.option("sequences")) {
  17333. if (this.left instanceof AST_Seq) {
  17334. var seq = this.left;
  17335. var x = seq.to_array();
  17336. this.left = x.pop();
  17337. x.push(this);
  17338. seq = AST_Seq.from_array(x).transform(compressor);
  17339. return seq;
  17340. }
  17341. if (this.right instanceof AST_Seq && !(this.operator == "||" || this.operator == "&&") && !this.left.has_side_effects()) {
  17342. var seq = this.right;
  17343. var x = seq.to_array();
  17344. this.right = x.pop();
  17345. x.push(this);
  17346. seq = AST_Seq.from_array(x).transform(compressor);
  17347. return seq;
  17348. }
  17349. }
  17350. return this;
  17351. });
  17352. var commutativeOperators = makePredicate("== === != !== * & | ^");
  17353. OPT(AST_Binary, function(self, compressor) {
  17354. function reverse(op) {
  17355. if (!(self.left.has_side_effects() && self.right.has_side_effects())) {
  17356. if (op) self.operator = op;
  17357. var tmp = self.left;
  17358. self.left = self.right;
  17359. self.right = tmp;
  17360. }
  17361. }
  17362. if (commutativeOperators(self.operator)) {
  17363. if (self.right instanceof AST_Constant && !(self.left instanceof AST_Constant)) {
  17364. reverse();
  17365. }
  17366. }
  17367. self = self.lift_sequences(compressor);
  17368. if (compressor.option("comparisons")) switch (self.operator) {
  17369. case "===":
  17370. case "!==":
  17371. if (self.left.is_string(compressor) && self.right.is_string(compressor) || self.left.is_boolean() && self.right.is_boolean()) {
  17372. self.operator = self.operator.substr(0, 2);
  17373. }
  17374. case "==":
  17375. case "!=":
  17376. if (self.left instanceof AST_String && self.left.value == "undefined" && self.right instanceof AST_UnaryPrefix && self.right.operator == "typeof") {
  17377. if (!(self.right.expression instanceof AST_SymbolRef) || !self.right.expression.undeclared()) {
  17378. self.left = self.right.expression;
  17379. self.right = make_node(AST_Undefined, self.left).optimize(compressor);
  17380. if (self.operator.length == 2) self.operator += "=";
  17381. }
  17382. }
  17383. break;
  17384. }
  17385. if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
  17386. case "&&":
  17387. var ll = self.left.evaluate(compressor);
  17388. var rr = self.right.evaluate(compressor);
  17389. if (ll.length > 1 && !ll[1] || rr.length > 1 && !rr[1]) {
  17390. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  17391. return make_node(AST_False, self);
  17392. }
  17393. if (ll.length > 1 && ll[1]) {
  17394. return rr[0];
  17395. }
  17396. if (rr.length > 1 && rr[1]) {
  17397. return ll[0];
  17398. }
  17399. break;
  17400. case "||":
  17401. var ll = self.left.evaluate(compressor);
  17402. var rr = self.right.evaluate(compressor);
  17403. if (ll.length > 1 && ll[1] || rr.length > 1 && rr[1]) {
  17404. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  17405. return make_node(AST_True, self);
  17406. }
  17407. if (ll.length > 1 && !ll[1]) {
  17408. return rr[0];
  17409. }
  17410. if (rr.length > 1 && !rr[1]) {
  17411. return ll[0];
  17412. }
  17413. break;
  17414. case "+":
  17415. var ll = self.left.evaluate(compressor);
  17416. var rr = self.right.evaluate(compressor);
  17417. if (ll.length > 1 && ll[0] instanceof AST_String && ll[1] || rr.length > 1 && rr[0] instanceof AST_String && rr[1]) {
  17418. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  17419. return make_node(AST_True, self);
  17420. }
  17421. break;
  17422. }
  17423. var exp = self.evaluate(compressor);
  17424. if (exp.length > 1) {
  17425. if (best_of(exp[0], self) !== self) return exp[0];
  17426. }
  17427. if (compressor.option("comparisons")) {
  17428. if (!(compressor.parent() instanceof AST_Binary) || compressor.parent() instanceof AST_Assign) {
  17429. var negated = make_node(AST_UnaryPrefix, self, {
  17430. operator: "!",
  17431. expression: self.negate(compressor)
  17432. });
  17433. self = best_of(self, negated);
  17434. }
  17435. switch (self.operator) {
  17436. case "<":
  17437. reverse(">");
  17438. break;
  17439. case "<=":
  17440. reverse(">=");
  17441. break;
  17442. }
  17443. }
  17444. if (self.operator == "+" && self.right instanceof AST_String && self.right.getValue() === "" && self.left instanceof AST_Binary && self.left.operator == "+" && self.left.is_string(compressor)) {
  17445. return self.left;
  17446. }
  17447. return self;
  17448. });
  17449. OPT(AST_SymbolRef, function(self, compressor) {
  17450. if (self.undeclared()) {
  17451. var defines = compressor.option("global_defs");
  17452. if (defines && defines.hasOwnProperty(self.name)) {
  17453. return make_node_from_constant(compressor, defines[self.name], self);
  17454. }
  17455. switch (self.name) {
  17456. case "undefined":
  17457. return make_node(AST_Undefined, self);
  17458. case "NaN":
  17459. return make_node(AST_NaN, self);
  17460. case "Infinity":
  17461. return make_node(AST_Infinity, self);
  17462. }
  17463. }
  17464. return self;
  17465. });
  17466. OPT(AST_Undefined, function(self, compressor) {
  17467. if (compressor.option("unsafe")) {
  17468. var scope = compressor.find_parent(AST_Scope);
  17469. var undef = scope.find_variable("undefined");
  17470. if (undef) {
  17471. var ref = make_node(AST_SymbolRef, self, {
  17472. name: "undefined",
  17473. scope: scope,
  17474. thedef: undef
  17475. });
  17476. ref.reference();
  17477. return ref;
  17478. }
  17479. }
  17480. return self;
  17481. });
  17482. var ASSIGN_OPS = [ "+", "-", "/", "*", "%", ">>", "<<", ">>>", "|", "^", "&" ];
  17483. OPT(AST_Assign, function(self, compressor) {
  17484. self = self.lift_sequences(compressor);
  17485. if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary && self.right.left instanceof AST_SymbolRef && self.right.left.name == self.left.name && member(self.right.operator, ASSIGN_OPS)) {
  17486. self.operator = self.right.operator + "=";
  17487. self.right = self.right.right;
  17488. }
  17489. return self;
  17490. });
  17491. OPT(AST_Conditional, function(self, compressor) {
  17492. if (!compressor.option("conditionals")) return self;
  17493. if (self.condition instanceof AST_Seq) {
  17494. var car = self.condition.car;
  17495. self.condition = self.condition.cdr;
  17496. return AST_Seq.cons(car, self);
  17497. }
  17498. var cond = self.condition.evaluate(compressor);
  17499. if (cond.length > 1) {
  17500. if (cond[1]) {
  17501. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  17502. return self.consequent;
  17503. } else {
  17504. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  17505. return self.alternative;
  17506. }
  17507. }
  17508. var negated = cond[0].negate(compressor);
  17509. if (best_of(cond[0], negated) === negated) {
  17510. self = make_node(AST_Conditional, self, {
  17511. condition: negated,
  17512. consequent: self.alternative,
  17513. alternative: self.consequent
  17514. });
  17515. }
  17516. var consequent = self.consequent;
  17517. var alternative = self.alternative;
  17518. if (consequent instanceof AST_Assign && alternative instanceof AST_Assign && consequent.operator == alternative.operator && consequent.left.equivalent_to(alternative.left)) {
  17519. self = make_node(AST_Assign, self, {
  17520. operator: consequent.operator,
  17521. left: consequent.left,
  17522. right: make_node(AST_Conditional, self, {
  17523. condition: self.condition,
  17524. consequent: consequent.right,
  17525. alternative: alternative.right
  17526. })
  17527. });
  17528. }
  17529. return self;
  17530. });
  17531. OPT(AST_Boolean, function(self, compressor) {
  17532. if (compressor.option("booleans")) {
  17533. var p = compressor.parent();
  17534. if (p instanceof AST_Binary && (p.operator == "==" || p.operator == "!=")) {
  17535. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  17536. operator: p.operator,
  17537. value: self.value,
  17538. file: p.start.file,
  17539. line: p.start.line,
  17540. col: p.start.col
  17541. });
  17542. return make_node(AST_Number, self, {
  17543. value: +self.value
  17544. });
  17545. }
  17546. return make_node(AST_UnaryPrefix, self, {
  17547. operator: "!",
  17548. expression: make_node(AST_Number, self, {
  17549. value: 1 - self.value
  17550. })
  17551. });
  17552. }
  17553. return self;
  17554. });
  17555. OPT(AST_Sub, function(self, compressor) {
  17556. var prop = self.property;
  17557. if (prop instanceof AST_String && compressor.option("properties")) {
  17558. prop = prop.getValue();
  17559. if (is_identifier(prop)) {
  17560. return make_node(AST_Dot, self, {
  17561. expression: self.expression,
  17562. property: prop
  17563. });
  17564. }
  17565. }
  17566. return self;
  17567. });
  17568. function literals_in_boolean_context(self, compressor) {
  17569. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  17570. return make_node(AST_True, self);
  17571. }
  17572. return self;
  17573. }
  17574. OPT(AST_Array, literals_in_boolean_context);
  17575. OPT(AST_Object, literals_in_boolean_context);
  17576. OPT(AST_RegExp, literals_in_boolean_context);
  17577. })();
  17578. "use strict";
  17579. function SourceMap(options) {
  17580. options = defaults(options, {
  17581. file: null,
  17582. root: null,
  17583. orig: null
  17584. });
  17585. var generator = new MOZ_SourceMap.SourceMapGenerator({
  17586. file: options.file,
  17587. sourceRoot: options.root
  17588. });
  17589. var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
  17590. function add(source, gen_line, gen_col, orig_line, orig_col, name) {
  17591. if (orig_map) {
  17592. var info = orig_map.originalPositionFor({
  17593. line: orig_line,
  17594. column: orig_col
  17595. });
  17596. source = info.source;
  17597. orig_line = info.line;
  17598. orig_col = info.column;
  17599. name = info.name;
  17600. }
  17601. generator.addMapping({
  17602. generated: {
  17603. line: gen_line,
  17604. column: gen_col
  17605. },
  17606. original: {
  17607. line: orig_line,
  17608. column: orig_col
  17609. },
  17610. source: source,
  17611. name: name
  17612. });
  17613. }
  17614. return {
  17615. add: add,
  17616. get: function() {
  17617. return generator;
  17618. },
  17619. toString: function() {
  17620. return generator.toString();
  17621. }
  17622. };
  17623. }
  17624. "use strict";
  17625. (function() {
  17626. var MOZ_TO_ME = {
  17627. TryStatement: function(M) {
  17628. return new AST_Try({
  17629. start: my_start_token(M),
  17630. end: my_end_token(M),
  17631. body: from_moz(M.block).body,
  17632. bcatch: from_moz(M.handlers[0]),
  17633. bfinally: M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  17634. });
  17635. },
  17636. CatchClause: function(M) {
  17637. return new AST_Catch({
  17638. start: my_start_token(M),
  17639. end: my_end_token(M),
  17640. argname: from_moz(M.param),
  17641. body: from_moz(M.body).body
  17642. });
  17643. },
  17644. ObjectExpression: function(M) {
  17645. return new AST_Object({
  17646. start: my_start_token(M),
  17647. end: my_end_token(M),
  17648. properties: M.properties.map(function(prop) {
  17649. var key = prop.key;
  17650. var name = key.type == "Identifier" ? key.name : key.value;
  17651. var args = {
  17652. start: my_start_token(key),
  17653. end: my_end_token(prop.value),
  17654. key: name,
  17655. value: from_moz(prop.value)
  17656. };
  17657. switch (prop.kind) {
  17658. case "init":
  17659. return new AST_ObjectKeyVal(args);
  17660. case "set":
  17661. args.value.name = from_moz(key);
  17662. return new AST_ObjectSetter(args);
  17663. case "get":
  17664. args.value.name = from_moz(key);
  17665. return new AST_ObjectGetter(args);
  17666. }
  17667. })
  17668. });
  17669. },
  17670. SequenceExpression: function(M) {
  17671. return AST_Seq.from_array(M.expressions.map(from_moz));
  17672. },
  17673. MemberExpression: function(M) {
  17674. return new (M.computed ? AST_Sub : AST_Dot)({
  17675. start: my_start_token(M),
  17676. end: my_end_token(M),
  17677. property: M.computed ? from_moz(M.property) : M.property.name,
  17678. expression: from_moz(M.object)
  17679. });
  17680. },
  17681. SwitchCase: function(M) {
  17682. return new (M.test ? AST_Case : AST_Default)({
  17683. start: my_start_token(M),
  17684. end: my_end_token(M),
  17685. expression: from_moz(M.test),
  17686. body: M.consequent.map(from_moz)
  17687. });
  17688. },
  17689. Literal: function(M) {
  17690. var val = M.value, args = {
  17691. start: my_start_token(M),
  17692. end: my_end_token(M)
  17693. };
  17694. if (val === null) return new AST_Null(args);
  17695. switch (typeof val) {
  17696. case "string":
  17697. args.value = val;
  17698. return new AST_String(args);
  17699. case "number":
  17700. args.value = val;
  17701. return new AST_Number(args);
  17702. case "boolean":
  17703. return new (val ? AST_True : AST_False)(args);
  17704. default:
  17705. args.value = val;
  17706. return new AST_RegExp(args);
  17707. }
  17708. },
  17709. UnaryExpression: From_Moz_Unary,
  17710. UpdateExpression: From_Moz_Unary,
  17711. Identifier: function(M) {
  17712. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  17713. return new (M.name == "this" ? AST_This : p.type == "LabeledStatement" ? AST_Label : p.type == "VariableDeclarator" && p.id === M ? p.kind == "const" ? AST_SymbolConst : AST_SymbolVar : p.type == "FunctionExpression" ? p.id === M ? AST_SymbolLambda : AST_SymbolFunarg : p.type == "FunctionDeclaration" ? p.id === M ? AST_SymbolDefun : AST_SymbolFunarg : p.type == "CatchClause" ? AST_SymbolCatch : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef : AST_SymbolRef)({
  17714. start: my_start_token(M),
  17715. end: my_end_token(M),
  17716. name: M.name
  17717. });
  17718. }
  17719. };
  17720. function From_Moz_Unary(M) {
  17721. return new (M.prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  17722. start: my_start_token(M),
  17723. end: my_end_token(M),
  17724. operator: M.operator,
  17725. expression: from_moz(M.argument)
  17726. });
  17727. }
  17728. var ME_TO_MOZ = {};
  17729. map("Node", AST_Node);
  17730. map("Program", AST_Toplevel, "body@body");
  17731. map("Function", AST_Function, "id>name, params@argnames, body%body");
  17732. map("EmptyStatement", AST_EmptyStatement);
  17733. map("BlockStatement", AST_BlockStatement, "body@body");
  17734. map("ExpressionStatement", AST_SimpleStatement, "expression>body");
  17735. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  17736. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  17737. map("BreakStatement", AST_Break, "label>label");
  17738. map("ContinueStatement", AST_Continue, "label>label");
  17739. map("WithStatement", AST_With, "object>expression, body>body");
  17740. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  17741. map("ReturnStatement", AST_Return, "argument>value");
  17742. map("ThrowStatement", AST_Throw, "argument>value");
  17743. map("WhileStatement", AST_While, "test>condition, body>body");
  17744. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  17745. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  17746. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  17747. map("DebuggerStatement", AST_Debugger);
  17748. map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body");
  17749. map("VariableDeclaration", AST_Var, "declarations@definitions");
  17750. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  17751. map("ThisExpression", AST_This);
  17752. map("ArrayExpression", AST_Array, "elements@elements");
  17753. map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body");
  17754. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  17755. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  17756. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  17757. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  17758. map("NewExpression", AST_New, "callee>expression, arguments@args");
  17759. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  17760. function my_start_token(moznode) {
  17761. return new AST_Token({
  17762. file: moznode.loc && moznode.loc.source,
  17763. line: moznode.loc && moznode.loc.start.line,
  17764. col: moznode.loc && moznode.loc.start.column,
  17765. pos: moznode.start,
  17766. endpos: moznode.start
  17767. });
  17768. }
  17769. function my_end_token(moznode) {
  17770. return new AST_Token({
  17771. file: moznode.loc && moznode.loc.source,
  17772. line: moznode.loc && moznode.loc.end.line,
  17773. col: moznode.loc && moznode.loc.end.column,
  17774. pos: moznode.end,
  17775. endpos: moznode.end
  17776. });
  17777. }
  17778. function map(moztype, mytype, propmap) {
  17779. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  17780. moz_to_me += "return new mytype({\n" + "start: my_start_token(M),\n" + "end: my_end_token(M)";
  17781. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop) {
  17782. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  17783. if (!m) throw new Error("Can't understand property map: " + prop);
  17784. var moz = "M." + m[1], how = m[2], my = m[3];
  17785. moz_to_me += ",\n" + my + ": ";
  17786. if (how == "@") {
  17787. moz_to_me += moz + ".map(from_moz)";
  17788. } else if (how == ">") {
  17789. moz_to_me += "from_moz(" + moz + ")";
  17790. } else if (how == "=") {
  17791. moz_to_me += moz;
  17792. } else if (how == "%") {
  17793. moz_to_me += "from_moz(" + moz + ").body";
  17794. } else throw new Error("Can't understand operator in propmap: " + prop);
  17795. });
  17796. moz_to_me += "\n})}";
  17797. moz_to_me = new Function("mytype", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(mytype, my_start_token, my_end_token, from_moz);
  17798. return MOZ_TO_ME[moztype] = moz_to_me;
  17799. }
  17800. var FROM_MOZ_STACK = null;
  17801. function from_moz(node) {
  17802. FROM_MOZ_STACK.push(node);
  17803. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  17804. FROM_MOZ_STACK.pop();
  17805. return ret;
  17806. }
  17807. AST_Node.from_mozilla_ast = function(node) {
  17808. var save_stack = FROM_MOZ_STACK;
  17809. FROM_MOZ_STACK = [];
  17810. var ast = from_moz(node);
  17811. FROM_MOZ_STACK = save_stack;
  17812. return ast;
  17813. };
  17814. })();
  17815. exports["array_to_hash"] = array_to_hash;
  17816. exports["slice"] = slice;
  17817. exports["characters"] = characters;
  17818. exports["member"] = member;
  17819. exports["find_if"] = find_if;
  17820. exports["repeat_string"] = repeat_string;
  17821. exports["DefaultsError"] = DefaultsError;
  17822. exports["defaults"] = defaults;
  17823. exports["merge"] = merge;
  17824. exports["noop"] = noop;
  17825. exports["MAP"] = MAP;
  17826. exports["push_uniq"] = push_uniq;
  17827. exports["string_template"] = string_template;
  17828. exports["remove"] = remove;
  17829. exports["mergeSort"] = mergeSort;
  17830. exports["set_difference"] = set_difference;
  17831. exports["set_intersection"] = set_intersection;
  17832. exports["makePredicate"] = makePredicate;
  17833. exports["Dictionary"] = Dictionary;
  17834. exports["DEFNODE"] = DEFNODE;
  17835. exports["AST_Token"] = AST_Token;
  17836. exports["AST_Node"] = AST_Node;
  17837. exports["AST_Statement"] = AST_Statement;
  17838. exports["AST_Debugger"] = AST_Debugger;
  17839. exports["AST_Directive"] = AST_Directive;
  17840. exports["AST_SimpleStatement"] = AST_SimpleStatement;
  17841. exports["walk_body"] = walk_body;
  17842. exports["AST_Block"] = AST_Block;
  17843. exports["AST_BlockStatement"] = AST_BlockStatement;
  17844. exports["AST_EmptyStatement"] = AST_EmptyStatement;
  17845. exports["AST_StatementWithBody"] = AST_StatementWithBody;
  17846. exports["AST_LabeledStatement"] = AST_LabeledStatement;
  17847. exports["AST_DWLoop"] = AST_DWLoop;
  17848. exports["AST_Do"] = AST_Do;
  17849. exports["AST_While"] = AST_While;
  17850. exports["AST_For"] = AST_For;
  17851. exports["AST_ForIn"] = AST_ForIn;
  17852. exports["AST_With"] = AST_With;
  17853. exports["AST_Scope"] = AST_Scope;
  17854. exports["AST_Toplevel"] = AST_Toplevel;
  17855. exports["AST_Lambda"] = AST_Lambda;
  17856. exports["AST_Accessor"] = AST_Accessor;
  17857. exports["AST_Function"] = AST_Function;
  17858. exports["AST_Defun"] = AST_Defun;
  17859. exports["AST_Jump"] = AST_Jump;
  17860. exports["AST_Exit"] = AST_Exit;
  17861. exports["AST_Return"] = AST_Return;
  17862. exports["AST_Throw"] = AST_Throw;
  17863. exports["AST_LoopControl"] = AST_LoopControl;
  17864. exports["AST_Break"] = AST_Break;
  17865. exports["AST_Continue"] = AST_Continue;
  17866. exports["AST_If"] = AST_If;
  17867. exports["AST_Switch"] = AST_Switch;
  17868. exports["AST_SwitchBranch"] = AST_SwitchBranch;
  17869. exports["AST_Default"] = AST_Default;
  17870. exports["AST_Case"] = AST_Case;
  17871. exports["AST_Try"] = AST_Try;
  17872. exports["AST_Catch"] = AST_Catch;
  17873. exports["AST_Finally"] = AST_Finally;
  17874. exports["AST_Definitions"] = AST_Definitions;
  17875. exports["AST_Var"] = AST_Var;
  17876. exports["AST_Const"] = AST_Const;
  17877. exports["AST_VarDef"] = AST_VarDef;
  17878. exports["AST_Call"] = AST_Call;
  17879. exports["AST_New"] = AST_New;
  17880. exports["AST_Seq"] = AST_Seq;
  17881. exports["AST_PropAccess"] = AST_PropAccess;
  17882. exports["AST_Dot"] = AST_Dot;
  17883. exports["AST_Sub"] = AST_Sub;
  17884. exports["AST_Unary"] = AST_Unary;
  17885. exports["AST_UnaryPrefix"] = AST_UnaryPrefix;
  17886. exports["AST_UnaryPostfix"] = AST_UnaryPostfix;
  17887. exports["AST_Binary"] = AST_Binary;
  17888. exports["AST_Conditional"] = AST_Conditional;
  17889. exports["AST_Assign"] = AST_Assign;
  17890. exports["AST_Array"] = AST_Array;
  17891. exports["AST_Object"] = AST_Object;
  17892. exports["AST_ObjectProperty"] = AST_ObjectProperty;
  17893. exports["AST_ObjectKeyVal"] = AST_ObjectKeyVal;
  17894. exports["AST_ObjectSetter"] = AST_ObjectSetter;
  17895. exports["AST_ObjectGetter"] = AST_ObjectGetter;
  17896. exports["AST_Symbol"] = AST_Symbol;
  17897. exports["AST_SymbolAccessor"] = AST_SymbolAccessor;
  17898. exports["AST_SymbolDeclaration"] = AST_SymbolDeclaration;
  17899. exports["AST_SymbolVar"] = AST_SymbolVar;
  17900. exports["AST_SymbolConst"] = AST_SymbolConst;
  17901. exports["AST_SymbolFunarg"] = AST_SymbolFunarg;
  17902. exports["AST_SymbolDefun"] = AST_SymbolDefun;
  17903. exports["AST_SymbolLambda"] = AST_SymbolLambda;
  17904. exports["AST_SymbolCatch"] = AST_SymbolCatch;
  17905. exports["AST_Label"] = AST_Label;
  17906. exports["AST_SymbolRef"] = AST_SymbolRef;
  17907. exports["AST_LabelRef"] = AST_LabelRef;
  17908. exports["AST_This"] = AST_This;
  17909. exports["AST_Constant"] = AST_Constant;
  17910. exports["AST_String"] = AST_String;
  17911. exports["AST_Number"] = AST_Number;
  17912. exports["AST_RegExp"] = AST_RegExp;
  17913. exports["AST_Atom"] = AST_Atom;
  17914. exports["AST_Null"] = AST_Null;
  17915. exports["AST_NaN"] = AST_NaN;
  17916. exports["AST_Undefined"] = AST_Undefined;
  17917. exports["AST_Infinity"] = AST_Infinity;
  17918. exports["AST_Boolean"] = AST_Boolean;
  17919. exports["AST_False"] = AST_False;
  17920. exports["AST_True"] = AST_True;
  17921. exports["TreeWalker"] = TreeWalker;
  17922. exports["KEYWORDS"] = KEYWORDS;
  17923. exports["KEYWORDS_ATOM"] = KEYWORDS_ATOM;
  17924. exports["RESERVED_WORDS"] = RESERVED_WORDS;
  17925. exports["KEYWORDS_BEFORE_EXPRESSION"] = KEYWORDS_BEFORE_EXPRESSION;
  17926. exports["OPERATOR_CHARS"] = OPERATOR_CHARS;
  17927. exports["RE_HEX_NUMBER"] = RE_HEX_NUMBER;
  17928. exports["RE_OCT_NUMBER"] = RE_OCT_NUMBER;
  17929. exports["RE_DEC_NUMBER"] = RE_DEC_NUMBER;
  17930. exports["OPERATORS"] = OPERATORS;
  17931. exports["WHITESPACE_CHARS"] = WHITESPACE_CHARS;
  17932. exports["PUNC_BEFORE_EXPRESSION"] = PUNC_BEFORE_EXPRESSION;
  17933. exports["PUNC_CHARS"] = PUNC_CHARS;
  17934. exports["REGEXP_MODIFIERS"] = REGEXP_MODIFIERS;
  17935. exports["UNICODE"] = UNICODE;
  17936. exports["is_letter"] = is_letter;
  17937. exports["is_digit"] = is_digit;
  17938. exports["is_alphanumeric_char"] = is_alphanumeric_char;
  17939. exports["is_unicode_combining_mark"] = is_unicode_combining_mark;
  17940. exports["is_unicode_connector_punctuation"] = is_unicode_connector_punctuation;
  17941. exports["is_identifier"] = is_identifier;
  17942. exports["is_identifier_start"] = is_identifier_start;
  17943. exports["is_identifier_char"] = is_identifier_char;
  17944. exports["parse_js_number"] = parse_js_number;
  17945. exports["JS_Parse_Error"] = JS_Parse_Error;
  17946. exports["js_error"] = js_error;
  17947. exports["is_token"] = is_token;
  17948. exports["EX_EOF"] = EX_EOF;
  17949. exports["tokenizer"] = tokenizer;
  17950. exports["UNARY_PREFIX"] = UNARY_PREFIX;
  17951. exports["UNARY_POSTFIX"] = UNARY_POSTFIX;
  17952. exports["ASSIGNMENT"] = ASSIGNMENT;
  17953. exports["PRECEDENCE"] = PRECEDENCE;
  17954. exports["STATEMENTS_WITH_LABELS"] = STATEMENTS_WITH_LABELS;
  17955. exports["ATOMIC_START_TOKEN"] = ATOMIC_START_TOKEN;
  17956. exports["parse"] = parse;
  17957. exports["TreeTransformer"] = TreeTransformer;
  17958. exports["SymbolDef"] = SymbolDef;
  17959. exports["base54"] = base54;
  17960. exports["OutputStream"] = OutputStream;
  17961. exports["Compressor"] = Compressor;
  17962. exports["SourceMap"] = SourceMap;
  17963. })({}, function() {
  17964. return exports;
  17965. }());
  17966. var UglifyJS = exports.UglifyJS;
  17967. UglifyJS.AST_Node.warn_function = function(txt) {
  17968. logger.error("uglifyjs2 WARN: " + txt);
  17969. };
  17970. //JRB: MODIFIED FROM UGLIFY SOURCE
  17971. //to take a name for the file, and then set toplevel.filename to be that name.
  17972. exports.minify = function(files, options, name) {
  17973. options = UglifyJS.defaults(options, {
  17974. outSourceMap : null,
  17975. sourceRoot : null,
  17976. inSourceMap : null,
  17977. fromString : false,
  17978. warnings : false,
  17979. mangle : {},
  17980. output : null,
  17981. compress : {}
  17982. });
  17983. if (typeof files == "string")
  17984. files = [ files ];
  17985. // 1. parse
  17986. var toplevel = null;
  17987. files.forEach(function(file){
  17988. var code = options.fromString
  17989. ? file
  17990. : fs.readFileSync(file, "utf8");
  17991. toplevel = UglifyJS.parse(code, {
  17992. filename: options.fromString ? name : file,
  17993. toplevel: toplevel
  17994. });
  17995. });
  17996. // 2. compress
  17997. if (options.compress) {
  17998. var compress = { warnings: options.warnings };
  17999. UglifyJS.merge(compress, options.compress);
  18000. toplevel.figure_out_scope();
  18001. var sq = UglifyJS.Compressor(compress);
  18002. toplevel = toplevel.transform(sq);
  18003. }
  18004. // 3. mangle
  18005. if (options.mangle) {
  18006. toplevel.figure_out_scope();
  18007. toplevel.compute_char_frequency();
  18008. toplevel.mangle_names(options.mangle);
  18009. }
  18010. // 4. output
  18011. var map = null;
  18012. var inMap = null;
  18013. if (options.inSourceMap) {
  18014. inMap = fs.readFileSync(options.inSourceMap, "utf8");
  18015. }
  18016. if (options.outSourceMap) map = UglifyJS.SourceMap({
  18017. file: options.outSourceMap,
  18018. orig: inMap,
  18019. root: options.sourceRoot
  18020. });
  18021. var output = { source_map: map };
  18022. if (options.output) {
  18023. UglifyJS.merge(output, options.output);
  18024. }
  18025. var stream = UglifyJS.OutputStream(output);
  18026. toplevel.print(stream);
  18027. return {
  18028. code : stream + "",
  18029. map : map + ""
  18030. };
  18031. };
  18032. // exports.describe_ast = function() {
  18033. // function doitem(ctor) {
  18034. // var sub = {};
  18035. // ctor.SUBCLASSES.forEach(function(ctor){
  18036. // sub[ctor.TYPE] = doitem(ctor);
  18037. // });
  18038. // var ret = {};
  18039. // if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS;
  18040. // if (ctor.SUBCLASSES.length > 0) ret.sub = sub;
  18041. // return ret;
  18042. // }
  18043. // return doitem(UglifyJS.AST_Node).sub;
  18044. // }
  18045. exports.describe_ast = function() {
  18046. var out = UglifyJS.OutputStream({ beautify: true });
  18047. function doitem(ctor) {
  18048. out.print("AST_" + ctor.TYPE);
  18049. var props = ctor.SELF_PROPS.filter(function(prop){
  18050. return !/^\$/.test(prop);
  18051. });
  18052. if (props.length > 0) {
  18053. out.space();
  18054. out.with_parens(function(){
  18055. props.forEach(function(prop, i){
  18056. if (i) out.space();
  18057. out.print(prop);
  18058. });
  18059. });
  18060. }
  18061. if (ctor.documentation) {
  18062. out.space();
  18063. out.print_string(ctor.documentation);
  18064. }
  18065. if (ctor.SUBCLASSES.length > 0) {
  18066. out.space();
  18067. out.with_block(function(){
  18068. ctor.SUBCLASSES.forEach(function(ctor, i){
  18069. out.indent();
  18070. doitem(ctor);
  18071. out.newline();
  18072. });
  18073. });
  18074. }
  18075. };
  18076. doitem(UglifyJS.AST_Node);
  18077. return out + "";
  18078. };
  18079. });
  18080. /**
  18081. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  18082. * Available via the MIT or new BSD license.
  18083. * see: http://github.com/jrburke/requirejs for details
  18084. */
  18085. /*jslint plusplus: true */
  18086. /*global define: false */
  18087. define('parse', ['./esprima'], function (esprima) {
  18088. 'use strict';
  18089. //This string is saved off because JSLint complains
  18090. //about obj.arguments use, as 'reserved word'
  18091. var argPropName = 'arguments';
  18092. //From an esprima example for traversing its ast.
  18093. function traverse(object, visitor) {
  18094. var key, child;
  18095. if (!object) {
  18096. return;
  18097. }
  18098. if (visitor.call(null, object) === false) {
  18099. return false;
  18100. }
  18101. for (key in object) {
  18102. if (object.hasOwnProperty(key)) {
  18103. child = object[key];
  18104. if (typeof child === 'object' && child !== null) {
  18105. if (traverse(child, visitor) === false) {
  18106. return false;
  18107. }
  18108. }
  18109. }
  18110. }
  18111. }
  18112. /**
  18113. * Pulls out dependencies from an array literal with just string members.
  18114. * If string literals, will just return those string values in an array,
  18115. * skipping other items in the array.
  18116. *
  18117. * @param {Node} node an AST node.
  18118. *
  18119. * @returns {Array} an array of strings.
  18120. * If null is returned, then it means the input node was not a valid
  18121. * dependency.
  18122. */
  18123. function getValidDeps(node) {
  18124. if (!node || node.type !== 'ArrayExpression' || !node.elements) {
  18125. return;
  18126. }
  18127. var deps = [];
  18128. node.elements.some(function (elem) {
  18129. if (elem.type === 'Literal') {
  18130. deps.push(elem.value);
  18131. }
  18132. });
  18133. return deps.length ? deps : undefined;
  18134. }
  18135. /**
  18136. * Main parse function. Returns a string of any valid require or
  18137. * define/require.def calls as part of one JavaScript source string.
  18138. * @param {String} moduleName the module name that represents this file.
  18139. * It is used to create a default define if there is not one already for the
  18140. * file. This allows properly tracing dependencies for builds. Otherwise, if
  18141. * the file just has a require() call, the file dependencies will not be
  18142. * properly reflected: the file will come before its dependencies.
  18143. * @param {String} moduleName
  18144. * @param {String} fileName
  18145. * @param {String} fileContents
  18146. * @param {Object} options optional options. insertNeedsDefine: true will
  18147. * add calls to require.needsDefine() if appropriate.
  18148. * @returns {String} JS source string or null, if no require or
  18149. * define/require.def calls are found.
  18150. */
  18151. function parse(moduleName, fileName, fileContents, options) {
  18152. options = options || {};
  18153. //Set up source input
  18154. var i, moduleCall, depString,
  18155. moduleDeps = [],
  18156. result = '',
  18157. moduleList = [],
  18158. needsDefine = true,
  18159. astRoot = esprima.parse(fileContents);
  18160. parse.recurse(astRoot, function (callName, config, name, deps) {
  18161. if (!deps) {
  18162. deps = [];
  18163. }
  18164. if (callName === 'define' && (!name || name === moduleName)) {
  18165. needsDefine = false;
  18166. }
  18167. if (!name) {
  18168. //If there is no module name, the dependencies are for
  18169. //this file/default module name.
  18170. moduleDeps = moduleDeps.concat(deps);
  18171. } else {
  18172. moduleList.push({
  18173. name: name,
  18174. deps: deps
  18175. });
  18176. }
  18177. //If define was found, no need to dive deeper, unless
  18178. //the config explicitly wants to dig deeper.
  18179. return !!options.findNestedDependencies;
  18180. }, options);
  18181. if (options.insertNeedsDefine && needsDefine) {
  18182. result += 'require.needsDefine("' + moduleName + '");';
  18183. }
  18184. if (moduleDeps.length || moduleList.length) {
  18185. for (i = 0; i < moduleList.length; i++) {
  18186. moduleCall = moduleList[i];
  18187. if (result) {
  18188. result += '\n';
  18189. }
  18190. //If this is the main module for this file, combine any
  18191. //"anonymous" dependencies (could come from a nested require
  18192. //call) with this module.
  18193. if (moduleCall.name === moduleName) {
  18194. moduleCall.deps = moduleCall.deps.concat(moduleDeps);
  18195. moduleDeps = [];
  18196. }
  18197. depString = moduleCall.deps.length ? '["' +
  18198. moduleCall.deps.join('","') + '"]' : '[]';
  18199. result += 'define("' + moduleCall.name + '",' +
  18200. depString + ');';
  18201. }
  18202. if (moduleDeps.length) {
  18203. if (result) {
  18204. result += '\n';
  18205. }
  18206. depString = moduleDeps.length ? '["' + moduleDeps.join('","') +
  18207. '"]' : '[]';
  18208. result += 'define("' + moduleName + '",' + depString + ');';
  18209. }
  18210. }
  18211. return result || null;
  18212. }
  18213. /**
  18214. * Handles parsing a file recursively for require calls.
  18215. * @param {Array} parentNode the AST node to start with.
  18216. * @param {Function} onMatch function to call on a parse match.
  18217. * @param {Object} [options] This is normally the build config options if
  18218. * it is passed.
  18219. */
  18220. parse.recurse = function (object, onMatch, options) {
  18221. //Like traverse, but skips if branches that would not be processed
  18222. //after has application that results in tests of true or false boolean
  18223. //literal values.
  18224. var key, child,
  18225. hasHas = options && options.has;
  18226. if (!object) {
  18227. return;
  18228. }
  18229. //If has replacement has resulted in if(true){} or if(false){}, take
  18230. //the appropriate branch and skip the other one.
  18231. if (hasHas && object.type === 'IfStatement' && object.test.type &&
  18232. object.test.type === 'Literal') {
  18233. if (object.test.value) {
  18234. //Take the if branch
  18235. this.recurse(object.consequent, onMatch, options);
  18236. } else {
  18237. //Take the else branch
  18238. this.recurse(object.alternate, onMatch, options);
  18239. }
  18240. } else {
  18241. if (this.parseNode(object, onMatch) === false) {
  18242. return;
  18243. }
  18244. for (key in object) {
  18245. if (object.hasOwnProperty(key)) {
  18246. child = object[key];
  18247. if (typeof child === 'object' && child !== null) {
  18248. this.recurse(child, onMatch, options);
  18249. }
  18250. }
  18251. }
  18252. }
  18253. };
  18254. /**
  18255. * Determines if the file defines the require/define module API.
  18256. * Specifically, it looks for the `define.amd = ` expression.
  18257. * @param {String} fileName
  18258. * @param {String} fileContents
  18259. * @returns {Boolean}
  18260. */
  18261. parse.definesRequire = function (fileName, fileContents) {
  18262. var found = false;
  18263. traverse(esprima.parse(fileContents), function (node) {
  18264. if (parse.hasDefineAmd(node)) {
  18265. found = true;
  18266. //Stop traversal
  18267. return false;
  18268. }
  18269. });
  18270. return found;
  18271. };
  18272. /**
  18273. * Finds require("") calls inside a CommonJS anonymous module wrapped in a
  18274. * define(function(require, exports, module){}) wrapper. These dependencies
  18275. * will be added to a modified define() call that lists the dependencies
  18276. * on the outside of the function.
  18277. * @param {String} fileName
  18278. * @param {String} fileContents
  18279. * @returns {Array} an array of module names that are dependencies. Always
  18280. * returns an array, but could be of length zero.
  18281. */
  18282. parse.getAnonDeps = function (fileName, fileContents) {
  18283. var astRoot = esprima.parse(fileContents),
  18284. defFunc = this.findAnonDefineFactory(astRoot);
  18285. return parse.getAnonDepsFromNode(defFunc);
  18286. };
  18287. /**
  18288. * Finds require("") calls inside a CommonJS anonymous module wrapped
  18289. * in a define function, given an AST node for the definition function.
  18290. * @param {Node} node the AST node for the definition function.
  18291. * @returns {Array} and array of dependency names. Can be of zero length.
  18292. */
  18293. parse.getAnonDepsFromNode = function (node) {
  18294. var deps = [],
  18295. funcArgLength;
  18296. if (node) {
  18297. this.findRequireDepNames(node, deps);
  18298. //If no deps, still add the standard CommonJS require, exports,
  18299. //module, in that order, to the deps, but only if specified as
  18300. //function args. In particular, if exports is used, it is favored
  18301. //over the return value of the function, so only add it if asked.
  18302. funcArgLength = node.params && node.params.length;
  18303. if (funcArgLength) {
  18304. deps = (funcArgLength > 1 ? ["require", "exports", "module"] :
  18305. ["require"]).concat(deps);
  18306. }
  18307. }
  18308. return deps;
  18309. };
  18310. /**
  18311. * Finds the function in define(function (require, exports, module){});
  18312. * @param {Array} node
  18313. * @returns {Boolean}
  18314. */
  18315. parse.findAnonDefineFactory = function (node) {
  18316. var match;
  18317. traverse(node, function (node) {
  18318. var arg0, arg1;
  18319. if (node && node.type === 'CallExpression' &&
  18320. node.callee && node.callee.type === 'Identifier' &&
  18321. node.callee.name === 'define' && node[argPropName]) {
  18322. //Just the factory function passed to define
  18323. arg0 = node[argPropName][0];
  18324. if (arg0 && arg0.type === 'FunctionExpression') {
  18325. match = arg0;
  18326. return false;
  18327. }
  18328. //A string literal module ID followed by the factory function.
  18329. arg1 = node[argPropName][1];
  18330. if (arg0.type === 'Literal' &&
  18331. arg1 && arg1.type === 'FunctionExpression') {
  18332. match = arg1;
  18333. return false;
  18334. }
  18335. }
  18336. });
  18337. return match;
  18338. };
  18339. /**
  18340. * Finds any config that is passed to requirejs. That includes calls to
  18341. * require/requirejs.config(), as well as require({}, ...) and
  18342. * requirejs({}, ...)
  18343. * @param {String} fileContents
  18344. *
  18345. * @returns {Object} a config details object with the following properties:
  18346. * - config: {Object} the config object found. Can be undefined if no
  18347. * config found.
  18348. * - range: {Array} the start index and end index in the contents where
  18349. * the config was found. Can be undefined if no config found.
  18350. * Can throw an error if the config in the file cannot be evaluated in
  18351. * a build context to valid JavaScript.
  18352. */
  18353. parse.findConfig = function (fileContents) {
  18354. /*jslint evil: true */
  18355. var jsConfig, foundRange, foundConfig,
  18356. astRoot = esprima.parse(fileContents, {
  18357. range: true
  18358. });
  18359. traverse(astRoot, function (node) {
  18360. var arg,
  18361. requireType = parse.hasRequire(node);
  18362. if (requireType && (requireType === 'require' ||
  18363. requireType === 'requirejs' ||
  18364. requireType === 'requireConfig' ||
  18365. requireType === 'requirejsConfig')) {
  18366. arg = node[argPropName] && node[argPropName][0];
  18367. if (arg && arg.type === 'ObjectExpression') {
  18368. jsConfig = parse.nodeToString(fileContents, arg);
  18369. foundRange = arg.range;
  18370. return false;
  18371. }
  18372. } else {
  18373. arg = parse.getRequireObjectLiteral(node);
  18374. if (arg) {
  18375. jsConfig = parse.nodeToString(fileContents, arg);
  18376. foundRange = arg.range;
  18377. return false;
  18378. }
  18379. }
  18380. });
  18381. if (jsConfig) {
  18382. foundConfig = eval('(' + jsConfig + ')');
  18383. }
  18384. return {
  18385. config: foundConfig,
  18386. range: foundRange
  18387. };
  18388. };
  18389. /** Returns the node for the object literal assigned to require/requirejs,
  18390. * for holding a declarative config.
  18391. */
  18392. parse.getRequireObjectLiteral = function (node) {
  18393. if (node.id && node.id.type === 'Identifier' &&
  18394. (node.id.name === 'require' || node.id.name === 'requirejs') &&
  18395. node.init && node.init.type === 'ObjectExpression') {
  18396. return node.init;
  18397. }
  18398. };
  18399. /**
  18400. * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define
  18401. * Does *not* do .config calls though. See pragma.namespace for the complete
  18402. * set of namespace transforms. This function is used because require calls
  18403. * inside a define() call should not be renamed, so a simple regexp is not
  18404. * good enough.
  18405. * @param {String} fileContents the contents to transform.
  18406. * @param {String} ns the namespace, *not* including trailing dot.
  18407. * @return {String} the fileContents with the namespace applied
  18408. */
  18409. parse.renameNamespace = function (fileContents, ns) {
  18410. var ranges = [],
  18411. astRoot = esprima.parse(fileContents, {
  18412. range: true
  18413. });
  18414. parse.recurse(astRoot, function (callName, config, name, deps, node) {
  18415. ranges.push(node.range);
  18416. //Do not recurse into define functions, they should be using
  18417. //local defines.
  18418. return callName !== 'define';
  18419. }, {});
  18420. //Go backwards through the found ranges, adding in the namespace name
  18421. //in front.
  18422. ranges.reverse();
  18423. ranges.forEach(function (range) {
  18424. fileContents = fileContents.substring(0, range[0]) +
  18425. ns + '.' +
  18426. fileContents.substring(range[0]);
  18427. });
  18428. return fileContents;
  18429. };
  18430. /**
  18431. * Finds all dependencies specified in dependency arrays and inside
  18432. * simplified commonjs wrappers.
  18433. * @param {String} fileName
  18434. * @param {String} fileContents
  18435. *
  18436. * @returns {Array} an array of dependency strings. The dependencies
  18437. * have not been normalized, they may be relative IDs.
  18438. */
  18439. parse.findDependencies = function (fileName, fileContents, options) {
  18440. var dependencies = [],
  18441. astRoot = esprima.parse(fileContents);
  18442. parse.recurse(astRoot, function (callName, config, name, deps) {
  18443. if (deps) {
  18444. dependencies = dependencies.concat(deps);
  18445. }
  18446. }, options);
  18447. return dependencies;
  18448. };
  18449. /**
  18450. * Finds only CJS dependencies, ones that are the form
  18451. * require('stringLiteral')
  18452. */
  18453. parse.findCjsDependencies = function (fileName, fileContents) {
  18454. var dependencies = [];
  18455. traverse(esprima.parse(fileContents), function (node) {
  18456. var arg;
  18457. if (node && node.type === 'CallExpression' && node.callee &&
  18458. node.callee.type === 'Identifier' &&
  18459. node.callee.name === 'require' && node[argPropName] &&
  18460. node[argPropName].length === 1) {
  18461. arg = node[argPropName][0];
  18462. if (arg.type === 'Literal') {
  18463. dependencies.push(arg.value);
  18464. }
  18465. }
  18466. });
  18467. return dependencies;
  18468. };
  18469. //function define() {}
  18470. parse.hasDefDefine = function (node) {
  18471. return node.type === 'FunctionDeclaration' && node.id &&
  18472. node.id.type === 'Identifier' && node.id.name === 'define';
  18473. };
  18474. //define.amd = ...
  18475. parse.hasDefineAmd = function (node) {
  18476. return node && node.type === 'AssignmentExpression' &&
  18477. node.left && node.left.type === 'MemberExpression' &&
  18478. node.left.object && node.left.object.name === 'define' &&
  18479. node.left.property && node.left.property.name === 'amd';
  18480. };
  18481. //require(), requirejs(), require.config() and requirejs.config()
  18482. parse.hasRequire = function (node) {
  18483. var callName,
  18484. c = node && node.callee;
  18485. if (node && node.type === 'CallExpression' && c) {
  18486. if (c.type === 'Identifier' &&
  18487. (c.name === 'require' ||
  18488. c.name === 'requirejs')) {
  18489. //A require/requirejs({}, ...) call
  18490. callName = c.name;
  18491. } else if (c.type === 'MemberExpression' &&
  18492. c.object &&
  18493. c.object.type === 'Identifier' &&
  18494. (c.object.name === 'require' ||
  18495. c.object.name === 'requirejs') &&
  18496. c.property && c.property.name === 'config') {
  18497. // require/requirejs.config({}) call
  18498. callName = c.object.name + 'Config';
  18499. }
  18500. }
  18501. return callName;
  18502. };
  18503. //define()
  18504. parse.hasDefine = function (node) {
  18505. return node && node.type === 'CallExpression' && node.callee &&
  18506. node.callee.type === 'Identifier' &&
  18507. node.callee.name === 'define';
  18508. };
  18509. /**
  18510. * If there is a named define in the file, returns the name. Does not
  18511. * scan for mulitple names, just the first one.
  18512. */
  18513. parse.getNamedDefine = function (fileContents) {
  18514. var name;
  18515. traverse(esprima.parse(fileContents), function (node) {
  18516. if (node && node.type === 'CallExpression' && node.callee &&
  18517. node.callee.type === 'Identifier' &&
  18518. node.callee.name === 'define' &&
  18519. node[argPropName] && node[argPropName][0] &&
  18520. node[argPropName][0].type === 'Literal') {
  18521. name = node[argPropName][0].value;
  18522. return false;
  18523. }
  18524. });
  18525. return name;
  18526. };
  18527. /**
  18528. * Determines if define(), require({}|[]) or requirejs was called in the
  18529. * file. Also finds out if define() is declared and if define.amd is called.
  18530. */
  18531. parse.usesAmdOrRequireJs = function (fileName, fileContents) {
  18532. var uses;
  18533. traverse(esprima.parse(fileContents), function (node) {
  18534. var type, callName, arg;
  18535. if (parse.hasDefDefine(node)) {
  18536. //function define() {}
  18537. type = 'declaresDefine';
  18538. } else if (parse.hasDefineAmd(node)) {
  18539. type = 'defineAmd';
  18540. } else {
  18541. callName = parse.hasRequire(node);
  18542. if (callName) {
  18543. arg = node[argPropName] && node[argPropName][0];
  18544. if (arg && (arg.type === 'ObjectExpression' ||
  18545. arg.type === 'ArrayExpression')) {
  18546. type = callName;
  18547. }
  18548. } else if (parse.hasDefine(node)) {
  18549. type = 'define';
  18550. }
  18551. }
  18552. if (type) {
  18553. if (!uses) {
  18554. uses = {};
  18555. }
  18556. uses[type] = true;
  18557. }
  18558. });
  18559. return uses;
  18560. };
  18561. /**
  18562. * Determines if require(''), exports.x =, module.exports =,
  18563. * __dirname, __filename are used. So, not strictly traditional CommonJS,
  18564. * also checks for Node variants.
  18565. */
  18566. parse.usesCommonJs = function (fileName, fileContents) {
  18567. var uses = null,
  18568. assignsExports = false;
  18569. traverse(esprima.parse(fileContents), function (node) {
  18570. var type,
  18571. exp = node.expression;
  18572. if (node.type === 'Identifier' &&
  18573. (node.name === '__dirname' || node.name === '__filename')) {
  18574. type = node.name.substring(2);
  18575. } else if (node.type === 'VariableDeclarator' && node.id &&
  18576. node.id.type === 'Identifier' &&
  18577. node.id.name === 'exports') {
  18578. //Hmm, a variable assignment for exports, so does not use cjs
  18579. //exports.
  18580. type = 'varExports';
  18581. } else if (exp && exp.type === 'AssignmentExpression' && exp.left &&
  18582. exp.left.type === 'MemberExpression' && exp.left.object) {
  18583. if (exp.left.object.name === 'module' && exp.left.property &&
  18584. exp.left.property.name === 'exports') {
  18585. type = 'moduleExports';
  18586. } else if (exp.left.object.name === 'exports' &&
  18587. exp.left.property) {
  18588. type = 'exports';
  18589. }
  18590. } else if (node && node.type === 'CallExpression' && node.callee &&
  18591. node.callee.type === 'Identifier' &&
  18592. node.callee.name === 'require' && node[argPropName] &&
  18593. node[argPropName].length === 1 &&
  18594. node[argPropName][0].type === 'Literal') {
  18595. type = 'require';
  18596. }
  18597. if (type) {
  18598. if (type === 'varExports') {
  18599. assignsExports = true;
  18600. } else if (type !== 'exports' || !assignsExports) {
  18601. if (!uses) {
  18602. uses = {};
  18603. }
  18604. uses[type] = true;
  18605. }
  18606. }
  18607. });
  18608. return uses;
  18609. };
  18610. parse.findRequireDepNames = function (node, deps) {
  18611. traverse(node, function (node) {
  18612. var arg;
  18613. if (node && node.type === 'CallExpression' && node.callee &&
  18614. node.callee.type === 'Identifier' &&
  18615. node.callee.name === 'require' &&
  18616. node[argPropName] && node[argPropName].length === 1) {
  18617. arg = node[argPropName][0];
  18618. if (arg.type === 'Literal') {
  18619. deps.push(arg.value);
  18620. }
  18621. }
  18622. });
  18623. };
  18624. /**
  18625. * Determines if a specific node is a valid require or define/require.def
  18626. * call.
  18627. * @param {Array} node
  18628. * @param {Function} onMatch a function to call when a match is found.
  18629. * It is passed the match name, and the config, name, deps possible args.
  18630. * The config, name and deps args are not normalized.
  18631. *
  18632. * @returns {String} a JS source string with the valid require/define call.
  18633. * Otherwise null.
  18634. */
  18635. parse.parseNode = function (node, onMatch) {
  18636. var name, deps, cjsDeps, arg, factory,
  18637. args = node && node[argPropName],
  18638. callName = parse.hasRequire(node);
  18639. if (callName === 'require' || callName === 'requirejs') {
  18640. //A plain require/requirejs call
  18641. arg = node[argPropName] && node[argPropName][0];
  18642. if (arg.type !== 'ArrayExpression') {
  18643. if (arg.type === 'ObjectExpression') {
  18644. //A config call, try the second arg.
  18645. arg = node[argPropName][1];
  18646. }
  18647. }
  18648. deps = getValidDeps(arg);
  18649. if (!deps) {
  18650. return;
  18651. }
  18652. return onMatch("require", null, null, deps, node);
  18653. } else if (parse.hasDefine(node) && args && args.length) {
  18654. name = args[0];
  18655. deps = args[1];
  18656. factory = args[2];
  18657. if (name.type === 'ArrayExpression') {
  18658. //No name, adjust args
  18659. factory = deps;
  18660. deps = name;
  18661. name = null;
  18662. } else if (name.type === 'FunctionExpression') {
  18663. //Just the factory, no name or deps
  18664. factory = name;
  18665. name = deps = null;
  18666. } else if (name.type !== 'Literal') {
  18667. //An object literal, just null out
  18668. name = deps = factory = null;
  18669. }
  18670. if (name && name.type === 'Literal' && deps) {
  18671. if (deps.type === 'FunctionExpression') {
  18672. //deps is the factory
  18673. factory = deps;
  18674. deps = null;
  18675. } else if (deps.type === 'ObjectExpression') {
  18676. //deps is object literal, null out
  18677. deps = factory = null;
  18678. }
  18679. }
  18680. if (deps && deps.type === 'ArrayExpression') {
  18681. deps = getValidDeps(deps);
  18682. } else if (factory && factory.type === 'FunctionExpression') {
  18683. //If no deps and a factory function, could be a commonjs sugar
  18684. //wrapper, scan the function for dependencies.
  18685. cjsDeps = parse.getAnonDepsFromNode(factory);
  18686. if (cjsDeps.length) {
  18687. deps = cjsDeps;
  18688. }
  18689. } else if (deps || factory) {
  18690. //Does not match the shape of an AMD call.
  18691. return;
  18692. }
  18693. //Just save off the name as a string instead of an AST object.
  18694. if (name && name.type === 'Literal') {
  18695. name = name.value;
  18696. }
  18697. return onMatch("define", null, name, deps, node);
  18698. }
  18699. };
  18700. /**
  18701. * Converts an AST node into a JS source string by extracting
  18702. * the node's location from the given contents string. Assumes
  18703. * esprima.parse() with ranges was done.
  18704. * @param {String} contents
  18705. * @param {Object} node
  18706. * @returns {String} a JS source string.
  18707. */
  18708. parse.nodeToString = function (contents, node) {
  18709. var range = node.range;
  18710. return contents.substring(range[0], range[1]);
  18711. };
  18712. /**
  18713. * Extracts license comments from JS text.
  18714. * @param {String} fileName
  18715. * @param {String} contents
  18716. * @returns {String} a string of license comments.
  18717. */
  18718. parse.getLicenseComments = function (fileName, contents) {
  18719. var commentNode, refNode, subNode, value, i, j,
  18720. ast = esprima.parse(contents, {
  18721. comment: true
  18722. }),
  18723. result = '',
  18724. existsMap = {},
  18725. lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n';
  18726. if (ast.comments) {
  18727. for (i = 0; i < ast.comments.length; i++) {
  18728. commentNode = ast.comments[i];
  18729. if (commentNode.type === 'Line') {
  18730. value = '//' + commentNode.value + lineEnd;
  18731. refNode = commentNode;
  18732. if (i + 1 >= ast.comments.length) {
  18733. value += lineEnd;
  18734. } else {
  18735. //Look for immediately adjacent single line comments
  18736. //since it could from a multiple line comment made out
  18737. //of single line comments. Like this comment.
  18738. for (j = i + 1; j < ast.comments.length; j++) {
  18739. subNode = ast.comments[j];
  18740. if (subNode.type === 'Line' &&
  18741. subNode.range[0] === refNode.range[1]) {
  18742. //Adjacent single line comment. Collect it.
  18743. value += '//' + subNode.value + lineEnd;
  18744. refNode = subNode;
  18745. } else {
  18746. //No more single line comment blocks. Break out
  18747. //and continue outer looping.
  18748. break;
  18749. }
  18750. }
  18751. value += lineEnd;
  18752. i = j - 1;
  18753. }
  18754. } else {
  18755. value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd;
  18756. }
  18757. if (!existsMap[value] && (value.indexOf('license') !== -1 ||
  18758. (commentNode.type === 'Block' &&
  18759. value.indexOf('/*!') === 0) ||
  18760. value.indexOf('opyright') !== -1 ||
  18761. value.indexOf('(c)') !== -1)) {
  18762. result += value;
  18763. existsMap[value] = true;
  18764. }
  18765. }
  18766. }
  18767. return result;
  18768. };
  18769. return parse;
  18770. });
  18771. /**
  18772. * @license Copyright (c) 2012, The Dojo Foundation All Rights Reserved.
  18773. * Available via the MIT or new BSD license.
  18774. * see: http://github.com/jrburke/requirejs for details
  18775. */
  18776. /*jslint */
  18777. /*global define */
  18778. define('transform', [ './esprima', './parse', 'logger', 'lang'], function (esprima, parse, logger, lang) {
  18779. 'use strict';
  18780. var transform,
  18781. baseIndentRegExp = /^([ \t]+)/,
  18782. indentRegExp = /\{[\r\n]+([ \t]+)/,
  18783. bulkIndentRegExps = {
  18784. '\n': /\n/g,
  18785. '\r\n': /\r\n/g
  18786. };
  18787. function applyIndent(str, indent, lineReturn) {
  18788. var regExp = bulkIndentRegExps[lineReturn];
  18789. return str.replace(regExp, '$&' + indent);
  18790. }
  18791. return (transform = {
  18792. toTransport: function (namespace, moduleName, path, contents, onFound, options) {
  18793. options = options || {};
  18794. var tokens, foundAnon, deps, lastRange, parenCount, inDefine,
  18795. scanCount = 0,
  18796. scanReset = false,
  18797. defineRanges = [],
  18798. contentInsertion = '',
  18799. depString = '';
  18800. try {
  18801. tokens = esprima.parse(contents, {
  18802. tokens: true,
  18803. range: true
  18804. }).tokens;
  18805. } catch (e) {
  18806. logger.trace('toTransport skipping ' + path + ': ' +
  18807. e.toString());
  18808. return contents;
  18809. }
  18810. //Find the define calls and their position in the files.
  18811. tokens.some(function (token, i) {
  18812. var prev, prev2, next, next2, next3, next4, next5,
  18813. needsId, depAction, nameCommaRange, foundId,
  18814. sourceUrlData, range,
  18815. namespaceExists = false;
  18816. if (inDefine && token.type === 'Punctuator') {
  18817. //Looking for the end of the define call.
  18818. if (token.value === '(') {
  18819. parenCount += 1;
  18820. } else if (token.value === ')') {
  18821. parenCount -= 1;
  18822. }
  18823. if (parenCount === 0) {
  18824. inDefine = false;
  18825. //Found the end of the define call. Hold onto
  18826. //it.
  18827. lastRange = defineRanges.length &&
  18828. defineRanges[defineRanges.length - 1];
  18829. if (lastRange && !lastRange.defineEndRange) {
  18830. lastRange.defineEndRange = token.range;
  18831. }
  18832. }
  18833. }
  18834. if (token.type === 'Identifier' && token.value === 'define') {
  18835. //Possible match. Do not want something.define calls
  18836. //though, and only defines follow by a paren
  18837. prev = tokens[i - 1];
  18838. next = tokens[i + 1];
  18839. if (prev && prev.type === 'Punctuator' &&
  18840. prev.value === '.') {
  18841. //a define on a sub-object, not a top level
  18842. //define() call. If the sub object is the
  18843. //namespace, then it is ok.
  18844. prev2 = tokens[i - 2];
  18845. if (!prev2) {
  18846. return;
  18847. }
  18848. //If the prev2 does not match namespace, then bail.
  18849. if (!namespace || prev2.type !== 'Identifier' ||
  18850. prev2.value !== namespace) {
  18851. return;
  18852. } else if (namespace) {
  18853. namespaceExists = true;
  18854. }
  18855. }
  18856. if (!next || next.type !== 'Punctuator' ||
  18857. next.value !== '(') {
  18858. //Not a define() function call. Bail.
  18859. return;
  18860. }
  18861. if (prev && prev.type === 'Keyword' &&
  18862. prev.value === 'function') {
  18863. //A declaration of a define function. Skip it.
  18864. return;
  18865. }
  18866. next2 = tokens[i + 2];
  18867. if (!next2) {
  18868. return;
  18869. }
  18870. //Figure out if this needs a named define call.
  18871. if (next2.type === 'Punctuator' && next2.value === '[') {
  18872. //Dependency array
  18873. needsId = true;
  18874. depAction = 'skip';
  18875. } else if (next2.type === 'Punctuator' &&
  18876. next2.value === '{') {
  18877. //Object literal
  18878. needsId = true;
  18879. depAction = 'skip';
  18880. } else if (next2.type === 'Keyword' &&
  18881. next2.value === 'function') {
  18882. //function
  18883. needsId = true;
  18884. depAction = 'scan';
  18885. } else if (next2.type === 'String') {
  18886. //Named module
  18887. needsId = false;
  18888. //The value includes the quotes around the string,
  18889. //so remove them.
  18890. foundId = next2.value.substring(1,
  18891. next2.value.length - 1);
  18892. //assumed it does not need dependencies injected
  18893. //If next argument is a function it means we need
  18894. //dependency scanning.
  18895. next3 = tokens[i + 3];
  18896. next4 = tokens[i + 4];
  18897. if (!next3 || !next4) {
  18898. return;
  18899. }
  18900. if (next3.type === 'Punctuator' &&
  18901. next3.value === ',' &&
  18902. next4.type === 'Keyword' &&
  18903. next4.value === 'function') {
  18904. depAction = 'scan';
  18905. nameCommaRange = next3.range;
  18906. } else {
  18907. depAction = 'skip';
  18908. }
  18909. } else if (next2.type === 'Identifier') {
  18910. //May be the define(factory); type.
  18911. next3 = tokens[i + 3];
  18912. if (!next3) {
  18913. return;
  18914. }
  18915. if (next3.type === 'Punctuator' &&
  18916. next3.value === ')') {
  18917. needsId = true;
  18918. depAction = 'empty';
  18919. } else {
  18920. return;
  18921. }
  18922. } else if (next2.type === 'Numeric') {
  18923. //May be the define(12345); type.
  18924. next3 = tokens[i + 3];
  18925. if (!next3) {
  18926. return;
  18927. }
  18928. if (next3.type === 'Punctuator' &&
  18929. next3.value === ')') {
  18930. needsId = true;
  18931. depAction = 'skip';
  18932. } else {
  18933. return;
  18934. }
  18935. } else if (next2.type === 'Punctuator' &&
  18936. next2.value === '-') {
  18937. //May be the define(-12345); type.
  18938. next3 = tokens[i + 3];
  18939. if (!next3) {
  18940. return;
  18941. }
  18942. if (next3.type === 'Numeric') {
  18943. next4 = tokens[i + 4];
  18944. if (!next4) {
  18945. return;
  18946. }
  18947. if (next4.type === 'Punctuator' &&
  18948. next4.value === ')') {
  18949. needsId = true;
  18950. depAction = 'skip';
  18951. } else {
  18952. return;
  18953. }
  18954. } else {
  18955. return;
  18956. }
  18957. } else if (next2.type === 'Keyword' && next2.value === 'this') {
  18958. //May be the define(this.key); type
  18959. next3 = tokens[i + 3];
  18960. next4 = tokens[i + 4];
  18961. next5 = tokens[i + 5];
  18962. if (!next3 || !next4 || !next5) {
  18963. return;
  18964. }
  18965. if (next3.type === 'Punctuator' && next3.value === '.' &&
  18966. next4.type === 'Identifier' &&
  18967. next5.type === 'Punctuator' && next5.value === ')') {
  18968. needsId = true;
  18969. depAction = 'empty';
  18970. } else {
  18971. return;
  18972. }
  18973. } else {
  18974. //Not a match, skip it.
  18975. return;
  18976. }
  18977. //A valid define call. Need to find the end, start counting
  18978. //parentheses.
  18979. inDefine = true;
  18980. parenCount = 0;
  18981. range = {
  18982. foundId: foundId,
  18983. needsId: needsId,
  18984. depAction: depAction,
  18985. namespaceExists: namespaceExists,
  18986. defineRange: token.range,
  18987. parenRange: next.range,
  18988. nameCommaRange: nameCommaRange,
  18989. sourceUrlData: sourceUrlData
  18990. };
  18991. //Only transform ones that do not have IDs. If it has an
  18992. //ID but no dependency array, assume it is something like
  18993. //a phonegap implementation, that has its own internal
  18994. //define that cannot handle dependency array constructs,
  18995. //and if it is a named module, then it means it has been
  18996. //set for transport form.
  18997. if (range.needsId) {
  18998. if (foundAnon) {
  18999. logger.trace(path + ' has more than one anonymous ' +
  19000. 'define. May be a built file from another ' +
  19001. 'build system like, Ender. Skipping normalization.');
  19002. defineRanges = [];
  19003. return true;
  19004. } else {
  19005. foundAnon = range;
  19006. defineRanges.push(range);
  19007. }
  19008. } else if (depAction === 'scan') {
  19009. scanCount += 1;
  19010. if (scanCount > 1) {
  19011. //Just go back to an array that just has the
  19012. //anon one, since this is an already optimized
  19013. //file like the phonegap one.
  19014. if (!scanReset) {
  19015. defineRanges = foundAnon ? [foundAnon] : [];
  19016. scanReset = true;
  19017. }
  19018. } else {
  19019. defineRanges.push(range);
  19020. }
  19021. }
  19022. }
  19023. });
  19024. if (!defineRanges.length) {
  19025. return contents;
  19026. }
  19027. //Reverse the matches, need to start from the bottom of
  19028. //the file to modify it, so that the ranges are still true
  19029. //further up.
  19030. defineRanges.reverse();
  19031. defineRanges.forEach(function (info) {
  19032. //Do the modifications "backwards", in other words, start with the
  19033. //one that is farthest down and work up, so that the ranges in the
  19034. //defineRanges still apply. So that means deps, id, then namespace.
  19035. if (info.needsId && moduleName) {
  19036. contentInsertion += "'" + moduleName + "',";
  19037. }
  19038. if (info.depAction === 'scan') {
  19039. deps = parse.getAnonDeps(path, contents.substring(info.defineRange[0], info.defineEndRange[1]));
  19040. if (deps.length) {
  19041. depString = '[' + deps.map(function (dep) {
  19042. return "'" + dep + "'";
  19043. }) + ']';
  19044. } else {
  19045. depString = '[]';
  19046. }
  19047. depString += ',';
  19048. if (info.nameCommaRange) {
  19049. //Already have a named module, need to insert the
  19050. //dependencies after the name.
  19051. contents = contents.substring(0, info.nameCommaRange[1]) +
  19052. depString +
  19053. contents.substring(info.nameCommaRange[1],
  19054. contents.length);
  19055. } else {
  19056. contentInsertion += depString;
  19057. }
  19058. }
  19059. if (contentInsertion) {
  19060. contents = contents.substring(0, info.parenRange[1]) +
  19061. contentInsertion +
  19062. contents.substring(info.parenRange[1],
  19063. contents.length);
  19064. }
  19065. //Do namespace last so that ui does not mess upthe parenRange
  19066. //used above.
  19067. if (namespace && !info.namespaceExists) {
  19068. contents = contents.substring(0, info.defineRange[0]) +
  19069. namespace + '.' +
  19070. contents.substring(info.defineRange[0],
  19071. contents.length);
  19072. }
  19073. //Notify any listener for the found info
  19074. if (onFound) {
  19075. onFound(info);
  19076. }
  19077. });
  19078. if (options.useSourceUrl) {
  19079. contents = 'eval("' + lang.jsEscape(contents) +
  19080. '\\n//@ sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') +
  19081. path +
  19082. '");\n';
  19083. }
  19084. return contents;
  19085. },
  19086. /**
  19087. * Modify the contents of a require.config/requirejs.config call. This
  19088. * call will LOSE any existing comments that are in the config string.
  19089. *
  19090. * @param {String} fileContents String that may contain a config call
  19091. * @param {Function} onConfig Function called when the first config
  19092. * call is found. It will be passed an Object which is the current
  19093. * config, and the onConfig function should return an Object to use
  19094. * as the config.
  19095. * @return {String} the fileContents with the config changes applied.
  19096. */
  19097. modifyConfig: function (fileContents, onConfig) {
  19098. var details = parse.findConfig(fileContents),
  19099. config = details.config;
  19100. if (config) {
  19101. config = onConfig(config);
  19102. if (config) {
  19103. return transform.serializeConfig(config,
  19104. fileContents,
  19105. details.range[0],
  19106. details.range[1]);
  19107. }
  19108. }
  19109. return fileContents;
  19110. },
  19111. serializeConfig: function (config, fileContents, start, end) {
  19112. //Calculate base level of indent
  19113. var indent, match, configString, outDentRegExp,
  19114. baseIndent = '',
  19115. startString = fileContents.substring(0, start),
  19116. existingConfigString = fileContents.substring(start, end),
  19117. lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n',
  19118. lastReturnIndex = startString.lastIndexOf('\n');
  19119. //Get the basic amount of indent for the require config call.
  19120. if (lastReturnIndex === -1) {
  19121. lastReturnIndex = 0;
  19122. }
  19123. match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start));
  19124. if (match && match[1]) {
  19125. baseIndent = match[1];
  19126. }
  19127. //Calculate internal indentation for config
  19128. match = indentRegExp.exec(existingConfigString);
  19129. if (match && match[1]) {
  19130. indent = match[1];
  19131. }
  19132. if (!indent || indent.length < baseIndent) {
  19133. indent = ' ';
  19134. } else {
  19135. indent = indent.substring(baseIndent.length);
  19136. }
  19137. outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g');
  19138. configString = transform.objectToString(config,
  19139. indent,
  19140. lineReturn,
  19141. outDentRegExp);
  19142. //Add in the base indenting level.
  19143. configString = applyIndent(configString, baseIndent, lineReturn);
  19144. return startString + configString + fileContents.substring(end);
  19145. },
  19146. /**
  19147. * Tries converting a JS object to a string. This will likely suck, and
  19148. * is tailored to the type of config expected in a loader config call.
  19149. * So, hasOwnProperty fields, strings, numbers, arrays and functions,
  19150. * no weird recursively referenced stuff.
  19151. * @param {Object} obj the object to convert
  19152. * @param {String} indent the indentation to use for each level
  19153. * @param {String} lineReturn the type of line return to use
  19154. * @param {outDentRegExp} outDentRegExp the regexp to use to outdent functions
  19155. * @param {String} totalIndent the total indent to print for this level
  19156. * @return {String} a string representation of the object.
  19157. */
  19158. objectToString: function (obj, indent, lineReturn, outDentRegExp, totalIndent) {
  19159. var startBrace, endBrace, nextIndent,
  19160. first = true,
  19161. value = '';
  19162. totalIndent = totalIndent || '';
  19163. nextIndent = totalIndent + indent;
  19164. if (obj === null) {
  19165. value = 'null';
  19166. } else if (obj === undefined) {
  19167. value = 'undefined';
  19168. } else if (typeof obj === 'number') {
  19169. value = obj;
  19170. } else if (typeof obj === 'string') {
  19171. //Use double quotes in case the config may also work as JSON.
  19172. value = '"' + lang.jsEscape(obj) + '"';
  19173. } else if (lang.isArray(obj)) {
  19174. lang.each(obj, function (item, i) {
  19175. value += (i !== 0 ? ',' + lineReturn : '' ) +
  19176. nextIndent +
  19177. transform.objectToString(item,
  19178. indent,
  19179. lineReturn,
  19180. outDentRegExp,
  19181. nextIndent);
  19182. });
  19183. startBrace = '[';
  19184. endBrace = ']';
  19185. } else if (lang.isFunction(obj) || lang.isRegExp(obj)) {
  19186. //The outdent regexp just helps pretty up the conversion
  19187. //just in node. Rhino strips comments and does a different
  19188. //indent scheme for Function toString, so not really helpful
  19189. //there.
  19190. value = obj.toString().replace(outDentRegExp, '$1');
  19191. } else {
  19192. //An object
  19193. lang.eachProp(obj, function (v, prop) {
  19194. value += (first ? '': ',' + lineReturn) +
  19195. nextIndent +
  19196. '"' + lang.jsEscape(prop) + '": ' +
  19197. transform.objectToString(v,
  19198. indent,
  19199. lineReturn,
  19200. outDentRegExp,
  19201. nextIndent);
  19202. first = false;
  19203. });
  19204. startBrace = '{';
  19205. endBrace = '}';
  19206. }
  19207. if (startBrace) {
  19208. value = startBrace +
  19209. lineReturn +
  19210. value +
  19211. lineReturn + totalIndent +
  19212. endBrace;
  19213. }
  19214. return value;
  19215. }
  19216. });
  19217. });/**
  19218. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  19219. * Available via the MIT or new BSD license.
  19220. * see: http://github.com/jrburke/requirejs for details
  19221. */
  19222. /*jslint regexp: true, plusplus: true */
  19223. /*global define: false */
  19224. define('pragma', ['parse', 'logger'], function (parse, logger) {
  19225. 'use strict';
  19226. function Temp() {}
  19227. function create(obj, mixin) {
  19228. Temp.prototype = obj;
  19229. var temp = new Temp(), prop;
  19230. //Avoid any extra memory hanging around
  19231. Temp.prototype = null;
  19232. if (mixin) {
  19233. for (prop in mixin) {
  19234. if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) {
  19235. temp[prop] = mixin[prop];
  19236. }
  19237. }
  19238. }
  19239. return temp; // Object
  19240. }
  19241. var pragma = {
  19242. conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/,
  19243. useStrictRegExp: /['"]use strict['"];/g,
  19244. hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
  19245. configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g,
  19246. nsWrapRegExp: /\/\*requirejs namespace: true \*\//,
  19247. apiDefRegExp: /var requirejs, require, define;/,
  19248. defineCheckRegExp: /typeof\s+define\s*===\s*["']function["']\s*&&\s*define\s*\.\s*amd/g,
  19249. defineStringCheckRegExp: /typeof\s+define\s*===\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g,
  19250. defineTypeFirstCheckRegExp: /\s*["']function["']\s*===\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g,
  19251. defineJQueryRegExp: /typeof\s+define\s*===\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g,
  19252. defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g,
  19253. defineTernaryRegExp: /typeof\s+define\s*===\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/,
  19254. amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*'function'\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g,
  19255. removeStrict: function (contents, config) {
  19256. return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '');
  19257. },
  19258. namespace: function (fileContents, ns, onLifecycleName) {
  19259. if (ns) {
  19260. //Namespace require/define calls
  19261. fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3(');
  19262. fileContents = parse.renameNamespace(fileContents, ns);
  19263. //Namespace define ternary use:
  19264. fileContents = fileContents.replace(pragma.defineTernaryRegExp,
  19265. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define");
  19266. //Namespace define jquery use:
  19267. fileContents = fileContents.replace(pragma.defineJQueryRegExp,
  19268. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery");
  19269. //Namespace has.js define use:
  19270. fileContents = fileContents.replace(pragma.defineHasRegExp,
  19271. "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd");
  19272. //Namespace define checks.
  19273. //Do these ones last, since they are a subset of the more specific
  19274. //checks above.
  19275. fileContents = fileContents.replace(pragma.defineCheckRegExp,
  19276. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd");
  19277. fileContents = fileContents.replace(pragma.defineStringCheckRegExp,
  19278. "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']");
  19279. fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp,
  19280. "'function' === typeof " + ns + ".define && " + ns + ".define.amd");
  19281. //Check for require.js with the require/define definitions
  19282. if (pragma.apiDefRegExp.test(fileContents) &&
  19283. fileContents.indexOf("if (typeof " + ns + " === 'undefined')") === -1) {
  19284. //Wrap the file contents in a typeof check, and a function
  19285. //to contain the API globals.
  19286. fileContents = "var " + ns + ";(function () { if (typeof " +
  19287. ns + " === 'undefined') {\n" +
  19288. ns + ' = {};\n' +
  19289. fileContents +
  19290. "\n" +
  19291. ns + ".requirejs = requirejs;" +
  19292. ns + ".require = require;" +
  19293. ns + ".define = define;\n" +
  19294. "}\n}());";
  19295. }
  19296. //Finally, if the file wants a special wrapper because it ties
  19297. //in to the requirejs internals in a way that would not fit
  19298. //the above matches, do that. Look for /*requirejs namespace: true*/
  19299. if (pragma.nsWrapRegExp.test(fileContents)) {
  19300. //Remove the pragma.
  19301. fileContents = fileContents.replace(pragma.nsWrapRegExp, '');
  19302. //Alter the contents.
  19303. fileContents = '(function () {\n' +
  19304. 'var require = ' + ns + '.require,' +
  19305. 'requirejs = ' + ns + '.requirejs,' +
  19306. 'define = ' + ns + '.define;\n' +
  19307. fileContents +
  19308. '\n}());';
  19309. }
  19310. }
  19311. return fileContents;
  19312. },
  19313. /**
  19314. * processes the fileContents for some //>> conditional statements
  19315. */
  19316. process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) {
  19317. /*jslint evil: true */
  19318. var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,
  19319. matches, type, marker, condition, isTrue, endRegExp, endMatches,
  19320. endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,
  19321. i, dep, moduleName, collectorMod,
  19322. lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,
  19323. //Legacy arg defined to help in dojo conversion script. Remove later
  19324. //when dojo no longer needs conversion:
  19325. kwArgs = pragmas;
  19326. //Mix in a specific lifecycle scoped object, to allow targeting
  19327. //some pragmas/has tests to only when files are saved, or at different
  19328. //lifecycle events. Do not bother with kwArgs in this section, since
  19329. //the old dojo kwArgs were for all points in the build lifecycle.
  19330. if (onLifecycleName) {
  19331. lifecyclePragmas = config['pragmas' + onLifecycleName];
  19332. lifecycleHas = config['has' + onLifecycleName];
  19333. if (lifecyclePragmas) {
  19334. pragmas = create(pragmas || {}, lifecyclePragmas);
  19335. }
  19336. if (lifecycleHas) {
  19337. hasConfig = create(hasConfig || {}, lifecycleHas);
  19338. }
  19339. }
  19340. //Replace has references if desired
  19341. if (hasConfig) {
  19342. fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {
  19343. if (hasConfig.hasOwnProperty(test)) {
  19344. return !!hasConfig[test];
  19345. }
  19346. return match;
  19347. });
  19348. }
  19349. if (!config.skipPragmas) {
  19350. while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) {
  19351. //Found a conditional. Get the conditional line.
  19352. lineEndIndex = fileContents.indexOf("\n", foundIndex);
  19353. if (lineEndIndex === -1) {
  19354. lineEndIndex = fileContents.length - 1;
  19355. }
  19356. //Increment startIndex past the line so the next conditional search can be done.
  19357. startIndex = lineEndIndex + 1;
  19358. //Break apart the conditional.
  19359. conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);
  19360. matches = conditionLine.match(pragma.conditionalRegExp);
  19361. if (matches) {
  19362. type = matches[1];
  19363. marker = matches[2];
  19364. condition = matches[3];
  19365. isTrue = false;
  19366. //See if the condition is true.
  19367. try {
  19368. isTrue = !!eval("(" + condition + ")");
  19369. } catch (e) {
  19370. throw "Error in file: " +
  19371. fileName +
  19372. ". Conditional comment: " +
  19373. conditionLine +
  19374. " failed with this error: " + e;
  19375. }
  19376. //Find the endpoint marker.
  19377. endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g");
  19378. endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));
  19379. if (endMatches) {
  19380. endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;
  19381. //Find the next line return based on the match position.
  19382. lineEndIndex = fileContents.indexOf("\n", endMarkerIndex);
  19383. if (lineEndIndex === -1) {
  19384. lineEndIndex = fileContents.length - 1;
  19385. }
  19386. //Should we include the segment?
  19387. shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue));
  19388. //Remove the conditional comments, and optionally remove the content inside
  19389. //the conditional comments.
  19390. startLength = startIndex - foundIndex;
  19391. fileContents = fileContents.substring(0, foundIndex) +
  19392. (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") +
  19393. fileContents.substring(lineEndIndex + 1, fileContents.length);
  19394. //Move startIndex to foundIndex, since that is the new position in the file
  19395. //where we need to look for more conditionals in the next while loop pass.
  19396. startIndex = foundIndex;
  19397. } else {
  19398. throw "Error in file: " +
  19399. fileName +
  19400. ". Cannot find end marker for conditional comment: " +
  19401. conditionLine;
  19402. }
  19403. }
  19404. }
  19405. }
  19406. //If need to find all plugin resources to optimize, do that now,
  19407. //before namespacing, since the namespacing will change the API
  19408. //names.
  19409. //If there is a plugin collector, scan the file for plugin resources.
  19410. if (config.optimizeAllPluginResources && pluginCollector) {
  19411. try {
  19412. deps = parse.findDependencies(fileName, fileContents);
  19413. if (deps.length) {
  19414. for (i = 0; i < deps.length; i++) {
  19415. dep = deps[i];
  19416. if (dep.indexOf('!') !== -1) {
  19417. moduleName = dep.split('!')[0];
  19418. collectorMod = pluginCollector[moduleName];
  19419. if (!collectorMod) {
  19420. collectorMod = pluginCollector[moduleName] = [];
  19421. }
  19422. collectorMod.push(dep);
  19423. }
  19424. }
  19425. }
  19426. } catch (eDep) {
  19427. logger.error('Parse error looking for plugin resources in ' +
  19428. fileName + ', skipping.');
  19429. }
  19430. }
  19431. //Strip amdefine use for node-shared modules.
  19432. fileContents = fileContents.replace(pragma.amdefineRegExp, '');
  19433. //Do namespacing
  19434. if (onLifecycleName === 'OnSave' && config.namespace) {
  19435. fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);
  19436. }
  19437. return pragma.removeStrict(fileContents, config);
  19438. }
  19439. };
  19440. return pragma;
  19441. });
  19442. if(env === 'browser') {
  19443. /**
  19444. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  19445. * Available via the MIT or new BSD license.
  19446. * see: http://github.com/jrburke/requirejs for details
  19447. */
  19448. /*jslint strict: false */
  19449. /*global define: false */
  19450. define('browser/optimize', {});
  19451. }
  19452. if(env === 'node') {
  19453. /**
  19454. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  19455. * Available via the MIT or new BSD license.
  19456. * see: http://github.com/jrburke/requirejs for details
  19457. */
  19458. /*jslint strict: false */
  19459. /*global define: false */
  19460. define('node/optimize', {});
  19461. }
  19462. if(env === 'rhino') {
  19463. /**
  19464. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  19465. * Available via the MIT or new BSD license.
  19466. * see: http://github.com/jrburke/requirejs for details
  19467. */
  19468. /*jslint sloppy: true, plusplus: true */
  19469. /*global define, java, Packages, com */
  19470. define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) {
  19471. //Add .reduce to Rhino so UglifyJS can run in Rhino,
  19472. //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
  19473. //but rewritten for brevity, and to be good enough for use by UglifyJS.
  19474. if (!Array.prototype.reduce) {
  19475. Array.prototype.reduce = function (fn /*, initialValue */) {
  19476. var i = 0,
  19477. length = this.length,
  19478. accumulator;
  19479. if (arguments.length >= 2) {
  19480. accumulator = arguments[1];
  19481. } else {
  19482. if (length) {
  19483. while (!(i in this)) {
  19484. i++;
  19485. }
  19486. accumulator = this[i++];
  19487. }
  19488. }
  19489. for (; i < length; i++) {
  19490. if (i in this) {
  19491. accumulator = fn.call(undefined, accumulator, this[i], i, this);
  19492. }
  19493. }
  19494. return accumulator;
  19495. };
  19496. }
  19497. var JSSourceFilefromCode, optimize,
  19498. mapRegExp = /"file":"[^"]+"/;
  19499. //Bind to Closure compiler, but if it is not available, do not sweat it.
  19500. try {
  19501. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  19502. } catch (e) {}
  19503. //Helper for closure compiler, because of weird Java-JavaScript interactions.
  19504. function closurefromCode(filename, content) {
  19505. return JSSourceFilefromCode.invoke(null, [filename, content]);
  19506. }
  19507. function getFileWriter(fileName, encoding) {
  19508. var outFile = new java.io.File(fileName), outWriter, parentDir;
  19509. parentDir = outFile.getAbsoluteFile().getParentFile();
  19510. if (!parentDir.exists()) {
  19511. if (!parentDir.mkdirs()) {
  19512. throw "Could not create directory: " + parentDir.getAbsolutePath();
  19513. }
  19514. }
  19515. if (encoding) {
  19516. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  19517. } else {
  19518. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  19519. }
  19520. return new java.io.BufferedWriter(outWriter);
  19521. }
  19522. optimize = {
  19523. closure: function (fileName, fileContents, outFileName, keepLines, config) {
  19524. config = config || {};
  19525. var result, mappings, optimized, compressed, baseName, writer,
  19526. outBaseName, outFileNameMap, outFileNameMapContent,
  19527. jscomp = Packages.com.google.javascript.jscomp,
  19528. flags = Packages.com.google.common.flags,
  19529. //Fake extern
  19530. externSourceFile = closurefromCode("fakeextern.js", " "),
  19531. //Set up source input
  19532. jsSourceFile = closurefromCode(String(fileName), String(fileContents)),
  19533. options, option, FLAG_compilation_level, compiler,
  19534. Compiler = Packages.com.google.javascript.jscomp.Compiler;
  19535. logger.trace("Minifying file: " + fileName);
  19536. baseName = (new java.io.File(fileName)).getName();
  19537. //Set up options
  19538. options = new jscomp.CompilerOptions();
  19539. for (option in config.CompilerOptions) {
  19540. // options are false by default and jslint wanted an if statement in this for loop
  19541. if (config.CompilerOptions[option]) {
  19542. options[option] = config.CompilerOptions[option];
  19543. }
  19544. }
  19545. options.prettyPrint = keepLines || options.prettyPrint;
  19546. FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];
  19547. FLAG_compilation_level.setOptionsForCompilationLevel(options);
  19548. if (config.generateSourceMaps) {
  19549. mappings = new java.util.ArrayList();
  19550. mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src"));
  19551. options.setSourceMapLocationMappings(mappings);
  19552. options.setSourceMapOutputPath(fileName + ".map");
  19553. }
  19554. //Trigger the compiler
  19555. Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);
  19556. compiler = new Compiler();
  19557. result = compiler.compile(externSourceFile, jsSourceFile, options);
  19558. if (result.success) {
  19559. optimized = String(compiler.toSource());
  19560. if (config.generateSourceMaps && result.sourceMap && outFileName) {
  19561. outBaseName = (new java.io.File(outFileName)).getName();
  19562. file.saveUtf8File(outFileName + ".src", fileContents);
  19563. outFileNameMap = outFileName + ".map";
  19564. writer = getFileWriter(outFileNameMap, "utf-8");
  19565. result.sourceMap.appendTo(writer, outFileName);
  19566. writer.close();
  19567. //Not sure how better to do this, but right now the .map file
  19568. //leaks the full OS path in the "file" property. Manually
  19569. //modify it to not do that.
  19570. file.saveFile(outFileNameMap,
  19571. file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"'));
  19572. fileContents = optimized + "\n//@ sourceMappingURL=" + outBaseName + ".map";
  19573. } else {
  19574. fileContents = optimized;
  19575. }
  19576. return fileContents;
  19577. } else {
  19578. throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');
  19579. }
  19580. return fileContents;
  19581. }
  19582. };
  19583. return optimize;
  19584. });
  19585. }
  19586. if(env === 'xpconnect') {
  19587. define('xpconnect/optimize', {});
  19588. }
  19589. /**
  19590. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  19591. * Available via the MIT or new BSD license.
  19592. * see: http://github.com/jrburke/requirejs for details
  19593. */
  19594. /*jslint plusplus: true, nomen: true, regexp: true */
  19595. /*global define: false */
  19596. define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',
  19597. 'pragma', 'uglifyjs/index', 'uglifyjs2'],
  19598. function (lang, logger, envOptimize, file, parse,
  19599. pragma, uglify, uglify2) {
  19600. 'use strict';
  19601. var optimize,
  19602. cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig,
  19603. cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g,
  19604. cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g;
  19605. /**
  19606. * If an URL from a CSS url value contains start/end quotes, remove them.
  19607. * This is not done in the regexp, since my regexp fu is not that strong,
  19608. * and the CSS spec allows for ' and " in the URL if they are backslash escaped.
  19609. * @param {String} url
  19610. */
  19611. function cleanCssUrlQuotes(url) {
  19612. //Make sure we are not ending in whitespace.
  19613. //Not very confident of the css regexps above that there will not be ending
  19614. //whitespace.
  19615. url = url.replace(/\s+$/, "");
  19616. if (url.charAt(0) === "'" || url.charAt(0) === "\"") {
  19617. url = url.substring(1, url.length - 1);
  19618. }
  19619. return url;
  19620. }
  19621. /**
  19622. * Inlines nested stylesheets that have @import calls in them.
  19623. * @param {String} fileName the file name
  19624. * @param {String} fileContents the file contents
  19625. * @param {String} cssImportIgnore comma delimited string of files to ignore
  19626. * @param {String} cssPrefix string to be prefixed before relative URLs
  19627. * @param {Object} included an object used to track the files already imported
  19628. */
  19629. function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included) {
  19630. //Find the last slash in the name.
  19631. fileName = fileName.replace(lang.backSlashRegExp, "/");
  19632. var endIndex = fileName.lastIndexOf("/"),
  19633. //Make a file path based on the last slash.
  19634. //If no slash, so must be just a file name. Use empty string then.
  19635. filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "",
  19636. //store a list of merged files
  19637. importList = [],
  19638. skippedList = [];
  19639. //First make a pass by removing an commented out @import calls.
  19640. fileContents = fileContents.replace(cssCommentImportRegExp, '');
  19641. //Make sure we have a delimited ignore list to make matching faster
  19642. if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {
  19643. cssImportIgnore += ",";
  19644. }
  19645. fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {
  19646. //Only process media type "all" or empty media type rules.
  19647. if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {
  19648. skippedList.push(fileName);
  19649. return fullMatch;
  19650. }
  19651. importFileName = cleanCssUrlQuotes(importFileName);
  19652. //Ignore the file import if it is part of an ignore list.
  19653. if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {
  19654. return fullMatch;
  19655. }
  19656. //Make sure we have a unix path for the rest of the operation.
  19657. importFileName = importFileName.replace(lang.backSlashRegExp, "/");
  19658. try {
  19659. //if a relative path, then tack on the filePath.
  19660. //If it is not a relative path, then the readFile below will fail,
  19661. //and we will just skip that import.
  19662. var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,
  19663. importContents = file.readFile(fullImportFileName), i,
  19664. importEndIndex, importPath, fixedUrlMatch, colonIndex, parts, flat;
  19665. //Skip the file if it has already been included.
  19666. if (included[fullImportFileName]) {
  19667. return '';
  19668. }
  19669. included[fullImportFileName] = true;
  19670. //Make sure to flatten any nested imports.
  19671. flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);
  19672. importContents = flat.fileContents;
  19673. if (flat.importList.length) {
  19674. importList.push.apply(importList, flat.importList);
  19675. }
  19676. if (flat.skippedList.length) {
  19677. skippedList.push.apply(skippedList, flat.skippedList);
  19678. }
  19679. //Make the full import path
  19680. importEndIndex = importFileName.lastIndexOf("/");
  19681. //Make a file path based on the last slash.
  19682. //If no slash, so must be just a file name. Use empty string then.
  19683. importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";
  19684. //fix url() on relative import (#5)
  19685. importPath = importPath.replace(/^\.\//, '');
  19686. //Modify URL paths to match the path represented by this file.
  19687. importContents = importContents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {
  19688. fixedUrlMatch = cleanCssUrlQuotes(urlMatch);
  19689. fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");
  19690. //Only do the work for relative URLs. Skip things that start with / or have
  19691. //a protocol.
  19692. colonIndex = fixedUrlMatch.indexOf(":");
  19693. if (fixedUrlMatch.charAt(0) !== "/" && (colonIndex === -1 || colonIndex > fixedUrlMatch.indexOf("/"))) {
  19694. //It is a relative URL, tack on the cssPrefix and path prefix
  19695. urlMatch = cssPrefix + importPath + fixedUrlMatch;
  19696. } else {
  19697. logger.trace(importFileName + "\n URL not a relative URL, skipping: " + urlMatch);
  19698. }
  19699. //Collapse .. and .
  19700. parts = urlMatch.split("/");
  19701. for (i = parts.length - 1; i > 0; i--) {
  19702. if (parts[i] === ".") {
  19703. parts.splice(i, 1);
  19704. } else if (parts[i] === "..") {
  19705. if (i !== 0 && parts[i - 1] !== "..") {
  19706. parts.splice(i - 1, 2);
  19707. i -= 1;
  19708. }
  19709. }
  19710. }
  19711. return "url(" + parts.join("/") + ")";
  19712. });
  19713. importList.push(fullImportFileName);
  19714. return importContents;
  19715. } catch (e) {
  19716. logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName);
  19717. return fullMatch;
  19718. }
  19719. });
  19720. return {
  19721. importList : importList,
  19722. skippedList: skippedList,
  19723. fileContents : fileContents
  19724. };
  19725. }
  19726. optimize = {
  19727. /**
  19728. * Optimizes a file that contains JavaScript content. Optionally collects
  19729. * plugin resources mentioned in a file, and then passes the content
  19730. * through an minifier if one is specified via config.optimize.
  19731. *
  19732. * @param {String} fileName the name of the file to optimize
  19733. * @param {String} fileContents the contents to optimize. If this is
  19734. * a null value, then fileName will be used to read the fileContents.
  19735. * @param {String} outFileName the name of the file to use for the
  19736. * saved optimized content.
  19737. * @param {Object} config the build config object.
  19738. * @param {Array} [pluginCollector] storage for any plugin resources
  19739. * found.
  19740. */
  19741. jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {
  19742. if (!fileContents) {
  19743. fileContents = file.readFile(fileName);
  19744. }
  19745. fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);
  19746. file.saveUtf8File(outFileName, fileContents);
  19747. },
  19748. /**
  19749. * Optimizes a file that contains JavaScript content. Optionally collects
  19750. * plugin resources mentioned in a file, and then passes the content
  19751. * through an minifier if one is specified via config.optimize.
  19752. *
  19753. * @param {String} fileName the name of the file that matches the
  19754. * fileContents.
  19755. * @param {String} fileContents the string of JS to optimize.
  19756. * @param {Object} [config] the build config object.
  19757. * @param {Array} [pluginCollector] storage for any plugin resources
  19758. * found.
  19759. */
  19760. js: function (fileName, fileContents, outFileName, config, pluginCollector) {
  19761. var optFunc, optConfig,
  19762. parts = (String(config.optimize)).split('.'),
  19763. optimizerName = parts[0],
  19764. keepLines = parts[1] === 'keepLines',
  19765. licenseContents = '';
  19766. config = config || {};
  19767. //Apply pragmas/namespace renaming
  19768. fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);
  19769. //Optimize the JS files if asked.
  19770. if (optimizerName && optimizerName !== 'none') {
  19771. optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];
  19772. if (!optFunc) {
  19773. throw new Error('optimizer with name of "' +
  19774. optimizerName +
  19775. '" not found for this environment');
  19776. }
  19777. optConfig = config[optimizerName] || {};
  19778. if (config.generateSourceMaps) {
  19779. optConfig.generateSourceMaps = !!config.generateSourceMaps;
  19780. }
  19781. try {
  19782. if (config.preserveLicenseComments) {
  19783. //Pull out any license comments for prepending after optimization.
  19784. try {
  19785. licenseContents = parse.getLicenseComments(fileName, fileContents);
  19786. } catch (e) {
  19787. throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString());
  19788. }
  19789. }
  19790. fileContents = licenseContents + optFunc(fileName,
  19791. fileContents,
  19792. outFileName,
  19793. keepLines,
  19794. optConfig);
  19795. } catch (e) {
  19796. if (config.throwWhen && config.throwWhen.optimize) {
  19797. throw e;
  19798. } else {
  19799. logger.error(e);
  19800. }
  19801. }
  19802. }
  19803. return fileContents;
  19804. },
  19805. /**
  19806. * Optimizes one CSS file, inlining @import calls, stripping comments, and
  19807. * optionally removes line returns.
  19808. * @param {String} fileName the path to the CSS file to optimize
  19809. * @param {String} outFileName the path to save the optimized file.
  19810. * @param {Object} config the config object with the optimizeCss and
  19811. * cssImportIgnore options.
  19812. */
  19813. cssFile: function (fileName, outFileName, config) {
  19814. //Read in the file. Make sure we have a JS string.
  19815. var originalFileContents = file.readFile(fileName),
  19816. flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}),
  19817. //Do not use the flattened CSS if there was one that was skipped.
  19818. fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,
  19819. startIndex, endIndex, buildText, comment;
  19820. if (flat.skippedList.length) {
  19821. logger.warn('Cannot inline @imports for ' + fileName +
  19822. ',\nthe following files had media queries in them:\n' +
  19823. flat.skippedList.join('\n'));
  19824. }
  19825. //Do comment removal.
  19826. try {
  19827. if (config.optimizeCss.indexOf(".keepComments") === -1) {
  19828. startIndex = 0;
  19829. //Get rid of comments.
  19830. while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) {
  19831. endIndex = fileContents.indexOf("*/", startIndex + 2);
  19832. if (endIndex === -1) {
  19833. throw "Improper comment in CSS file: " + fileName;
  19834. }
  19835. comment = fileContents.substring(startIndex, endIndex);
  19836. if (config.preserveLicenseComments &&
  19837. (comment.indexOf('license') !== -1 ||
  19838. comment.indexOf('opyright') !== -1 ||
  19839. comment.indexOf('(c)') !== -1)) {
  19840. //Keep the comment, just increment the startIndex
  19841. startIndex = endIndex;
  19842. } else {
  19843. fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);
  19844. startIndex = 0;
  19845. }
  19846. }
  19847. }
  19848. //Get rid of newlines.
  19849. if (config.optimizeCss.indexOf(".keepLines") === -1) {
  19850. fileContents = fileContents.replace(/[\r\n]/g, "");
  19851. fileContents = fileContents.replace(/\s+/g, " ");
  19852. fileContents = fileContents.replace(/\{\s/g, "{");
  19853. fileContents = fileContents.replace(/\s\}/g, "}");
  19854. } else {
  19855. //Remove multiple empty lines.
  19856. fileContents = fileContents.replace(/(\r\n)+/g, "\r\n");
  19857. fileContents = fileContents.replace(/(\n)+/g, "\n");
  19858. }
  19859. } catch (e) {
  19860. fileContents = originalFileContents;
  19861. logger.error("Could not optimized CSS file: " + fileName + ", error: " + e);
  19862. }
  19863. file.saveUtf8File(outFileName, fileContents);
  19864. //text output to stdout and/or written to build.txt file
  19865. buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n";
  19866. flat.importList.push(fileName);
  19867. buildText += flat.importList.map(function(path){
  19868. return path.replace(config.dir, "");
  19869. }).join("\n");
  19870. return {
  19871. importList: flat.importList,
  19872. buildText: buildText +"\n"
  19873. };
  19874. },
  19875. /**
  19876. * Optimizes CSS files, inlining @import calls, stripping comments, and
  19877. * optionally removes line returns.
  19878. * @param {String} startDir the path to the top level directory
  19879. * @param {Object} config the config object with the optimizeCss and
  19880. * cssImportIgnore options.
  19881. */
  19882. css: function (startDir, config) {
  19883. var buildText = "",
  19884. importList = [],
  19885. shouldRemove = config.dir && config.removeCombined,
  19886. i, fileName, result, fileList;
  19887. if (config.optimizeCss.indexOf("standard") !== -1) {
  19888. fileList = file.getFilteredFileList(startDir, /\.css$/, true);
  19889. if (fileList) {
  19890. for (i = 0; i < fileList.length; i++) {
  19891. fileName = fileList[i];
  19892. logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName);
  19893. result = optimize.cssFile(fileName, fileName, config);
  19894. buildText += result.buildText;
  19895. if (shouldRemove) {
  19896. result.importList.pop();
  19897. importList = importList.concat(result.importList);
  19898. }
  19899. }
  19900. }
  19901. if (shouldRemove) {
  19902. importList.forEach(function (path) {
  19903. if (file.exists(path)) {
  19904. file.deleteFile(path);
  19905. }
  19906. });
  19907. }
  19908. }
  19909. return buildText;
  19910. },
  19911. optimizers: {
  19912. uglify: function (fileName, fileContents, outFileName, keepLines, config) {
  19913. var parser = uglify.parser,
  19914. processor = uglify.uglify,
  19915. ast, errMessage, errMatch;
  19916. config = config || {};
  19917. logger.trace("Uglifying file: " + fileName);
  19918. try {
  19919. ast = parser.parse(fileContents, config.strict_semicolons);
  19920. if (config.no_mangle !== true) {
  19921. ast = processor.ast_mangle(ast, config);
  19922. }
  19923. ast = processor.ast_squeeze(ast, config);
  19924. fileContents = processor.gen_code(ast, config);
  19925. if (config.max_line_length) {
  19926. fileContents = processor.split_lines(fileContents, config.max_line_length);
  19927. }
  19928. //Add trailing semicolon to match uglifyjs command line version
  19929. fileContents += ';';
  19930. } catch (e) {
  19931. errMessage = e.toString();
  19932. errMatch = /\nError(\r)?\n/.exec(errMessage);
  19933. if (errMatch) {
  19934. errMessage = errMessage.substring(0, errMatch.index);
  19935. }
  19936. throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + errMessage);
  19937. }
  19938. return fileContents;
  19939. },
  19940. uglify2: function (fileName, fileContents, outFileName, keepLines, config) {
  19941. var result,
  19942. uconfig = {},
  19943. baseName = fileName && fileName.split('/').pop();
  19944. config = config || {};
  19945. lang.mixin(uconfig, config, true);
  19946. uconfig.fromString = true;
  19947. if (config.generateSourceMaps && outFileName) {
  19948. uconfig.outSourceMap = baseName;
  19949. }
  19950. logger.trace("Uglify2 file: " + fileName);
  19951. try {
  19952. result = uglify2.minify(fileContents, uconfig, baseName + '.src');
  19953. if (uconfig.outSourceMap && result.map) {
  19954. file.saveFile(outFileName + '.src', fileContents);
  19955. file.saveFile(outFileName + '.map', result.map);
  19956. fileContents = result.code + "\n//@ sourceMappingURL=" + baseName + ".map";
  19957. } else {
  19958. fileContents = result.code;
  19959. }
  19960. } catch (e) {
  19961. throw new Error('Cannot uglify2 file: ' + fileName + '. Skipping it. Error is:\n' + e.toString());
  19962. }
  19963. return fileContents;
  19964. }
  19965. }
  19966. };
  19967. return optimize;
  19968. });
  19969. /**
  19970. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  19971. * Available via the MIT or new BSD license.
  19972. * see: http://github.com/jrburke/requirejs for details
  19973. */
  19974. /*
  19975. * This file patches require.js to communicate with the build system.
  19976. */
  19977. //Using sloppy since this uses eval for some code like plugins,
  19978. //which may not be strict mode compliant. So if use strict is used
  19979. //below they will have strict rules applied and may cause an error.
  19980. /*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */
  19981. /*global require, define: true */
  19982. //NOT asking for require as a dependency since the goal is to modify the
  19983. //global require below
  19984. define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function (
  19985. file,
  19986. pragma,
  19987. parse,
  19988. lang,
  19989. logger,
  19990. commonJs,
  19991. prim
  19992. ) {
  19993. var allowRun = true,
  19994. hasProp = lang.hasProp,
  19995. falseProp = lang.falseProp,
  19996. getOwn = lang.getOwn;
  19997. //This method should be called when the patches to require should take hold.
  19998. return function () {
  19999. if (!allowRun) {
  20000. return;
  20001. }
  20002. allowRun = false;
  20003. var layer,
  20004. pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/,
  20005. oldNewContext = require.s.newContext,
  20006. oldDef,
  20007. //create local undefined values for module and exports,
  20008. //so that when files are evaled in this function they do not
  20009. //see the node values used for r.js
  20010. exports,
  20011. module;
  20012. /**
  20013. * Reset "global" build caches that are kept around between
  20014. * build layer builds. Useful to do when there are multiple
  20015. * top level requirejs.optimize() calls.
  20016. */
  20017. require._cacheReset = function () {
  20018. //Stored raw text caches, used by browser use.
  20019. require._cachedRawText = {};
  20020. //Stored cached file contents for reuse in other layers.
  20021. require._cachedFileContents = {};
  20022. //Store which cached files contain a require definition.
  20023. require._cachedDefinesRequireUrls = {};
  20024. };
  20025. require._cacheReset();
  20026. /**
  20027. * Makes sure the URL is something that can be supported by the
  20028. * optimization tool.
  20029. * @param {String} url
  20030. * @returns {Boolean}
  20031. */
  20032. require._isSupportedBuildUrl = function (url) {
  20033. //Ignore URLs with protocols, hosts or question marks, means either network
  20034. //access is needed to fetch it or it is too dynamic. Note that
  20035. //on Windows, full paths are used for some urls, which include
  20036. //the drive, like c:/something, so need to test for something other
  20037. //than just a colon.
  20038. if (url.indexOf("://") === -1 && url.indexOf("?") === -1 &&
  20039. url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) {
  20040. return true;
  20041. } else {
  20042. if (!layer.ignoredUrls[url]) {
  20043. if (url.indexOf('empty:') === -1) {
  20044. logger.info('Cannot optimize network URL, skipping: ' + url);
  20045. }
  20046. layer.ignoredUrls[url] = true;
  20047. }
  20048. return false;
  20049. }
  20050. };
  20051. function normalizeUrlWithBase(context, moduleName, url) {
  20052. //Adjust the URL if it was not transformed to use baseUrl.
  20053. if (require.jsExtRegExp.test(moduleName)) {
  20054. url = (context.config.dir || context.config.dirBaseUrl) + url;
  20055. }
  20056. return url;
  20057. }
  20058. //Overrides the new context call to add existing tracking features.
  20059. require.s.newContext = function (name) {
  20060. var context = oldNewContext(name),
  20061. oldEnable = context.enable,
  20062. moduleProto = context.Module.prototype,
  20063. oldInit = moduleProto.init,
  20064. oldCallPlugin = moduleProto.callPlugin;
  20065. //Only do this for the context used for building.
  20066. if (name === '_') {
  20067. //For build contexts, do everything sync
  20068. context.nextTick = function (fn) {
  20069. fn();
  20070. };
  20071. context.needFullExec = {};
  20072. context.fullExec = {};
  20073. context.plugins = {};
  20074. context.buildShimExports = {};
  20075. //Override the shim exports function generator to just
  20076. //spit out strings that can be used in the stringified
  20077. //build output.
  20078. context.makeShimExports = function (value) {
  20079. function fn() {
  20080. return '(function (global) {\n' +
  20081. ' return function () {\n' +
  20082. ' var ret, fn;\n' +
  20083. (value.init ?
  20084. (' fn = ' + value.init.toString() + ';\n' +
  20085. ' ret = fn.apply(global, arguments);\n') : '') +
  20086. (value.exports ?
  20087. ' return ret || global.' + value.exports + ';\n' :
  20088. ' return ret;\n') +
  20089. ' };\n' +
  20090. '}(this))';
  20091. }
  20092. return fn;
  20093. };
  20094. context.enable = function (depMap, parent) {
  20095. var id = depMap.id,
  20096. parentId = parent && parent.map.id,
  20097. needFullExec = context.needFullExec,
  20098. fullExec = context.fullExec,
  20099. mod = getOwn(context.registry, id);
  20100. if (mod && !mod.defined) {
  20101. if (parentId && getOwn(needFullExec, parentId)) {
  20102. needFullExec[id] = true;
  20103. }
  20104. } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) ||
  20105. (parentId && getOwn(needFullExec, parentId) &&
  20106. falseProp(fullExec, id))) {
  20107. context.require.undef(id);
  20108. }
  20109. return oldEnable.apply(context, arguments);
  20110. };
  20111. //Override load so that the file paths can be collected.
  20112. context.load = function (moduleName, url) {
  20113. /*jslint evil: true */
  20114. var contents, pluginBuilderMatch, builderName,
  20115. shim, shimExports;
  20116. //Do not mark the url as fetched if it is
  20117. //not an empty: URL, used by the optimizer.
  20118. //In that case we need to be sure to call
  20119. //load() for each module that is mapped to
  20120. //empty: so that dependencies are satisfied
  20121. //correctly.
  20122. if (url.indexOf('empty:') === 0) {
  20123. delete context.urlFetched[url];
  20124. }
  20125. //Only handle urls that can be inlined, so that means avoiding some
  20126. //URLs like ones that require network access or may be too dynamic,
  20127. //like JSONP
  20128. if (require._isSupportedBuildUrl(url)) {
  20129. //Adjust the URL if it was not transformed to use baseUrl.
  20130. url = normalizeUrlWithBase(context, moduleName, url);
  20131. //Save the module name to path and path to module name mappings.
  20132. layer.buildPathMap[moduleName] = url;
  20133. layer.buildFileToModule[url] = moduleName;
  20134. if (hasProp(context.plugins, moduleName)) {
  20135. //plugins need to have their source evaled as-is.
  20136. context.needFullExec[moduleName] = true;
  20137. }
  20138. prim().start(function () {
  20139. if (hasProp(require._cachedFileContents, url) &&
  20140. (falseProp(context.needFullExec, moduleName) ||
  20141. getOwn(context.fullExec, moduleName))) {
  20142. contents = require._cachedFileContents[url];
  20143. //If it defines require, mark it so it can be hoisted.
  20144. //Done here and in the else below, before the
  20145. //else block removes code from the contents.
  20146. //Related to #263
  20147. if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) {
  20148. layer.existingRequireUrl = url;
  20149. }
  20150. } else {
  20151. //Load the file contents, process for conditionals, then
  20152. //evaluate it.
  20153. return require._cacheReadAsync(url).then(function (text) {
  20154. contents = text;
  20155. if (context.config.cjsTranslate) {
  20156. contents = commonJs.convert(url, contents);
  20157. }
  20158. //If there is a read filter, run it now.
  20159. if (context.config.onBuildRead) {
  20160. contents = context.config.onBuildRead(moduleName, url, contents);
  20161. }
  20162. contents = pragma.process(url, contents, context.config, 'OnExecute');
  20163. //Find out if the file contains a require() definition. Need to know
  20164. //this so we can inject plugins right after it, but before they are needed,
  20165. //and to make sure this file is first, so that define calls work.
  20166. try {
  20167. if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) {
  20168. layer.existingRequireUrl = url;
  20169. require._cachedDefinesRequireUrls[url] = true;
  20170. }
  20171. } catch (e1) {
  20172. throw new Error('Parse error using esprima ' +
  20173. 'for file: ' + url + '\n' + e1);
  20174. }
  20175. }).then(function () {
  20176. if (hasProp(context.plugins, moduleName)) {
  20177. //This is a loader plugin, check to see if it has a build extension,
  20178. //otherwise the plugin will act as the plugin builder too.
  20179. pluginBuilderMatch = pluginBuilderRegExp.exec(contents);
  20180. if (pluginBuilderMatch) {
  20181. //Load the plugin builder for the plugin contents.
  20182. builderName = context.makeModuleMap(pluginBuilderMatch[3],
  20183. context.makeModuleMap(moduleName),
  20184. null,
  20185. true).id;
  20186. return require._cacheReadAsync(context.nameToUrl(builderName));
  20187. }
  20188. }
  20189. return contents;
  20190. }).then(function (text) {
  20191. contents = text;
  20192. //Parse out the require and define calls.
  20193. //Do this even for plugins in case they have their own
  20194. //dependencies that may be separate to how the pluginBuilder works.
  20195. try {
  20196. if (falseProp(context.needFullExec, moduleName)) {
  20197. contents = parse(moduleName, url, contents, {
  20198. insertNeedsDefine: true,
  20199. has: context.config.has,
  20200. findNestedDependencies: context.config.findNestedDependencies
  20201. });
  20202. }
  20203. } catch (e2) {
  20204. throw new Error('Parse error using esprima ' +
  20205. 'for file: ' + url + '\n' + e2);
  20206. }
  20207. require._cachedFileContents[url] = contents;
  20208. });
  20209. }
  20210. }).then(function () {
  20211. if (contents) {
  20212. eval(contents);
  20213. }
  20214. try {
  20215. //If have a string shim config, and this is
  20216. //a fully executed module, try to see if
  20217. //it created a variable in this eval scope
  20218. if (getOwn(context.needFullExec, moduleName)) {
  20219. shim = getOwn(context.config.shim, moduleName);
  20220. if (shim && shim.exports) {
  20221. shimExports = eval(shim.exports);
  20222. if (typeof shimExports !== 'undefined') {
  20223. context.buildShimExports[moduleName] = shimExports;
  20224. }
  20225. }
  20226. }
  20227. //Need to close out completion of this module
  20228. //so that listeners will get notified that it is available.
  20229. context.completeLoad(moduleName);
  20230. } catch (e) {
  20231. //Track which module could not complete loading.
  20232. if (!e.moduleTree) {
  20233. e.moduleTree = [];
  20234. }
  20235. e.moduleTree.push(moduleName);
  20236. throw e;
  20237. }
  20238. }).then(null, function (eOuter) {
  20239. if (!eOuter.fileName) {
  20240. eOuter.fileName = url;
  20241. }
  20242. throw eOuter;
  20243. }).end();
  20244. } else {
  20245. //With unsupported URLs still need to call completeLoad to
  20246. //finish loading.
  20247. context.completeLoad(moduleName);
  20248. }
  20249. };
  20250. //Marks module has having a name, and optionally executes the
  20251. //callback, but only if it meets certain criteria.
  20252. context.execCb = function (name, cb, args, exports) {
  20253. var buildShimExports = getOwn(layer.context.buildShimExports, name);
  20254. if (buildShimExports) {
  20255. return buildShimExports;
  20256. } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) {
  20257. return cb.apply(exports, args);
  20258. }
  20259. return undefined;
  20260. };
  20261. moduleProto.init = function (depMaps) {
  20262. if (context.needFullExec[this.map.id]) {
  20263. lang.each(depMaps, lang.bind(this, function (depMap) {
  20264. if (typeof depMap === 'string') {
  20265. depMap = context.makeModuleMap(depMap,
  20266. (this.map.isDefine ? this.map : this.map.parentMap));
  20267. }
  20268. if (!context.fullExec[depMap.id]) {
  20269. context.require.undef(depMap.id);
  20270. }
  20271. }));
  20272. }
  20273. return oldInit.apply(this, arguments);
  20274. };
  20275. moduleProto.callPlugin = function () {
  20276. var map = this.map,
  20277. pluginMap = context.makeModuleMap(map.prefix),
  20278. pluginId = pluginMap.id,
  20279. pluginMod = getOwn(context.registry, pluginId);
  20280. context.plugins[pluginId] = true;
  20281. context.needFullExec[pluginId] = true;
  20282. //If the module is not waiting to finish being defined,
  20283. //undef it and start over, to get full execution.
  20284. if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) {
  20285. context.require.undef(pluginMap.id);
  20286. }
  20287. return oldCallPlugin.apply(this, arguments);
  20288. };
  20289. }
  20290. return context;
  20291. };
  20292. //Clear up the existing context so that the newContext modifications
  20293. //above will be active.
  20294. delete require.s.contexts._;
  20295. /** Reset state for each build layer pass. */
  20296. require._buildReset = function () {
  20297. var oldContext = require.s.contexts._;
  20298. //Clear up the existing context.
  20299. delete require.s.contexts._;
  20300. //Set up new context, so the layer object can hold onto it.
  20301. require({});
  20302. layer = require._layer = {
  20303. buildPathMap: {},
  20304. buildFileToModule: {},
  20305. buildFilePaths: [],
  20306. pathAdded: {},
  20307. modulesWithNames: {},
  20308. needsDefine: {},
  20309. existingRequireUrl: "",
  20310. ignoredUrls: {},
  20311. context: require.s.contexts._
  20312. };
  20313. //Return the previous context in case it is needed, like for
  20314. //the basic config object.
  20315. return oldContext;
  20316. };
  20317. require._buildReset();
  20318. //Override define() to catch modules that just define an object, so that
  20319. //a dummy define call is not put in the build file for them. They do
  20320. //not end up getting defined via context.execCb, so we need to catch them
  20321. //at the define call.
  20322. oldDef = define;
  20323. //This function signature does not have to be exact, just match what we
  20324. //are looking for.
  20325. define = function (name) {
  20326. if (typeof name === "string" && falseProp(layer.needsDefine, name)) {
  20327. layer.modulesWithNames[name] = true;
  20328. }
  20329. return oldDef.apply(require, arguments);
  20330. };
  20331. define.amd = oldDef.amd;
  20332. //Add some utilities for plugins
  20333. require._readFile = file.readFile;
  20334. require._fileExists = function (path) {
  20335. return file.exists(path);
  20336. };
  20337. //Called when execManager runs for a dependency. Used to figure out
  20338. //what order of execution.
  20339. require.onResourceLoad = function (context, map) {
  20340. var id = map.id,
  20341. url;
  20342. //If build needed a full execution, indicate it
  20343. //has been done now. But only do it if the context is tracking
  20344. //that. Only valid for the context used in a build, not for
  20345. //other contexts being run, like for useLib, plain requirejs
  20346. //use in node/rhino.
  20347. if (context.needFullExec && getOwn(context.needFullExec, id)) {
  20348. context.fullExec[id] = true;
  20349. }
  20350. //A plugin.
  20351. if (map.prefix) {
  20352. if (falseProp(layer.pathAdded, id)) {
  20353. layer.buildFilePaths.push(id);
  20354. //For plugins the real path is not knowable, use the name
  20355. //for both module to file and file to module mappings.
  20356. layer.buildPathMap[id] = id;
  20357. layer.buildFileToModule[id] = id;
  20358. layer.modulesWithNames[id] = true;
  20359. layer.pathAdded[id] = true;
  20360. }
  20361. } else if (map.url && require._isSupportedBuildUrl(map.url)) {
  20362. //If the url has not been added to the layer yet, and it
  20363. //is from an actual file that was loaded, add it now.
  20364. url = normalizeUrlWithBase(context, id, map.url);
  20365. if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) {
  20366. //Remember the list of dependencies for this layer.
  20367. layer.buildFilePaths.push(url);
  20368. layer.pathAdded[url] = true;
  20369. }
  20370. }
  20371. };
  20372. //Called by output of the parse() function, when a file does not
  20373. //explicitly call define, probably just require, but the parse()
  20374. //function normalizes on define() for dependency mapping and file
  20375. //ordering works correctly.
  20376. require.needsDefine = function (moduleName) {
  20377. layer.needsDefine[moduleName] = true;
  20378. };
  20379. };
  20380. });
  20381. /**
  20382. * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  20383. * Available via the MIT or new BSD license.
  20384. * see: http://github.com/jrburke/requirejs for details
  20385. */
  20386. /*jslint */
  20387. /*global define: false, console: false */
  20388. define('commonJs', ['env!env/file', 'parse'], function (file, parse) {
  20389. 'use strict';
  20390. var commonJs = {
  20391. //Set to false if you do not want this file to log. Useful in environments
  20392. //like node where you want the work to happen without noise.
  20393. useLog: true,
  20394. convertDir: function (commonJsPath, savePath) {
  20395. var fileList, i,
  20396. jsFileRegExp = /\.js$/,
  20397. fileName, convertedFileName, fileContents;
  20398. //Get list of files to convert.
  20399. fileList = file.getFilteredFileList(commonJsPath, /\w/, true);
  20400. //Normalize on front slashes and make sure the paths do not end in a slash.
  20401. commonJsPath = commonJsPath.replace(/\\/g, "/");
  20402. savePath = savePath.replace(/\\/g, "/");
  20403. if (commonJsPath.charAt(commonJsPath.length - 1) === "/") {
  20404. commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1);
  20405. }
  20406. if (savePath.charAt(savePath.length - 1) === "/") {
  20407. savePath = savePath.substring(0, savePath.length - 1);
  20408. }
  20409. //Cycle through all the JS files and convert them.
  20410. if (!fileList || !fileList.length) {
  20411. if (commonJs.useLog) {
  20412. if (commonJsPath === "convert") {
  20413. //A request just to convert one file.
  20414. console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath)));
  20415. } else {
  20416. console.log("No files to convert in directory: " + commonJsPath);
  20417. }
  20418. }
  20419. } else {
  20420. for (i = 0; i < fileList.length; i++) {
  20421. fileName = fileList[i];
  20422. convertedFileName = fileName.replace(commonJsPath, savePath);
  20423. //Handle JS files.
  20424. if (jsFileRegExp.test(fileName)) {
  20425. fileContents = file.readFile(fileName);
  20426. fileContents = commonJs.convert(fileName, fileContents);
  20427. file.saveUtf8File(convertedFileName, fileContents);
  20428. } else {
  20429. //Just copy the file over.
  20430. file.copyFile(fileName, convertedFileName, true);
  20431. }
  20432. }
  20433. }
  20434. },
  20435. /**
  20436. * Does the actual file conversion.
  20437. *
  20438. * @param {String} fileName the name of the file.
  20439. *
  20440. * @param {String} fileContents the contents of a file :)
  20441. *
  20442. * @returns {String} the converted contents
  20443. */
  20444. convert: function (fileName, fileContents) {
  20445. //Strip out comments.
  20446. try {
  20447. var preamble = '',
  20448. commonJsProps = parse.usesCommonJs(fileName, fileContents);
  20449. //First see if the module is not already RequireJS-formatted.
  20450. if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) {
  20451. return fileContents;
  20452. }
  20453. if (commonJsProps.dirname || commonJsProps.filename) {
  20454. preamble = 'var __filename = module.uri || "", ' +
  20455. '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); ';
  20456. }
  20457. //Construct the wrapper boilerplate.
  20458. fileContents = 'define(function (require, exports, module) {' +
  20459. preamble +
  20460. fileContents +
  20461. '\n});\n';
  20462. } catch (e) {
  20463. console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e);
  20464. return fileContents;
  20465. }
  20466. return fileContents;
  20467. }
  20468. };
  20469. return commonJs;
  20470. });
  20471. /**
  20472. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  20473. * Available via the MIT or new BSD license.
  20474. * see: http://github.com/jrburke/requirejs for details
  20475. */
  20476. /*jslint plusplus: true, nomen: true, regexp: true */
  20477. /*global define, requirejs */
  20478. define('build', function (require) {
  20479. 'use strict';
  20480. var build, buildBaseConfig,
  20481. lang = require('lang'),
  20482. prim = require('prim'),
  20483. logger = require('logger'),
  20484. file = require('env!env/file'),
  20485. parse = require('parse'),
  20486. optimize = require('optimize'),
  20487. pragma = require('pragma'),
  20488. transform = require('transform'),
  20489. requirePatch = require('requirePatch'),
  20490. env = require('env'),
  20491. quit = require('env!env/quit'),
  20492. commonJs = require('commonJs'),
  20493. hasProp = lang.hasProp,
  20494. getOwn = lang.getOwn,
  20495. falseProp = lang.falseProp,
  20496. endsWithSemiColonRegExp = /;\s*$/;
  20497. prim.nextTick = function (fn) {
  20498. fn();
  20499. };
  20500. //Now map require to the outermost requirejs, now that we have
  20501. //local dependencies for this module. The rest of the require use is
  20502. //manipulating the requirejs loader.
  20503. require = requirejs;
  20504. //Caching function for performance. Attached to
  20505. //require so it can be reused in requirePatch.js. _cachedRawText
  20506. //set up by requirePatch.js
  20507. require._cacheReadAsync = function (path, encoding) {
  20508. var d;
  20509. if (lang.hasProp(require._cachedRawText, path)) {
  20510. d = prim();
  20511. d.resolve(require._cachedRawText[path]);
  20512. return d.promise;
  20513. } else {
  20514. return file.readFileAsync(path, encoding).then(function (text) {
  20515. require._cachedRawText[path] = text;
  20516. return text;
  20517. });
  20518. }
  20519. };
  20520. buildBaseConfig = {
  20521. appDir: "",
  20522. pragmas: {},
  20523. paths: {},
  20524. optimize: "uglify",
  20525. optimizeCss: "standard.keepLines",
  20526. inlineText: true,
  20527. isBuild: true,
  20528. optimizeAllPluginResources: false,
  20529. findNestedDependencies: false,
  20530. preserveLicenseComments: true,
  20531. //By default, all files/directories are copied, unless
  20532. //they match this regexp, by default just excludes .folders
  20533. dirExclusionRegExp: file.dirExclusionRegExp,
  20534. _buildPathToModuleIndex: {}
  20535. };
  20536. /**
  20537. * Some JS may not be valid if concatenated with other JS, in particular
  20538. * the style of omitting semicolons and rely on ASI. Add a semicolon in
  20539. * those cases.
  20540. */
  20541. function addSemiColon(text) {
  20542. if (endsWithSemiColonRegExp.test(text)) {
  20543. return text;
  20544. } else {
  20545. return text + ";";
  20546. }
  20547. }
  20548. function endsWithSlash(dirName) {
  20549. if (dirName.charAt(dirName.length - 1) !== "/") {
  20550. dirName += "/";
  20551. }
  20552. return dirName;
  20553. }
  20554. //Method used by plugin writeFile calls, defined up here to avoid
  20555. //jslint warning about "making a function in a loop".
  20556. function makeWriteFile(namespace, layer) {
  20557. function writeFile(name, contents) {
  20558. logger.trace('Saving plugin-optimized file: ' + name);
  20559. file.saveUtf8File(name, contents);
  20560. }
  20561. writeFile.asModule = function (moduleName, fileName, contents) {
  20562. writeFile(fileName,
  20563. build.toTransport(namespace, moduleName, fileName, contents, layer));
  20564. };
  20565. return writeFile;
  20566. }
  20567. /**
  20568. * Main API entry point into the build. The args argument can either be
  20569. * an array of arguments (like the onese passed on a command-line),
  20570. * or it can be a JavaScript object that has the format of a build profile
  20571. * file.
  20572. *
  20573. * If it is an object, then in addition to the normal properties allowed in
  20574. * a build profile file, the object should contain one other property:
  20575. *
  20576. * The object could also contain a "buildFile" property, which is a string
  20577. * that is the file path to a build profile that contains the rest
  20578. * of the build profile directives.
  20579. *
  20580. * This function does not return a status, it should throw an error if
  20581. * there is a problem completing the build.
  20582. */
  20583. build = function (args) {
  20584. var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree,
  20585. i, j, errorMod,
  20586. stackRegExp = /( {4}at[^\n]+)\n/,
  20587. standardIndent = ' ';
  20588. return prim().start(function () {
  20589. if (!args || lang.isArray(args)) {
  20590. if (!args || args.length < 1) {
  20591. logger.error("build.js buildProfile.js\n" +
  20592. "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file).");
  20593. return undefined;
  20594. }
  20595. //Next args can include a build file path as well as other build args.
  20596. //build file path comes first. If it does not contain an = then it is
  20597. //a build file path. Otherwise, just all build args.
  20598. if (args[0].indexOf("=") === -1) {
  20599. buildFile = args[0];
  20600. args.splice(0, 1);
  20601. }
  20602. //Remaining args are options to the build
  20603. cmdConfig = build.convertArrayToObject(args);
  20604. cmdConfig.buildFile = buildFile;
  20605. } else {
  20606. cmdConfig = args;
  20607. }
  20608. return build._run(cmdConfig);
  20609. }).then(null, function (e) {
  20610. errorMsg = e.toString();
  20611. errorTree = e.moduleTree;
  20612. stackMatch = stackRegExp.exec(errorMsg);
  20613. if (stackMatch) {
  20614. errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1);
  20615. }
  20616. //If a module tree that shows what module triggered the error,
  20617. //print it out.
  20618. if (errorTree && errorTree.length > 0) {
  20619. errorMsg += '\nIn module tree:\n';
  20620. for (i = errorTree.length - 1; i > -1; i--) {
  20621. errorMod = errorTree[i];
  20622. if (errorMod) {
  20623. for (j = errorTree.length - i; j > -1; j--) {
  20624. errorMsg += standardIndent;
  20625. }
  20626. errorMsg += errorMod + '\n';
  20627. }
  20628. }
  20629. logger.error(errorMsg);
  20630. }
  20631. errorStack = e.stack;
  20632. if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) {
  20633. errorMsg += '\n' + errorStack;
  20634. } else {
  20635. if (!stackMatch && errorStack) {
  20636. //Just trim out the first "at" in the stack.
  20637. stackMatch = stackRegExp.exec(errorStack);
  20638. if (stackMatch) {
  20639. errorMsg += '\n' + stackMatch[0] || '';
  20640. }
  20641. }
  20642. }
  20643. if (logger.level > logger.ERROR) {
  20644. throw new Error(errorMsg);
  20645. } else {
  20646. logger.error(errorMsg);
  20647. quit(1);
  20648. }
  20649. });
  20650. };
  20651. build._run = function (cmdConfig) {
  20652. var buildPaths, fileName, fileNames,
  20653. paths, i,
  20654. baseConfig, config,
  20655. modules, srcPath, buildContext,
  20656. destPath, moduleMap, parentModuleMap, context,
  20657. resources, resource, plugin, fileContents,
  20658. pluginProcessed = {},
  20659. buildFileContents = "",
  20660. pluginCollector = {};
  20661. return prim().start(function () {
  20662. var prop;
  20663. //Can now run the patches to require.js to allow it to be used for
  20664. //build generation. Do it here instead of at the top of the module
  20665. //because we want normal require behavior to load the build tool
  20666. //then want to switch to build mode.
  20667. requirePatch();
  20668. config = build.createConfig(cmdConfig);
  20669. paths = config.paths;
  20670. //Remove the previous build dir, in case it contains source transforms,
  20671. //like the ones done with onBuildRead and onBuildWrite.
  20672. if (config.dir && !config.keepBuildDir && file.exists(config.dir)) {
  20673. file.deleteFile(config.dir);
  20674. }
  20675. if (!config.out && !config.cssIn) {
  20676. //This is not just a one-off file build but a full build profile, with
  20677. //lots of files to process.
  20678. //First copy all the baseUrl content
  20679. file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true);
  20680. //Adjust baseUrl if config.appDir is in play, and set up build output paths.
  20681. buildPaths = {};
  20682. if (config.appDir) {
  20683. //All the paths should be inside the appDir, so just adjust
  20684. //the paths to use the dirBaseUrl
  20685. for (prop in paths) {
  20686. if (hasProp(paths, prop)) {
  20687. buildPaths[prop] = paths[prop].replace(config.appDir, config.dir);
  20688. }
  20689. }
  20690. } else {
  20691. //If no appDir, then make sure to copy the other paths to this directory.
  20692. for (prop in paths) {
  20693. if (hasProp(paths, prop)) {
  20694. //Set up build path for each path prefix, but only do so
  20695. //if the path falls out of the current baseUrl
  20696. if (paths[prop].indexOf(config.baseUrl) === 0) {
  20697. buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl);
  20698. } else {
  20699. buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop.replace(/\./g, "/");
  20700. //Make sure source path is fully formed with baseUrl,
  20701. //if it is a relative URL.
  20702. srcPath = paths[prop];
  20703. if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) {
  20704. srcPath = config.baseUrl + srcPath;
  20705. }
  20706. destPath = config.dirBaseUrl + buildPaths[prop];
  20707. //Skip empty: paths
  20708. if (srcPath !== 'empty:') {
  20709. //If the srcPath is a directory, copy the whole directory.
  20710. if (file.exists(srcPath) && file.isDirectory(srcPath)) {
  20711. //Copy files to build area. Copy all files (the /\w/ regexp)
  20712. file.copyDir(srcPath, destPath, /\w/, true);
  20713. } else {
  20714. //Try a .js extension
  20715. srcPath += '.js';
  20716. destPath += '.js';
  20717. file.copyFile(srcPath, destPath);
  20718. }
  20719. }
  20720. }
  20721. }
  20722. }
  20723. }
  20724. }
  20725. //Figure out source file location for each module layer. Do this by seeding require
  20726. //with source area configuration. This is needed so that later the module layers
  20727. //can be manually copied over to the source area, since the build may be
  20728. //require multiple times and the above copyDir call only copies newer files.
  20729. require({
  20730. baseUrl: config.baseUrl,
  20731. paths: paths,
  20732. packagePaths: config.packagePaths,
  20733. packages: config.packages
  20734. });
  20735. buildContext = require.s.contexts._;
  20736. modules = config.modules;
  20737. if (modules) {
  20738. modules.forEach(function (module) {
  20739. if (module.name) {
  20740. module._sourcePath = buildContext.nameToUrl(module.name);
  20741. //If the module does not exist, and this is not a "new" module layer,
  20742. //as indicated by a true "create" property on the module, and
  20743. //it is not a plugin-loaded resource, then throw an error.
  20744. if (!file.exists(module._sourcePath) && !module.create &&
  20745. module.name.indexOf('!') === -1) {
  20746. throw new Error("ERROR: module path does not exist: " +
  20747. module._sourcePath + " for module named: " + module.name +
  20748. ". Path is relative to: " + file.absPath('.'));
  20749. }
  20750. }
  20751. });
  20752. }
  20753. if (config.out) {
  20754. //Just set up the _buildPath for the module layer.
  20755. require(config);
  20756. if (!config.cssIn) {
  20757. config.modules[0]._buildPath = typeof config.out === 'function' ?
  20758. 'FUNCTION' : config.out;
  20759. }
  20760. } else if (!config.cssIn) {
  20761. //Now set up the config for require to use the build area, and calculate the
  20762. //build file locations. Pass along any config info too.
  20763. baseConfig = {
  20764. baseUrl: config.dirBaseUrl,
  20765. paths: buildPaths
  20766. };
  20767. lang.mixin(baseConfig, config);
  20768. require(baseConfig);
  20769. if (modules) {
  20770. modules.forEach(function (module) {
  20771. if (module.name) {
  20772. module._buildPath = buildContext.nameToUrl(module.name, null);
  20773. if (!module.create) {
  20774. file.copyFile(module._sourcePath, module._buildPath);
  20775. }
  20776. }
  20777. });
  20778. }
  20779. }
  20780. //Run CSS optimizations before doing JS module tracing, to allow
  20781. //things like text loader plugins loading CSS to get the optimized
  20782. //CSS.
  20783. if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) {
  20784. buildFileContents += optimize.css(config.dir, config);
  20785. }
  20786. }).then(function () {
  20787. var actions = [];
  20788. if (modules) {
  20789. actions = modules.map(function (module, i) {
  20790. return function () {
  20791. //Save off buildPath to module index in a hash for quicker
  20792. //lookup later.
  20793. config._buildPathToModuleIndex[module._buildPath] = i;
  20794. //Call require to calculate dependencies.
  20795. return build.traceDependencies(module, config)
  20796. .then(function (layer) {
  20797. module.layer = layer;
  20798. });
  20799. };
  20800. });
  20801. return prim.serial(actions);
  20802. }
  20803. }).then(function () {
  20804. var actions;
  20805. if (modules) {
  20806. //Now build up shadow layers for anything that should be excluded.
  20807. //Do this after tracing dependencies for each module, in case one
  20808. //of those modules end up being one of the excluded values.
  20809. actions = modules.map(function (module) {
  20810. return function () {
  20811. if (module.exclude) {
  20812. module.excludeLayers = [];
  20813. return prim.serial(module.exclude.map(function (exclude, i) {
  20814. return function () {
  20815. //See if it is already in the list of modules.
  20816. //If not trace dependencies for it.
  20817. var found = build.findBuildModule(exclude, modules);
  20818. if (found) {
  20819. module.excludeLayers[i] = found;
  20820. } else {
  20821. return build.traceDependencies({name: exclude}, config)
  20822. .then(function (layer) {
  20823. module.excludeLayers[i] = { layer: layer };
  20824. });
  20825. }
  20826. };
  20827. }));
  20828. }
  20829. };
  20830. });
  20831. return prim.serial(actions);
  20832. }
  20833. }).then(function () {
  20834. if (modules) {
  20835. return prim.serial(modules.map(function (module) {
  20836. return function () {
  20837. if (module.exclude) {
  20838. //module.exclude is an array of module names. For each one,
  20839. //get the nested dependencies for it via a matching entry
  20840. //in the module.excludeLayers array.
  20841. module.exclude.forEach(function (excludeModule, i) {
  20842. var excludeLayer = module.excludeLayers[i].layer,
  20843. map = excludeLayer.buildFileToModule;
  20844. excludeLayer.buildFilePaths.forEach(function(filePath){
  20845. build.removeModulePath(map[filePath], filePath, module.layer);
  20846. });
  20847. });
  20848. }
  20849. if (module.excludeShallow) {
  20850. //module.excludeShallow is an array of module names.
  20851. //shallow exclusions are just that module itself, and not
  20852. //its nested dependencies.
  20853. module.excludeShallow.forEach(function (excludeShallowModule) {
  20854. var path = getOwn(module.layer.buildPathMap, excludeShallowModule);
  20855. if (path) {
  20856. build.removeModulePath(excludeShallowModule, path, module.layer);
  20857. }
  20858. });
  20859. }
  20860. //Flatten them and collect the build output for each module.
  20861. return build.flattenModule(module, module.layer, config).then(function (builtModule) {
  20862. //Save it to a temp file for now, in case there are other layers that
  20863. //contain optimized content that should not be included in later
  20864. //layer optimizations. See issue #56.
  20865. if (module._buildPath === 'FUNCTION') {
  20866. module._buildText = builtModule.text;
  20867. } else {
  20868. file.saveUtf8File(module._buildPath + '-temp', builtModule.text);
  20869. }
  20870. buildFileContents += builtModule.buildText;
  20871. });
  20872. };
  20873. }));
  20874. }
  20875. }).then(function () {
  20876. var moduleName;
  20877. if (modules) {
  20878. //Now move the build layers to their final position.
  20879. modules.forEach(function (module) {
  20880. var finalPath = module._buildPath;
  20881. if (finalPath !== 'FUNCTION') {
  20882. if (file.exists(finalPath)) {
  20883. file.deleteFile(finalPath);
  20884. }
  20885. file.renameFile(finalPath + '-temp', finalPath);
  20886. //And finally, if removeCombined is specified, remove
  20887. //any of the files that were used in this layer.
  20888. //Be sure not to remove other build layers.
  20889. if (config.removeCombined) {
  20890. module.layer.buildFilePaths.forEach(function (path) {
  20891. if (file.exists(path) && !modules.some(function (mod) {
  20892. return mod._buildPath === path;
  20893. })) {
  20894. file.deleteFile(path);
  20895. }
  20896. });
  20897. }
  20898. }
  20899. });
  20900. }
  20901. //If removeCombined in play, remove any empty directories that
  20902. //may now exist because of its use
  20903. if (config.removeCombined && !config.out && config.dir) {
  20904. file.deleteEmptyDirs(config.dir);
  20905. }
  20906. //Do other optimizations.
  20907. if (config.out && !config.cssIn) {
  20908. //Just need to worry about one JS file.
  20909. fileName = config.modules[0]._buildPath;
  20910. if (fileName === 'FUNCTION') {
  20911. config.modules[0]._buildText = optimize.js(fileName,
  20912. config.modules[0]._buildText,
  20913. null,
  20914. config);
  20915. } else {
  20916. optimize.jsFile(fileName, null, fileName, config);
  20917. }
  20918. } else if (!config.cssIn) {
  20919. //Normal optimizations across modules.
  20920. //JS optimizations.
  20921. fileNames = file.getFilteredFileList(config.dir, /\.js$/, true);
  20922. fileNames.forEach(function (fileName) {
  20923. var cfg, override, moduleIndex;
  20924. //Generate the module name from the config.dir root.
  20925. moduleName = fileName.replace(config.dir, '');
  20926. //Get rid of the extension
  20927. moduleName = moduleName.substring(0, moduleName.length - 3);
  20928. //If there is an override for a specific layer build module,
  20929. //and this file is that module, mix in the override for use
  20930. //by optimize.jsFile.
  20931. moduleIndex = getOwn(config._buildPathToModuleIndex, fileName);
  20932. //Normalize, since getOwn could have returned undefined
  20933. moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1;
  20934. //Try to avoid extra work if the other files do not need to
  20935. //be read. Build layers should be processed at the very
  20936. //least for optimization.
  20937. if (moduleIndex > -1 || !config.skipDirOptimize ||
  20938. config.normalizeDirDefines === "all" ||
  20939. config.cjsTranslate) {
  20940. //Convert the file to transport format, but without a name
  20941. //inserted (by passing null for moduleName) since the files are
  20942. //standalone, one module per file.
  20943. fileContents = file.readFile(fileName);
  20944. //For builds, if wanting cjs translation, do it now, so that
  20945. //the individual modules can be loaded cross domain via
  20946. //plain script tags.
  20947. if (config.cjsTranslate) {
  20948. fileContents = commonJs.convert(fileName, fileContents);
  20949. }
  20950. //Only do transport normalization if this is not a build
  20951. //layer (since it was already normalized) and if
  20952. //normalizeDirDefines indicated all should be done.
  20953. if (moduleIndex === -1 && config.normalizeDirDefines === "all") {
  20954. fileContents = build.toTransport(config.namespace,
  20955. null,
  20956. fileName,
  20957. fileContents);
  20958. }
  20959. override = moduleIndex > -1 ?
  20960. config.modules[moduleIndex].override : null;
  20961. if (override) {
  20962. cfg = build.createOverrideConfig(config, override);
  20963. } else {
  20964. cfg = config;
  20965. }
  20966. if (moduleIndex > -1 || !config.skipDirOptimize) {
  20967. optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector);
  20968. }
  20969. }
  20970. });
  20971. //Normalize all the plugin resources.
  20972. context = require.s.contexts._;
  20973. for (moduleName in pluginCollector) {
  20974. if (hasProp(pluginCollector, moduleName)) {
  20975. parentModuleMap = context.makeModuleMap(moduleName);
  20976. resources = pluginCollector[moduleName];
  20977. for (i = 0; i < resources.length; i++) {
  20978. resource = resources[i];
  20979. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  20980. if (falseProp(context.plugins, moduleMap.prefix)) {
  20981. //Set the value in context.plugins so it
  20982. //will be evaluated as a full plugin.
  20983. context.plugins[moduleMap.prefix] = true;
  20984. //Do not bother if the plugin is not available.
  20985. if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) {
  20986. continue;
  20987. }
  20988. //Rely on the require in the build environment
  20989. //to be synchronous
  20990. context.require([moduleMap.prefix]);
  20991. //Now that the plugin is loaded, redo the moduleMap
  20992. //since the plugin will need to normalize part of the path.
  20993. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  20994. }
  20995. //Only bother with plugin resources that can be handled
  20996. //processed by the plugin, via support of the writeFile
  20997. //method.
  20998. if (falseProp(pluginProcessed, moduleMap.id)) {
  20999. //Only do the work if the plugin was really loaded.
  21000. //Using an internal access because the file may
  21001. //not really be loaded.
  21002. plugin = getOwn(context.defined, moduleMap.prefix);
  21003. if (plugin && plugin.writeFile) {
  21004. plugin.writeFile(
  21005. moduleMap.prefix,
  21006. moduleMap.name,
  21007. require,
  21008. makeWriteFile(
  21009. config.namespace
  21010. ),
  21011. context.config
  21012. );
  21013. }
  21014. pluginProcessed[moduleMap.id] = true;
  21015. }
  21016. }
  21017. }
  21018. }
  21019. //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " "));
  21020. //All module layers are done, write out the build.txt file.
  21021. file.saveUtf8File(config.dir + "build.txt", buildFileContents);
  21022. }
  21023. //If just have one CSS file to optimize, do that here.
  21024. if (config.cssIn) {
  21025. buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText;
  21026. }
  21027. if (typeof config.out === 'function') {
  21028. config.out(config.modules[0]._buildText);
  21029. }
  21030. //Print out what was built into which layers.
  21031. if (buildFileContents) {
  21032. logger.info(buildFileContents);
  21033. return buildFileContents;
  21034. }
  21035. return '';
  21036. });
  21037. };
  21038. /**
  21039. * Converts command line args like "paths.foo=../some/path"
  21040. * result.paths = { foo: '../some/path' } where prop = paths,
  21041. * name = paths.foo and value = ../some/path, so it assumes the
  21042. * name=value splitting has already happened.
  21043. */
  21044. function stringDotToObj(result, name, value) {
  21045. var parts = name.split('.');
  21046. parts.forEach(function (prop, i) {
  21047. if (i === parts.length - 1) {
  21048. result[prop] = value;
  21049. } else {
  21050. if (falseProp(result, prop)) {
  21051. result[prop] = {};
  21052. }
  21053. result = result[prop];
  21054. }
  21055. });
  21056. }
  21057. build.objProps = {
  21058. paths: true,
  21059. wrap: true,
  21060. pragmas: true,
  21061. pragmasOnSave: true,
  21062. has: true,
  21063. hasOnSave: true,
  21064. uglify: true,
  21065. uglify2: true,
  21066. closure: true,
  21067. map: true,
  21068. throwWhen: true
  21069. };
  21070. build.hasDotPropMatch = function (prop) {
  21071. var dotProp,
  21072. index = prop.indexOf('.');
  21073. if (index !== -1) {
  21074. dotProp = prop.substring(0, index);
  21075. return hasProp(build.objProps, dotProp);
  21076. }
  21077. return false;
  21078. };
  21079. /**
  21080. * Converts an array that has String members of "name=value"
  21081. * into an object, where the properties on the object are the names in the array.
  21082. * Also converts the strings "true" and "false" to booleans for the values.
  21083. * member name/value pairs, and converts some comma-separated lists into
  21084. * arrays.
  21085. * @param {Array} ary
  21086. */
  21087. build.convertArrayToObject = function (ary) {
  21088. var result = {}, i, separatorIndex, prop, value,
  21089. needArray = {
  21090. "include": true,
  21091. "exclude": true,
  21092. "excludeShallow": true,
  21093. "insertRequire": true
  21094. };
  21095. for (i = 0; i < ary.length; i++) {
  21096. separatorIndex = ary[i].indexOf("=");
  21097. if (separatorIndex === -1) {
  21098. throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value";
  21099. }
  21100. value = ary[i].substring(separatorIndex + 1, ary[i].length);
  21101. if (value === "true") {
  21102. value = true;
  21103. } else if (value === "false") {
  21104. value = false;
  21105. }
  21106. prop = ary[i].substring(0, separatorIndex);
  21107. //Convert to array if necessary
  21108. if (getOwn(needArray, prop)) {
  21109. value = value.split(",");
  21110. }
  21111. if (build.hasDotPropMatch(prop)) {
  21112. stringDotToObj(result, prop, value);
  21113. } else {
  21114. result[prop] = value;
  21115. }
  21116. }
  21117. return result; //Object
  21118. };
  21119. build.makeAbsPath = function (path, absFilePath) {
  21120. if (!absFilePath) {
  21121. return path;
  21122. }
  21123. //Add abspath if necessary. If path starts with a slash or has a colon,
  21124. //then already is an abolute path.
  21125. if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) {
  21126. path = absFilePath +
  21127. (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') +
  21128. path;
  21129. path = file.normalize(path);
  21130. }
  21131. return path.replace(lang.backSlashRegExp, '/');
  21132. };
  21133. build.makeAbsObject = function (props, obj, absFilePath) {
  21134. var i, prop;
  21135. if (obj) {
  21136. for (i = 0; i < props.length; i++) {
  21137. prop = props[i];
  21138. if (hasProp(obj, prop) && typeof obj[prop] === 'string') {
  21139. obj[prop] = build.makeAbsPath(obj[prop], absFilePath);
  21140. }
  21141. }
  21142. }
  21143. };
  21144. /**
  21145. * For any path in a possible config, make it absolute relative
  21146. * to the absFilePath passed in.
  21147. */
  21148. build.makeAbsConfig = function (config, absFilePath) {
  21149. var props, prop, i;
  21150. props = ["appDir", "dir", "baseUrl"];
  21151. for (i = 0; i < props.length; i++) {
  21152. prop = props[i];
  21153. if (getOwn(config, prop)) {
  21154. //Add abspath if necessary, make sure these paths end in
  21155. //slashes
  21156. if (prop === "baseUrl") {
  21157. config.originalBaseUrl = config.baseUrl;
  21158. if (config.appDir) {
  21159. //If baseUrl with an appDir, the baseUrl is relative to
  21160. //the appDir, *not* the absFilePath. appDir and dir are
  21161. //made absolute before baseUrl, so this will work.
  21162. config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir);
  21163. } else {
  21164. //The dir output baseUrl is same as regular baseUrl, both
  21165. //relative to the absFilePath.
  21166. config.baseUrl = build.makeAbsPath(config[prop], absFilePath);
  21167. }
  21168. } else {
  21169. config[prop] = build.makeAbsPath(config[prop], absFilePath);
  21170. }
  21171. config[prop] = endsWithSlash(config[prop]);
  21172. }
  21173. }
  21174. build.makeAbsObject(["out", "cssIn"], config, absFilePath);
  21175. build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath);
  21176. };
  21177. build.nestedMix = {
  21178. paths: true,
  21179. has: true,
  21180. hasOnSave: true,
  21181. pragmas: true,
  21182. pragmasOnSave: true
  21183. };
  21184. /**
  21185. * Mixes additional source config into target config, and merges some
  21186. * nested config, like paths, correctly.
  21187. */
  21188. function mixConfig(target, source) {
  21189. var prop, value;
  21190. for (prop in source) {
  21191. if (hasProp(source, prop)) {
  21192. //If the value of the property is a plain object, then
  21193. //allow a one-level-deep mixing of it.
  21194. value = source[prop];
  21195. if (typeof value === 'object' && value &&
  21196. !lang.isArray(value) && !lang.isFunction(value) &&
  21197. !lang.isRegExp(value)) {
  21198. target[prop] = lang.mixin({}, target[prop], value, true);
  21199. } else {
  21200. target[prop] = value;
  21201. }
  21202. }
  21203. }
  21204. //Set up log level since it can affect if errors are thrown
  21205. //or caught and passed to errbacks while doing config setup.
  21206. if (lang.hasProp(target, 'logLevel')) {
  21207. logger.logLevel(target.logLevel);
  21208. }
  21209. }
  21210. /**
  21211. * Converts a wrap.startFile or endFile to be start/end as a string.
  21212. * the startFile/endFile values can be arrays.
  21213. */
  21214. function flattenWrapFile(wrap, keyName, absFilePath) {
  21215. var keyFileName = keyName + 'File';
  21216. if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) {
  21217. wrap[keyName] = '';
  21218. if (typeof wrap[keyFileName] === 'string') {
  21219. wrap[keyFileName] = [wrap[keyFileName]];
  21220. }
  21221. wrap[keyFileName].forEach(function (fileName) {
  21222. wrap[keyName] += (wrap[keyName] ? '\n' : '') +
  21223. file.readFile(build.makeAbsPath(fileName, absFilePath));
  21224. });
  21225. } else if (wrap[keyName] === null || wrap[keyName] === undefined) {
  21226. //Allow missing one, just set to empty string.
  21227. wrap[keyName] = '';
  21228. } else if (typeof wrap[keyName] !== 'string') {
  21229. throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed');
  21230. }
  21231. }
  21232. /**
  21233. * Creates a config object for an optimization build.
  21234. * It will also read the build profile if it is available, to create
  21235. * the configuration.
  21236. *
  21237. * @param {Object} cfg config options that take priority
  21238. * over defaults and ones in the build file. These options could
  21239. * be from a command line, for instance.
  21240. *
  21241. * @param {Object} the created config object.
  21242. */
  21243. build.createConfig = function (cfg) {
  21244. /*jslint evil: true */
  21245. var config = {}, buildFileContents, buildFileConfig, mainConfig,
  21246. mainConfigFile, mainConfigPath, buildFile, absFilePath;
  21247. //Make sure all paths are relative to current directory.
  21248. absFilePath = file.absPath('.');
  21249. build.makeAbsConfig(cfg, absFilePath);
  21250. build.makeAbsConfig(buildBaseConfig, absFilePath);
  21251. lang.mixin(config, buildBaseConfig);
  21252. lang.mixin(config, cfg, true);
  21253. //Set up log level early since it can affect if errors are thrown
  21254. //or caught and passed to errbacks, even while constructing config.
  21255. if (lang.hasProp(config, 'logLevel')) {
  21256. logger.logLevel(config.logLevel);
  21257. }
  21258. if (config.buildFile) {
  21259. //A build file exists, load it to get more config.
  21260. buildFile = file.absPath(config.buildFile);
  21261. //Find the build file, and make sure it exists, if this is a build
  21262. //that has a build profile, and not just command line args with an in=path
  21263. if (!file.exists(buildFile)) {
  21264. throw new Error("ERROR: build file does not exist: " + buildFile);
  21265. }
  21266. absFilePath = config.baseUrl = file.absPath(file.parent(buildFile));
  21267. //Load build file options.
  21268. buildFileContents = file.readFile(buildFile);
  21269. try {
  21270. buildFileConfig = eval("(" + buildFileContents + ")");
  21271. build.makeAbsConfig(buildFileConfig, absFilePath);
  21272. //Mix in the config now so that items in mainConfigFile can
  21273. //be resolved relative to them if necessary, like if appDir
  21274. //is set here, but the baseUrl is in mainConfigFile. Will
  21275. //re-mix in the same build config later after mainConfigFile
  21276. //is processed, since build config should take priority.
  21277. mixConfig(config, buildFileConfig);
  21278. } catch (e) {
  21279. throw new Error("Build file " + buildFile + " is malformed: " + e);
  21280. }
  21281. }
  21282. mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile);
  21283. if (mainConfigFile) {
  21284. mainConfigFile = build.makeAbsPath(mainConfigFile, absFilePath);
  21285. if (!file.exists(mainConfigFile)) {
  21286. throw new Error(mainConfigFile + ' does not exist.');
  21287. }
  21288. try {
  21289. mainConfig = parse.findConfig(file.readFile(mainConfigFile)).config;
  21290. } catch (configError) {
  21291. throw new Error('The config in mainConfigFile ' +
  21292. mainConfigFile +
  21293. ' cannot be used because it cannot be evaluated' +
  21294. ' correctly while running in the optimizer. Try only' +
  21295. ' using a config that is also valid JSON, or do not use' +
  21296. ' mainConfigFile and instead copy the config values needed' +
  21297. ' into a build file or command line arguments given to the optimizer.');
  21298. }
  21299. if (mainConfig) {
  21300. mainConfigPath = mainConfigFile.substring(0, mainConfigFile.lastIndexOf('/'));
  21301. //Add in some existing config, like appDir, since they can be
  21302. //used inside the mainConfigFile -- paths and baseUrl are
  21303. //relative to them.
  21304. if (config.appDir && !mainConfig.appDir) {
  21305. mainConfig.appDir = config.appDir;
  21306. }
  21307. //If no baseUrl, then use the directory holding the main config.
  21308. if (!mainConfig.baseUrl) {
  21309. mainConfig.baseUrl = mainConfigPath;
  21310. }
  21311. build.makeAbsConfig(mainConfig, mainConfigPath);
  21312. mixConfig(config, mainConfig);
  21313. }
  21314. }
  21315. //Mix in build file config, but only after mainConfig has been mixed in.
  21316. if (buildFileConfig) {
  21317. mixConfig(config, buildFileConfig);
  21318. }
  21319. //Re-apply the override config values. Command line
  21320. //args should take precedence over build file values.
  21321. mixConfig(config, cfg);
  21322. //Fix paths to full paths so that they can be adjusted consistently
  21323. //lately to be in the output area.
  21324. lang.eachProp(config.paths, function (value, prop) {
  21325. if (lang.isArray(value)) {
  21326. throw new Error('paths fallback not supported in optimizer. ' +
  21327. 'Please provide a build config path override ' +
  21328. 'for ' + prop);
  21329. }
  21330. config.paths[prop] = build.makeAbsPath(value, config.baseUrl);
  21331. });
  21332. //Set final output dir
  21333. if (hasProp(config, "baseUrl")) {
  21334. if (config.appDir) {
  21335. config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir);
  21336. } else {
  21337. config.dirBaseUrl = config.dir || config.baseUrl;
  21338. }
  21339. //Make sure dirBaseUrl ends in a slash, since it is
  21340. //concatenated with other strings.
  21341. config.dirBaseUrl = endsWithSlash(config.dirBaseUrl);
  21342. }
  21343. //Check for errors in config
  21344. if (config.main) {
  21345. throw new Error('"main" passed as an option, but the ' +
  21346. 'supported option is called "name".');
  21347. }
  21348. if (!config.name && !config.modules && !config.include && !config.cssIn) {
  21349. throw new Error('Missing either a "name", "include" or "modules" ' +
  21350. 'option');
  21351. }
  21352. if (config.cssIn) {
  21353. if (config.dir || config.appDir) {
  21354. throw new Error('cssIn is only for the output of single file ' +
  21355. 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.');
  21356. }
  21357. if (!config.out) {
  21358. throw new Error('"out" option missing.');
  21359. }
  21360. }
  21361. if (!config.cssIn && !config.baseUrl) {
  21362. //Just use the current directory as the baseUrl
  21363. config.baseUrl = './';
  21364. }
  21365. if (!config.out && !config.dir) {
  21366. throw new Error('Missing either an "out" or "dir" config value. ' +
  21367. 'If using "appDir" for a full project optimization, ' +
  21368. 'use "dir". If you want to optimize to one file, ' +
  21369. 'use "out".');
  21370. }
  21371. if (config.appDir && config.out) {
  21372. throw new Error('"appDir" is not compatible with "out". Use "dir" ' +
  21373. 'instead. appDir is used to copy whole projects, ' +
  21374. 'where "out" is used to just optimize to one file.');
  21375. }
  21376. if (config.out && config.dir) {
  21377. throw new Error('The "out" and "dir" options are incompatible.' +
  21378. ' Use "out" if you are targeting a single file for' +
  21379. ' for optimization, and "dir" if you want the appDir' +
  21380. ' or baseUrl directories optimized.');
  21381. }
  21382. if (config.dir && config.appDir && config.dir === config.appDir) {
  21383. throw new Error('"dir" and "appDir" set to the same directory.' +
  21384. ' This could result in the deletion of appDir.' +
  21385. ' Stopping.');
  21386. }
  21387. if (config.insertRequire && !lang.isArray(config.insertRequire)) {
  21388. throw new Error('insertRequire should be a list of module IDs' +
  21389. ' to insert in to a require([]) call.');
  21390. }
  21391. if (config.generateSourceMaps) {
  21392. if (config.preserveLicenseComments) {
  21393. throw new Error('Cannot use preserveLicenseComments and ' +
  21394. 'generateSourceMaps together. Either explcitly set ' +
  21395. 'preserveLicenseComments to false (default is true) or ' +
  21396. 'turn off generateSourceMaps. If you want source maps with ' +
  21397. 'license comments, see: ' +
  21398. 'http://requirejs.org/docs/errors.html#sourcemapcomments');
  21399. } else if (config.optimize !== 'none' &&
  21400. config.optimize !== 'closure' &&
  21401. config.optimize !== 'uglify2') {
  21402. //Allow optimize: none to pass, since it is useful when toggling
  21403. //minification on and off to debug something, and it implicitly
  21404. //works, since it does not need a source map.
  21405. throw new Error('optimize: "' + config.optimize +
  21406. '" does not support generateSourceMaps.');
  21407. }
  21408. }
  21409. if ((config.name || config.include) && !config.modules) {
  21410. //Just need to build one file, but may be part of a whole appDir/
  21411. //baseUrl copy, but specified on the command line, so cannot do
  21412. //the modules array setup. So create a modules section in that
  21413. //case.
  21414. config.modules = [
  21415. {
  21416. name: config.name,
  21417. out: config.out,
  21418. create: config.create,
  21419. include: config.include,
  21420. exclude: config.exclude,
  21421. excludeShallow: config.excludeShallow,
  21422. insertRequire: config.insertRequire,
  21423. stubModules: config.stubModules
  21424. }
  21425. ];
  21426. delete config.stubModules;
  21427. } else if (config.modules && config.out) {
  21428. throw new Error('If the "modules" option is used, then there ' +
  21429. 'should be a "dir" option set and "out" should ' +
  21430. 'not be used since "out" is only for single file ' +
  21431. 'optimization output.');
  21432. } else if (config.modules && config.name) {
  21433. throw new Error('"name" and "modules" options are incompatible. ' +
  21434. 'Either use "name" if doing a single file ' +
  21435. 'optimization, or "modules" if you want to target ' +
  21436. 'more than one file for optimization.');
  21437. }
  21438. if (config.out && !config.cssIn) {
  21439. //Just one file to optimize.
  21440. //Does not have a build file, so set up some defaults.
  21441. //Optimizing CSS should not be allowed, unless explicitly
  21442. //asked for on command line. In that case the only task is
  21443. //to optimize a CSS file.
  21444. if (!cfg.optimizeCss) {
  21445. config.optimizeCss = "none";
  21446. }
  21447. }
  21448. //Normalize cssPrefix
  21449. if (config.cssPrefix) {
  21450. //Make sure cssPrefix ends in a slash
  21451. config.cssPrefix = endsWithSlash(config.cssPrefix);
  21452. } else {
  21453. config.cssPrefix = '';
  21454. }
  21455. //Cycle through modules and combine any local stubModules with
  21456. //global values.
  21457. if (config.modules && config.modules.length) {
  21458. config.modules.forEach(function (mod) {
  21459. if (config.stubModules) {
  21460. mod.stubModules = config.stubModules.concat(mod.stubModules || []);
  21461. }
  21462. //Create a hash lookup for the stubModules config to make lookup
  21463. //cheaper later.
  21464. if (mod.stubModules) {
  21465. mod.stubModules._byName = {};
  21466. mod.stubModules.forEach(function (id) {
  21467. mod.stubModules._byName[id] = true;
  21468. });
  21469. }
  21470. });
  21471. }
  21472. //Get any wrap text.
  21473. try {
  21474. if (config.wrap) {
  21475. if (config.wrap === true) {
  21476. //Use default values.
  21477. config.wrap = {
  21478. start: '(function () {',
  21479. end: '}());'
  21480. };
  21481. } else {
  21482. flattenWrapFile(config.wrap, 'start', absFilePath);
  21483. flattenWrapFile(config.wrap, 'end', absFilePath);
  21484. }
  21485. }
  21486. } catch (wrapError) {
  21487. throw new Error('Malformed wrap config: ' + wrapError.toString());
  21488. }
  21489. //Do final input verification
  21490. if (config.context) {
  21491. throw new Error('The build argument "context" is not supported' +
  21492. ' in a build. It should only be used in web' +
  21493. ' pages.');
  21494. }
  21495. //Set up normalizeDirDefines. If not explicitly set, if optimize "none",
  21496. //set to "skip" otherwise set to "all".
  21497. if (!hasProp(config, 'normalizeDirDefines')) {
  21498. if (config.optimize === 'none' || config.skipDirOptimize) {
  21499. config.normalizeDirDefines = 'skip';
  21500. } else {
  21501. config.normalizeDirDefines = 'all';
  21502. }
  21503. }
  21504. //Set file.fileExclusionRegExp if desired
  21505. if (hasProp(config, 'fileExclusionRegExp')) {
  21506. if (typeof config.fileExclusionRegExp === "string") {
  21507. file.exclusionRegExp = new RegExp(config.fileExclusionRegExp);
  21508. } else {
  21509. file.exclusionRegExp = config.fileExclusionRegExp;
  21510. }
  21511. } else if (hasProp(config, 'dirExclusionRegExp')) {
  21512. //Set file.dirExclusionRegExp if desired, this is the old
  21513. //name for fileExclusionRegExp before 1.0.2. Support for backwards
  21514. //compatibility
  21515. file.exclusionRegExp = config.dirExclusionRegExp;
  21516. }
  21517. //Remove things that may cause problems in the build.
  21518. delete config.jQuery;
  21519. delete config.enforceDefine;
  21520. delete config.urlArgs;
  21521. return config;
  21522. };
  21523. /**
  21524. * finds the module being built/optimized with the given moduleName,
  21525. * or returns null.
  21526. * @param {String} moduleName
  21527. * @param {Array} modules
  21528. * @returns {Object} the module object from the build profile, or null.
  21529. */
  21530. build.findBuildModule = function (moduleName, modules) {
  21531. var i, module;
  21532. for (i = 0; i < modules.length; i++) {
  21533. module = modules[i];
  21534. if (module.name === moduleName) {
  21535. return module;
  21536. }
  21537. }
  21538. return null;
  21539. };
  21540. /**
  21541. * Removes a module name and path from a layer, if it is supposed to be
  21542. * excluded from the layer.
  21543. * @param {String} moduleName the name of the module
  21544. * @param {String} path the file path for the module
  21545. * @param {Object} layer the layer to remove the module/path from
  21546. */
  21547. build.removeModulePath = function (module, path, layer) {
  21548. var index = layer.buildFilePaths.indexOf(path);
  21549. if (index !== -1) {
  21550. layer.buildFilePaths.splice(index, 1);
  21551. }
  21552. };
  21553. /**
  21554. * Uses the module build config object to trace the dependencies for the
  21555. * given module.
  21556. *
  21557. * @param {Object} module the module object from the build config info.
  21558. * @param {Object} the build config object.
  21559. *
  21560. * @returns {Object} layer information about what paths and modules should
  21561. * be in the flattened module.
  21562. */
  21563. build.traceDependencies = function (module, config) {
  21564. var include, override, layer, context, baseConfig, oldContext,
  21565. rawTextByIds,
  21566. syncChecks = {
  21567. rhino: true,
  21568. node: true,
  21569. xpconnect: true
  21570. },
  21571. deferred = prim();
  21572. //Reset some state set up in requirePatch.js, and clean up require's
  21573. //current context.
  21574. oldContext = require._buildReset();
  21575. //Grab the reset layer and context after the reset, but keep the
  21576. //old config to reuse in the new context.
  21577. baseConfig = oldContext.config;
  21578. layer = require._layer;
  21579. context = layer.context;
  21580. //Put back basic config, use a fresh object for it.
  21581. //WARNING: probably not robust for paths and packages/packagePaths,
  21582. //since those property's objects can be modified. But for basic
  21583. //config clone it works out.
  21584. require(lang.mixin({}, baseConfig, true));
  21585. logger.trace("\nTracing dependencies for: " + (module.name || module.out));
  21586. include = module.name && !module.create ? [module.name] : [];
  21587. if (module.include) {
  21588. include = include.concat(module.include);
  21589. }
  21590. //If there are overrides to basic config, set that up now.;
  21591. if (module.override) {
  21592. override = lang.mixin({}, baseConfig, true);
  21593. lang.mixin(override, module.override, true);
  21594. require(override);
  21595. }
  21596. //Now, populate the rawText cache with any values explicitly passed in
  21597. //via config.
  21598. rawTextByIds = require.s.contexts._.config.rawText;
  21599. if (rawTextByIds) {
  21600. lang.eachProp(rawTextByIds, function (contents, id) {
  21601. var url = require.toUrl(id) + '.js';
  21602. require._cachedRawText[url] = contents;
  21603. });
  21604. }
  21605. //Figure out module layer dependencies by calling require to do the work.
  21606. //Configure the callbacks to be called.
  21607. deferred.resolve.__requireJsBuild = true;
  21608. deferred.reject.__requireJsBuild = true;
  21609. require(include, deferred.resolve, deferred.reject);
  21610. //If a sync build environment, check for errors here, instead of
  21611. //in the then callback below, since some errors, like two IDs pointed
  21612. //to same URL but only one anon ID will leave the loader in an
  21613. //unresolved state since a setTimeout cannot be used to check for
  21614. //timeout.
  21615. if (syncChecks[env.get()]) {
  21616. try {
  21617. build.checkForErrors(context);
  21618. } catch (e) {
  21619. deferred.reject(e);
  21620. }
  21621. }
  21622. return deferred.promise.then(function () {
  21623. //Reset config
  21624. if (module.override) {
  21625. require(baseConfig);
  21626. }
  21627. build.checkForErrors(context);
  21628. return layer;
  21629. });
  21630. };
  21631. build.checkForErrors = function (context) {
  21632. //Check to see if it all loaded. If not, then throw, and give
  21633. //a message on what is left.
  21634. var id, prop, mod, errUrl, idParts, pluginId,
  21635. errMessage = '',
  21636. failedPluginMap = {},
  21637. failedPluginIds = [],
  21638. errIds = [],
  21639. errUrlMap = {},
  21640. errUrlConflicts = {},
  21641. hasErrUrl = false,
  21642. registry = context.registry;
  21643. for (id in registry) {
  21644. if (hasProp(registry, id) && id.indexOf('_@r') !== 0) {
  21645. mod = getOwn(registry, id);
  21646. if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) {
  21647. errIds.push(id);
  21648. errUrl = mod.map.url;
  21649. if (errUrlMap[errUrl]) {
  21650. hasErrUrl = true;
  21651. //This error module has the same URL as another
  21652. //error module, could be misconfiguration.
  21653. if (!errUrlConflicts[errUrl]) {
  21654. errUrlConflicts[errUrl] = [];
  21655. //Store the original module that had the same URL.
  21656. errUrlConflicts[errUrl].push(errUrlMap[errUrl]);
  21657. }
  21658. errUrlConflicts[errUrl].push(id);
  21659. } else {
  21660. errUrlMap[errUrl] = id;
  21661. }
  21662. }
  21663. //Look for plugins that did not call load()
  21664. idParts = id.split('!');
  21665. pluginId = idParts[0];
  21666. if (idParts.length > 1 && falseProp(failedPluginMap, pluginId)) {
  21667. failedPluginIds.push(pluginId);
  21668. failedPluginMap[pluginId] = true;
  21669. }
  21670. }
  21671. }
  21672. if (errIds.length || failedPluginIds.length) {
  21673. if (failedPluginIds.length) {
  21674. errMessage += 'Loader plugin' +
  21675. (failedPluginIds.length === 1 ? '' : 's') +
  21676. ' did not call ' +
  21677. 'the load callback in the build: ' +
  21678. failedPluginIds.join(', ') + '\n';
  21679. }
  21680. errMessage += 'Module loading did not complete for: ' + errIds.join(', ');
  21681. if (hasErrUrl) {
  21682. errMessage += '\nThe following modules share the same URL. This ' +
  21683. 'could be a misconfiguration if that URL only has ' +
  21684. 'one anonymous module in it:';
  21685. for (prop in errUrlConflicts) {
  21686. if (hasProp(errUrlConflicts, prop)) {
  21687. errMessage += '\n' + prop + ': ' +
  21688. errUrlConflicts[prop].join(', ');
  21689. }
  21690. }
  21691. }
  21692. throw new Error(errMessage);
  21693. }
  21694. };
  21695. build.createOverrideConfig = function (config, override) {
  21696. var cfg = {};
  21697. lang.mixin(cfg, config, true);
  21698. lang.eachProp(override, function (value, prop) {
  21699. if (hasProp(build.objProps, prop)) {
  21700. //An object property, merge keys. Start a new object
  21701. //so that source object in config does not get modified.
  21702. cfg[prop] = {};
  21703. lang.mixin(cfg[prop], config[prop], true);
  21704. lang.mixin(cfg[prop], override[prop], true);
  21705. } else {
  21706. cfg[prop] = override[prop];
  21707. }
  21708. });
  21709. return cfg;
  21710. };
  21711. /**
  21712. * Uses the module build config object to create an flattened version
  21713. * of the module, with deep dependencies included.
  21714. *
  21715. * @param {Object} module the module object from the build config info.
  21716. *
  21717. * @param {Object} layer the layer object returned from build.traceDependencies.
  21718. *
  21719. * @param {Object} the build config object.
  21720. *
  21721. * @returns {Object} with two properties: "text", the text of the flattened
  21722. * module, and "buildText", a string of text representing which files were
  21723. * included in the flattened module text.
  21724. */
  21725. build.flattenModule = function (module, layer, config) {
  21726. var fileContents,
  21727. buildFileContents = '';
  21728. return prim().start(function () {
  21729. var reqIndex, currContents,
  21730. moduleName, shim, packageConfig, nonPackageName,
  21731. parts, builder, writeApi,
  21732. namespace, namespaceWithDot, stubModulesByName,
  21733. context = layer.context,
  21734. onLayerEnds = [],
  21735. onLayerEndAdded = {};
  21736. //Use override settings, particularly for pragmas
  21737. //Do this before the var readings since it reads config values.
  21738. if (module.override) {
  21739. config = build.createOverrideConfig(config, module.override);
  21740. }
  21741. namespace = config.namespace || '';
  21742. namespaceWithDot = namespace ? namespace + '.' : '';
  21743. stubModulesByName = (module.stubModules && module.stubModules._byName) || {};
  21744. //Start build output for the module.
  21745. buildFileContents += "\n" +
  21746. (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath) +
  21747. "\n----------------\n";
  21748. //If there was an existing file with require in it, hoist to the top.
  21749. if (layer.existingRequireUrl) {
  21750. reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl);
  21751. if (reqIndex !== -1) {
  21752. layer.buildFilePaths.splice(reqIndex, 1);
  21753. layer.buildFilePaths.unshift(layer.existingRequireUrl);
  21754. }
  21755. }
  21756. //Write the built module to disk, and build up the build output.
  21757. fileContents = "";
  21758. return prim.serial(layer.buildFilePaths.map(function (path) {
  21759. return function () {
  21760. moduleName = layer.buildFileToModule[path];
  21761. //If the moduleName is for a package main, then update it to the
  21762. //real main value.
  21763. packageConfig = layer.context.config.pkgs &&
  21764. getOwn(layer.context.config.pkgs, moduleName);
  21765. if (packageConfig) {
  21766. nonPackageName = moduleName;
  21767. moduleName += '/' + packageConfig.main;
  21768. }
  21769. return prim().start(function () {
  21770. //Figure out if the module is a result of a build plugin, and if so,
  21771. //then delegate to that plugin.
  21772. parts = context.makeModuleMap(moduleName);
  21773. builder = parts.prefix && getOwn(context.defined, parts.prefix);
  21774. if (builder) {
  21775. if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) {
  21776. onLayerEnds.push(builder);
  21777. onLayerEndAdded[parts.prefix] = true;
  21778. }
  21779. if (builder.write) {
  21780. writeApi = function (input) {
  21781. fileContents += "\n" + addSemiColon(input);
  21782. if (config.onBuildWrite) {
  21783. fileContents = config.onBuildWrite(moduleName, path, fileContents);
  21784. }
  21785. };
  21786. writeApi.asModule = function (moduleName, input) {
  21787. fileContents += "\n" +
  21788. addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, {
  21789. useSourceUrl: layer.context.config.useSourceUrl
  21790. }));
  21791. if (config.onBuildWrite) {
  21792. fileContents = config.onBuildWrite(moduleName, path, fileContents);
  21793. }
  21794. };
  21795. builder.write(parts.prefix, parts.name, writeApi);
  21796. }
  21797. return;
  21798. } else {
  21799. return prim().start(function () {
  21800. if (hasProp(stubModulesByName, moduleName)) {
  21801. //Just want to insert a simple module definition instead
  21802. //of the source module. Useful for plugins that inline
  21803. //all their resources.
  21804. if (hasProp(layer.context.plugins, moduleName)) {
  21805. //Slightly different content for plugins, to indicate
  21806. //that dynamic loading will not work.
  21807. return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});';
  21808. } else {
  21809. return 'define({});';
  21810. }
  21811. } else {
  21812. return require._cacheReadAsync(path);
  21813. }
  21814. }).then(function (text) {
  21815. var hasPackageName;
  21816. currContents = text;
  21817. if (config.cjsTranslate) {
  21818. currContents = commonJs.convert(path, currContents);
  21819. }
  21820. if (config.onBuildRead) {
  21821. currContents = config.onBuildRead(moduleName, path, currContents);
  21822. }
  21823. if (packageConfig) {
  21824. hasPackageName = (nonPackageName === parse.getNamedDefine(currContents));
  21825. }
  21826. if (namespace) {
  21827. currContents = pragma.namespace(currContents, namespace);
  21828. }
  21829. currContents = build.toTransport(namespace, moduleName, path, currContents, layer, {
  21830. useSourceUrl: config.useSourceUrl
  21831. });
  21832. if (packageConfig && !hasPackageName) {
  21833. currContents = addSemiColon(currContents) + '\n';
  21834. currContents += namespaceWithDot + "define('" +
  21835. packageConfig.name + "', ['" + moduleName +
  21836. "'], function (main) { return main; });\n";
  21837. }
  21838. if (config.onBuildWrite) {
  21839. currContents = config.onBuildWrite(moduleName, path, currContents);
  21840. }
  21841. //Semicolon is for files that are not well formed when
  21842. //concatenated with other content.
  21843. fileContents += "\n" + addSemiColon(currContents);
  21844. });
  21845. }
  21846. }).then(function () {
  21847. buildFileContents += path.replace(config.dir, "") + "\n";
  21848. //Some files may not have declared a require module, and if so,
  21849. //put in a placeholder call so the require does not try to load them
  21850. //after the module is processed.
  21851. //If we have a name, but no defined module, then add in the placeholder.
  21852. if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) {
  21853. shim = config.shim && (getOwn(config.shim, moduleName) || (packageConfig && getOwn(config.shim, nonPackageName)));
  21854. if (shim) {
  21855. fileContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' +
  21856. (shim.deps && shim.deps.length ?
  21857. build.makeJsArrayString(shim.deps) + ', ' : '') +
  21858. (shim.exportsFn ? shim.exportsFn() : 'function(){}') +
  21859. ');\n';
  21860. } else {
  21861. fileContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n';
  21862. }
  21863. }
  21864. });
  21865. };
  21866. })).then(function () {
  21867. if (onLayerEnds.length) {
  21868. onLayerEnds.forEach(function (builder) {
  21869. var path;
  21870. if (typeof module.out === 'string') {
  21871. path = module.out;
  21872. } else if (typeof module._buildPath === 'string') {
  21873. path = module._buildPath;
  21874. }
  21875. builder.onLayerEnd(function (input) {
  21876. fileContents += "\n" + addSemiColon(input);
  21877. }, {
  21878. name: module.name,
  21879. path: path
  21880. });
  21881. });
  21882. }
  21883. //Add a require at the end to kick start module execution, if that
  21884. //was desired. Usually this is only specified when using small shim
  21885. //loaders like almond.
  21886. if (module.insertRequire) {
  21887. fileContents += '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') + '"]);\n';
  21888. }
  21889. });
  21890. }).then(function () {
  21891. return {
  21892. text: config.wrap ?
  21893. config.wrap.start + fileContents + config.wrap.end :
  21894. fileContents,
  21895. buildText: buildFileContents
  21896. };
  21897. });
  21898. };
  21899. //Converts an JS array of strings to a string representation.
  21900. //Not using JSON.stringify() for Rhino's sake.
  21901. build.makeJsArrayString = function (ary) {
  21902. return '["' + ary.map(function (item) {
  21903. //Escape any double quotes, backslashes
  21904. return lang.jsEscape(item);
  21905. }).join('","') + '"]';
  21906. };
  21907. build.toTransport = function (namespace, moduleName, path, contents, layer, options) {
  21908. var baseUrl = layer && layer.context.config.baseUrl;
  21909. function onFound(info) {
  21910. //Only mark this module as having a name if not a named module,
  21911. //or if a named module and the name matches expectations.
  21912. if (layer && (info.needsId || info.foundId === moduleName)) {
  21913. layer.modulesWithNames[moduleName] = true;
  21914. }
  21915. }
  21916. //Convert path to be a local one to the baseUrl, useful for
  21917. //useSourceUrl.
  21918. if (baseUrl) {
  21919. path = path.replace(baseUrl, '');
  21920. }
  21921. return transform.toTransport(namespace, moduleName, path, contents, onFound, options);
  21922. };
  21923. return build;
  21924. });
  21925. }
  21926. /**
  21927. * Sets the default baseUrl for requirejs to be directory of top level
  21928. * script.
  21929. */
  21930. function setBaseUrl(fileName) {
  21931. //Use the file name's directory as the baseUrl if available.
  21932. dir = fileName.replace(/\\/g, '/');
  21933. if (dir.indexOf('/') !== -1) {
  21934. dir = dir.split('/');
  21935. dir.pop();
  21936. dir = dir.join('/');
  21937. exec("require({baseUrl: '" + dir + "'});");
  21938. }
  21939. }
  21940. function createRjsApi() {
  21941. //Create a method that will run the optimzer given an object
  21942. //config.
  21943. requirejs.optimize = function (config, callback, errback) {
  21944. if (!loadedOptimizedLib) {
  21945. loadLib();
  21946. loadedOptimizedLib = true;
  21947. }
  21948. //Create the function that will be called once build modules
  21949. //have been loaded.
  21950. var runBuild = function (build, logger) {
  21951. //Make sure config has a log level, and if not,
  21952. //make it "silent" by default.
  21953. config.logLevel = config.hasOwnProperty('logLevel') ?
  21954. config.logLevel : logger.SILENT;
  21955. //Reset build internals first in case this is part
  21956. //of a long-running server process that could have
  21957. //exceptioned out in a bad state. It is only defined
  21958. //after the first call though.
  21959. if (requirejs._buildReset) {
  21960. requirejs._buildReset();
  21961. requirejs._cacheReset();
  21962. }
  21963. function done(result) {
  21964. //And clean up, in case something else triggers
  21965. //a build in another pathway.
  21966. if (requirejs._buildReset) {
  21967. requirejs._buildReset();
  21968. requirejs._cacheReset();
  21969. }
  21970. // Ensure errors get propagated to the errback
  21971. if (result instanceof Error) {
  21972. throw result;
  21973. }
  21974. return result;
  21975. }
  21976. build(config).then(done, done).then(callback, errback);
  21977. };
  21978. requirejs({
  21979. context: 'build'
  21980. }, ['build', 'logger'], runBuild);
  21981. };
  21982. requirejs.tools = {
  21983. useLib: function (contextName, callback) {
  21984. if (!callback) {
  21985. callback = contextName;
  21986. contextName = 'uselib';
  21987. }
  21988. if (!useLibLoaded[contextName]) {
  21989. loadLib();
  21990. useLibLoaded[contextName] = true;
  21991. }
  21992. var req = requirejs({
  21993. context: contextName
  21994. });
  21995. req(['build'], function () {
  21996. callback(req);
  21997. });
  21998. }
  21999. };
  22000. requirejs.define = define;
  22001. }
  22002. //If in Node, and included via a require('requirejs'), just export and
  22003. //THROW IT ON THE GROUND!
  22004. if (env === 'node' && reqMain !== module) {
  22005. setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.'));
  22006. createRjsApi();
  22007. module.exports = requirejs;
  22008. return;
  22009. } else if (env === 'browser') {
  22010. //Only option is to use the API.
  22011. setBaseUrl(location.href);
  22012. createRjsApi();
  22013. return;
  22014. } else if ((env === 'rhino' || env === 'xpconnect') &&
  22015. //User sets up requirejsAsLib variable to indicate it is loaded
  22016. //via load() to be used as a library.
  22017. typeof requirejsAsLib !== 'undefined' && requirejsAsLib) {
  22018. //This script is loaded via rhino's load() method, expose the
  22019. //API and get out.
  22020. setBaseUrl(fileName);
  22021. createRjsApi();
  22022. return;
  22023. }
  22024. if (commandOption === 'o') {
  22025. //Do the optimizer work.
  22026. loadLib();
  22027. /**
  22028. * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
  22029. * Available via the MIT or new BSD license.
  22030. * see: http://github.com/jrburke/requirejs for details
  22031. */
  22032. /*
  22033. * Create a build.js file that has the build options you want and pass that
  22034. * build file to this file to do the build. See example.build.js for more information.
  22035. */
  22036. /*jslint strict: false, nomen: false */
  22037. /*global require: false */
  22038. require({
  22039. baseUrl: require.s.contexts._.config.baseUrl,
  22040. //Use a separate context than the default context so that the
  22041. //build can use the default context.
  22042. context: 'build',
  22043. catchError: {
  22044. define: true
  22045. }
  22046. }, ['env!env/args', 'build'],
  22047. function (args, build) {
  22048. build(args);
  22049. });
  22050. } else if (commandOption === 'v') {
  22051. console.log('r.js: ' + version + ', RequireJS: ' + this.requirejsVars.require.version);
  22052. } else if (commandOption === 'convert') {
  22053. loadLib();
  22054. this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'],
  22055. function (args, commonJs, print) {
  22056. var srcDir, outDir;
  22057. srcDir = args[0];
  22058. outDir = args[1];
  22059. if (!srcDir || !outDir) {
  22060. print('Usage: path/to/commonjs/modules output/dir');
  22061. return;
  22062. }
  22063. commonJs.convertDir(args[0], args[1]);
  22064. });
  22065. } else {
  22066. //Just run an app
  22067. //Load the bundled libraries for use in the app.
  22068. if (commandOption === 'lib') {
  22069. loadLib();
  22070. }
  22071. setBaseUrl(fileName);
  22072. if (exists(fileName)) {
  22073. exec(readFile(fileName), fileName);
  22074. } else {
  22075. showHelp();
  22076. }
  22077. }
  22078. }((typeof console !== 'undefined' ? console : undefined),
  22079. (typeof Packages !== 'undefined' || (typeof window === 'undefined' &&
  22080. typeof Components !== 'undefined' && Components.interfaces) ?
  22081. Array.prototype.slice.call(arguments, 0) : []),
  22082. (typeof readFile !== 'undefined' ? readFile : undefined)));