vendors~main.28bb9bf067b35b9514f7.js 1002 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735
  1. (window["webpackJsonpivprogCore"] = window["webpackJsonpivprogCore"] || []).push([["vendors~main"],{
  2. /***/ "./node_modules/antlr4/BufferedTokenStream.js":
  3. /*!****************************************************!*\
  4. !*** ./node_modules/antlr4/BufferedTokenStream.js ***!
  5. \****************************************************/
  6. /*! no static exports found */
  7. /***/ (function(module, exports, __webpack_require__) {
  8. //
  9. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  10. * Use of this file is governed by the BSD 3-clause license that
  11. * can be found in the LICENSE.txt file in the project root.
  12. */
  13. // This implementation of {@link TokenStream} loads tokens from a
  14. // {@link TokenSource} on-demand, and places the tokens in a buffer to provide
  15. // access to any previous token by index.
  16. //
  17. // <p>
  18. // This token stream ignores the value of {@link Token//getChannel}. If your
  19. // parser requires the token stream filter tokens to only those on a particular
  20. // channel, such as {@link Token//DEFAULT_CHANNEL} or
  21. // {@link Token//HIDDEN_CHANNEL}, use a filtering token stream such a
  22. // {@link CommonTokenStream}.</p>
  23. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  24. var Lexer = __webpack_require__(/*! ./Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
  25. var Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  26. // this is just to keep meaningful parameter types to Parser
  27. function TokenStream() {
  28. return this;
  29. }
  30. function BufferedTokenStream(tokenSource) {
  31. TokenStream.call(this);
  32. // The {@link TokenSource} from which tokens for this stream are fetched.
  33. this.tokenSource = tokenSource;
  34. // A collection of all tokens fetched from the token source. The list is
  35. // considered a complete view of the input once {@link //fetchedEOF} is set
  36. // to {@code true}.
  37. this.tokens = [];
  38. // The index into {@link //tokens} of the current token (next token to
  39. // {@link //consume}). {@link //tokens}{@code [}{@link //p}{@code ]} should
  40. // be
  41. // {@link //LT LT(1)}.
  42. //
  43. // <p>This field is set to -1 when the stream is first constructed or when
  44. // {@link //setTokenSource} is called, indicating that the first token has
  45. // not yet been fetched from the token source. For additional information,
  46. // see the documentation of {@link IntStream} for a description of
  47. // Initializing Methods.</p>
  48. this.index = -1;
  49. // Indicates whether the {@link Token//EOF} token has been fetched from
  50. // {@link //tokenSource} and added to {@link //tokens}. This field improves
  51. // performance for the following cases:
  52. //
  53. // <ul>
  54. // <li>{@link //consume}: The lookahead check in {@link //consume} to
  55. // prevent
  56. // consuming the EOF symbol is optimized by checking the values of
  57. // {@link //fetchedEOF} and {@link //p} instead of calling {@link
  58. // //LA}.</li>
  59. // <li>{@link //fetch}: The check to prevent adding multiple EOF symbols
  60. // into
  61. // {@link //tokens} is trivial with this field.</li>
  62. // <ul>
  63. this.fetchedEOF = false;
  64. return this;
  65. }
  66. BufferedTokenStream.prototype = Object.create(TokenStream.prototype);
  67. BufferedTokenStream.prototype.constructor = BufferedTokenStream;
  68. BufferedTokenStream.prototype.mark = function() {
  69. return 0;
  70. };
  71. BufferedTokenStream.prototype.release = function(marker) {
  72. // no resources to release
  73. };
  74. BufferedTokenStream.prototype.reset = function() {
  75. this.seek(0);
  76. };
  77. BufferedTokenStream.prototype.seek = function(index) {
  78. this.lazyInit();
  79. this.index = this.adjustSeekIndex(index);
  80. };
  81. BufferedTokenStream.prototype.get = function(index) {
  82. this.lazyInit();
  83. return this.tokens[index];
  84. };
  85. BufferedTokenStream.prototype.consume = function() {
  86. var skipEofCheck = false;
  87. if (this.index >= 0) {
  88. if (this.fetchedEOF) {
  89. // the last token in tokens is EOF. skip check if p indexes any
  90. // fetched token except the last.
  91. skipEofCheck = this.index < this.tokens.length - 1;
  92. } else {
  93. // no EOF token in tokens. skip check if p indexes a fetched token.
  94. skipEofCheck = this.index < this.tokens.length;
  95. }
  96. } else {
  97. // not yet initialized
  98. skipEofCheck = false;
  99. }
  100. if (!skipEofCheck && this.LA(1) === Token.EOF) {
  101. throw "cannot consume EOF";
  102. }
  103. if (this.sync(this.index + 1)) {
  104. this.index = this.adjustSeekIndex(this.index + 1);
  105. }
  106. };
  107. // Make sure index {@code i} in tokens has a token.
  108. //
  109. // @return {@code true} if a token is located at index {@code i}, otherwise
  110. // {@code false}.
  111. // @see //get(int i)
  112. // /
  113. BufferedTokenStream.prototype.sync = function(i) {
  114. var n = i - this.tokens.length + 1; // how many more elements we need?
  115. if (n > 0) {
  116. var fetched = this.fetch(n);
  117. return fetched >= n;
  118. }
  119. return true;
  120. };
  121. // Add {@code n} elements to buffer.
  122. //
  123. // @return The actual number of elements added to the buffer.
  124. // /
  125. BufferedTokenStream.prototype.fetch = function(n) {
  126. if (this.fetchedEOF) {
  127. return 0;
  128. }
  129. for (var i = 0; i < n; i++) {
  130. var t = this.tokenSource.nextToken();
  131. t.tokenIndex = this.tokens.length;
  132. this.tokens.push(t);
  133. if (t.type === Token.EOF) {
  134. this.fetchedEOF = true;
  135. return i + 1;
  136. }
  137. }
  138. return n;
  139. };
  140. // Get all tokens from start..stop inclusively///
  141. BufferedTokenStream.prototype.getTokens = function(start, stop, types) {
  142. if (types === undefined) {
  143. types = null;
  144. }
  145. if (start < 0 || stop < 0) {
  146. return null;
  147. }
  148. this.lazyInit();
  149. var subset = [];
  150. if (stop >= this.tokens.length) {
  151. stop = this.tokens.length - 1;
  152. }
  153. for (var i = start; i < stop; i++) {
  154. var t = this.tokens[i];
  155. if (t.type === Token.EOF) {
  156. break;
  157. }
  158. if (types === null || types.contains(t.type)) {
  159. subset.push(t);
  160. }
  161. }
  162. return subset;
  163. };
  164. BufferedTokenStream.prototype.LA = function(i) {
  165. return this.LT(i).type;
  166. };
  167. BufferedTokenStream.prototype.LB = function(k) {
  168. if (this.index - k < 0) {
  169. return null;
  170. }
  171. return this.tokens[this.index - k];
  172. };
  173. BufferedTokenStream.prototype.LT = function(k) {
  174. this.lazyInit();
  175. if (k === 0) {
  176. return null;
  177. }
  178. if (k < 0) {
  179. return this.LB(-k);
  180. }
  181. var i = this.index + k - 1;
  182. this.sync(i);
  183. if (i >= this.tokens.length) { // return EOF token
  184. // EOF must be last token
  185. return this.tokens[this.tokens.length - 1];
  186. }
  187. return this.tokens[i];
  188. };
  189. // Allowed derived classes to modify the behavior of operations which change
  190. // the current stream position by adjusting the target token index of a seek
  191. // operation. The default implementation simply returns {@code i}. If an
  192. // exception is thrown in this method, the current stream index should not be
  193. // changed.
  194. //
  195. // <p>For example, {@link CommonTokenStream} overrides this method to ensure
  196. // that
  197. // the seek target is always an on-channel token.</p>
  198. //
  199. // @param i The target token index.
  200. // @return The adjusted target token index.
  201. BufferedTokenStream.prototype.adjustSeekIndex = function(i) {
  202. return i;
  203. };
  204. BufferedTokenStream.prototype.lazyInit = function() {
  205. if (this.index === -1) {
  206. this.setup();
  207. }
  208. };
  209. BufferedTokenStream.prototype.setup = function() {
  210. this.sync(0);
  211. this.index = this.adjustSeekIndex(0);
  212. };
  213. // Reset this token stream by setting its token source.///
  214. BufferedTokenStream.prototype.setTokenSource = function(tokenSource) {
  215. this.tokenSource = tokenSource;
  216. this.tokens = [];
  217. this.index = -1;
  218. this.fetchedEOF = false;
  219. };
  220. // Given a starting index, return the index of the next token on channel.
  221. // Return i if tokens[i] is on channel. Return -1 if there are no tokens
  222. // on channel between i and EOF.
  223. // /
  224. BufferedTokenStream.prototype.nextTokenOnChannel = function(i, channel) {
  225. this.sync(i);
  226. if (i >= this.tokens.length) {
  227. return -1;
  228. }
  229. var token = this.tokens[i];
  230. while (token.channel !== this.channel) {
  231. if (token.type === Token.EOF) {
  232. return -1;
  233. }
  234. i += 1;
  235. this.sync(i);
  236. token = this.tokens[i];
  237. }
  238. return i;
  239. };
  240. // Given a starting index, return the index of the previous token on channel.
  241. // Return i if tokens[i] is on channel. Return -1 if there are no tokens
  242. // on channel between i and 0.
  243. BufferedTokenStream.prototype.previousTokenOnChannel = function(i, channel) {
  244. while (i >= 0 && this.tokens[i].channel !== channel) {
  245. i -= 1;
  246. }
  247. return i;
  248. };
  249. // Collect all tokens on specified channel to the right of
  250. // the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or
  251. // EOF. If channel is -1, find any non default channel token.
  252. BufferedTokenStream.prototype.getHiddenTokensToRight = function(tokenIndex,
  253. channel) {
  254. if (channel === undefined) {
  255. channel = -1;
  256. }
  257. this.lazyInit();
  258. if (tokenIndex < 0 || tokenIndex >= this.tokens.length) {
  259. throw "" + tokenIndex + " not in 0.." + this.tokens.length - 1;
  260. }
  261. var nextOnChannel = this.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL);
  262. var from_ = tokenIndex + 1;
  263. // if none onchannel to right, nextOnChannel=-1 so set to = last token
  264. var to = nextOnChannel === -1 ? this.tokens.length - 1 : nextOnChannel;
  265. return this.filterForChannel(from_, to, channel);
  266. };
  267. // Collect all tokens on specified channel to the left of
  268. // the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.
  269. // If channel is -1, find any non default channel token.
  270. BufferedTokenStream.prototype.getHiddenTokensToLeft = function(tokenIndex,
  271. channel) {
  272. if (channel === undefined) {
  273. channel = -1;
  274. }
  275. this.lazyInit();
  276. if (tokenIndex < 0 || tokenIndex >= this.tokens.length) {
  277. throw "" + tokenIndex + " not in 0.." + this.tokens.length - 1;
  278. }
  279. var prevOnChannel = this.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL);
  280. if (prevOnChannel === tokenIndex - 1) {
  281. return null;
  282. }
  283. // if none on channel to left, prevOnChannel=-1 then from=0
  284. var from_ = prevOnChannel + 1;
  285. var to = tokenIndex - 1;
  286. return this.filterForChannel(from_, to, channel);
  287. };
  288. BufferedTokenStream.prototype.filterForChannel = function(left, right, channel) {
  289. var hidden = [];
  290. for (var i = left; i < right + 1; i++) {
  291. var t = this.tokens[i];
  292. if (channel === -1) {
  293. if (t.channel !== Lexer.DEFAULT_TOKEN_CHANNEL) {
  294. hidden.push(t);
  295. }
  296. } else if (t.channel === channel) {
  297. hidden.push(t);
  298. }
  299. }
  300. if (hidden.length === 0) {
  301. return null;
  302. }
  303. return hidden;
  304. };
  305. BufferedTokenStream.prototype.getSourceName = function() {
  306. return this.tokenSource.getSourceName();
  307. };
  308. // Get the text of all tokens in this buffer.///
  309. BufferedTokenStream.prototype.getText = function(interval) {
  310. this.lazyInit();
  311. this.fill();
  312. if (interval === undefined || interval === null) {
  313. interval = new Interval(0, this.tokens.length - 1);
  314. }
  315. var start = interval.start;
  316. if (start instanceof Token) {
  317. start = start.tokenIndex;
  318. }
  319. var stop = interval.stop;
  320. if (stop instanceof Token) {
  321. stop = stop.tokenIndex;
  322. }
  323. if (start === null || stop === null || start < 0 || stop < 0) {
  324. return "";
  325. }
  326. if (stop >= this.tokens.length) {
  327. stop = this.tokens.length - 1;
  328. }
  329. var s = "";
  330. for (var i = start; i < stop + 1; i++) {
  331. var t = this.tokens[i];
  332. if (t.type === Token.EOF) {
  333. break;
  334. }
  335. s = s + t.text;
  336. }
  337. return s;
  338. };
  339. // Get all tokens from lexer until EOF///
  340. BufferedTokenStream.prototype.fill = function() {
  341. this.lazyInit();
  342. while (this.fetch(1000) === 1000) {
  343. continue;
  344. }
  345. };
  346. exports.BufferedTokenStream = BufferedTokenStream;
  347. /***/ }),
  348. /***/ "./node_modules/antlr4/CharStreams.js":
  349. /*!********************************************!*\
  350. !*** ./node_modules/antlr4/CharStreams.js ***!
  351. \********************************************/
  352. /*! no static exports found */
  353. /***/ (function(module, exports, __webpack_require__) {
  354. //
  355. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  356. * Use of this file is governed by the BSD 3-clause license that
  357. * can be found in the LICENSE.txt file in the project root.
  358. */
  359. //
  360. var InputStream = __webpack_require__(/*! ./InputStream */ "./node_modules/antlr4/InputStream.js").InputStream;
  361. var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined';
  362. var fs = isNodeJs ? __webpack_require__(/*! fs */ "./node_modules/node-libs-browser/mock/empty.js") : null;
  363. // Utility functions to create InputStreams from various sources.
  364. //
  365. // All returned InputStreams support the full range of Unicode
  366. // up to U+10FFFF (the default behavior of InputStream only supports
  367. // code points up to U+FFFF).
  368. var CharStreams = {
  369. // Creates an InputStream from a string.
  370. fromString: function(str) {
  371. return new InputStream(str, true);
  372. },
  373. // Asynchronously creates an InputStream from a blob given the
  374. // encoding of the bytes in that blob (defaults to 'utf8' if
  375. // encoding is null).
  376. //
  377. // Invokes onLoad(result) on success, onError(error) on
  378. // failure.
  379. fromBlob: function(blob, encoding, onLoad, onError) {
  380. var reader = FileReader();
  381. reader.onload = function(e) {
  382. var is = new InputStream(e.target.result, true);
  383. onLoad(is);
  384. };
  385. reader.onerror = onError;
  386. reader.readAsText(blob, encoding);
  387. },
  388. // Creates an InputStream from a Buffer given the
  389. // encoding of the bytes in that buffer (defaults to 'utf8' if
  390. // encoding is null).
  391. fromBuffer: function(buffer, encoding) {
  392. return new InputStream(buffer.toString(encoding), true);
  393. },
  394. // Asynchronously creates an InputStream from a file on disk given
  395. // the encoding of the bytes in that file (defaults to 'utf8' if
  396. // encoding is null).
  397. //
  398. // Invokes callback(error, result) on completion.
  399. fromPath: function(path, encoding, callback) {
  400. fs.readFile(path, encoding, function(err, data) {
  401. var is = null;
  402. if (data !== null) {
  403. is = new InputStream(data, true);
  404. }
  405. callback(err, is);
  406. });
  407. },
  408. // Synchronously creates an InputStream given a path to a file
  409. // on disk and the encoding of the bytes in that file (defaults to
  410. // 'utf8' if encoding is null).
  411. fromPathSync: function(path, encoding) {
  412. var data = fs.readFileSync(path, encoding);
  413. return new InputStream(data, true);
  414. }
  415. };
  416. exports.CharStreams = CharStreams;
  417. /***/ }),
  418. /***/ "./node_modules/antlr4/CommonTokenFactory.js":
  419. /*!***************************************************!*\
  420. !*** ./node_modules/antlr4/CommonTokenFactory.js ***!
  421. \***************************************************/
  422. /*! no static exports found */
  423. /***/ (function(module, exports, __webpack_require__) {
  424. //
  425. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  426. * Use of this file is governed by the BSD 3-clause license that
  427. * can be found in the LICENSE.txt file in the project root.
  428. */
  429. //
  430. //
  431. // This default implementation of {@link TokenFactory} creates
  432. // {@link CommonToken} objects.
  433. //
  434. var CommonToken = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").CommonToken;
  435. function TokenFactory() {
  436. return this;
  437. }
  438. function CommonTokenFactory(copyText) {
  439. TokenFactory.call(this);
  440. // Indicates whether {@link CommonToken//setText} should be called after
  441. // constructing tokens to explicitly set the text. This is useful for cases
  442. // where the input stream might not be able to provide arbitrary substrings
  443. // of text from the input after the lexer creates a token (e.g. the
  444. // implementation of {@link CharStream//getText} in
  445. // {@link UnbufferedCharStream} throws an
  446. // {@link UnsupportedOperationException}). Explicitly setting the token text
  447. // allows {@link Token//getText} to be called at any time regardless of the
  448. // input stream implementation.
  449. //
  450. // <p>
  451. // The default value is {@code false} to avoid the performance and memory
  452. // overhead of copying text for every token unless explicitly requested.</p>
  453. //
  454. this.copyText = copyText===undefined ? false : copyText;
  455. return this;
  456. }
  457. CommonTokenFactory.prototype = Object.create(TokenFactory.prototype);
  458. CommonTokenFactory.prototype.constructor = CommonTokenFactory;
  459. //
  460. // The default {@link CommonTokenFactory} instance.
  461. //
  462. // <p>
  463. // This token factory does not explicitly copy token text when constructing
  464. // tokens.</p>
  465. //
  466. CommonTokenFactory.DEFAULT = new CommonTokenFactory();
  467. CommonTokenFactory.prototype.create = function(source, type, text, channel, start, stop, line, column) {
  468. var t = new CommonToken(source, type, channel, start, stop);
  469. t.line = line;
  470. t.column = column;
  471. if (text !==null) {
  472. t.text = text;
  473. } else if (this.copyText && source[1] !==null) {
  474. t.text = source[1].getText(start,stop);
  475. }
  476. return t;
  477. };
  478. CommonTokenFactory.prototype.createThin = function(type, text) {
  479. var t = new CommonToken(null, type);
  480. t.text = text;
  481. return t;
  482. };
  483. exports.CommonTokenFactory = CommonTokenFactory;
  484. /***/ }),
  485. /***/ "./node_modules/antlr4/CommonTokenStream.js":
  486. /*!**************************************************!*\
  487. !*** ./node_modules/antlr4/CommonTokenStream.js ***!
  488. \**************************************************/
  489. /*! no static exports found */
  490. /***/ (function(module, exports, __webpack_require__) {
  491. //
  492. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  493. * Use of this file is governed by the BSD 3-clause license that
  494. * can be found in the LICENSE.txt file in the project root.
  495. */
  496. ///
  497. //
  498. // This class extends {@link BufferedTokenStream} with functionality to filter
  499. // token streams to tokens on a particular channel (tokens where
  500. // {@link Token//getChannel} returns a particular value).
  501. //
  502. // <p>
  503. // This token stream provides access to all tokens by index or when calling
  504. // methods like {@link //getText}. The channel filtering is only used for code
  505. // accessing tokens via the lookahead methods {@link //LA}, {@link //LT}, and
  506. // {@link //LB}.</p>
  507. //
  508. // <p>
  509. // By default, tokens are placed on the default channel
  510. // ({@link Token//DEFAULT_CHANNEL}), but may be reassigned by using the
  511. // {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to
  512. // call {@link Lexer//setChannel}.
  513. // </p>
  514. //
  515. // <p>
  516. // Note: lexer rules which use the {@code ->skip} lexer command or call
  517. // {@link Lexer//skip} do not produce tokens at all, so input text matched by
  518. // such a rule will not be available as part of the token stream, regardless of
  519. // channel.</p>
  520. ///
  521. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  522. var BufferedTokenStream = __webpack_require__(/*! ./BufferedTokenStream */ "./node_modules/antlr4/BufferedTokenStream.js").BufferedTokenStream;
  523. function CommonTokenStream(lexer, channel) {
  524. BufferedTokenStream.call(this, lexer);
  525. this.channel = channel===undefined ? Token.DEFAULT_CHANNEL : channel;
  526. return this;
  527. }
  528. CommonTokenStream.prototype = Object.create(BufferedTokenStream.prototype);
  529. CommonTokenStream.prototype.constructor = CommonTokenStream;
  530. CommonTokenStream.prototype.adjustSeekIndex = function(i) {
  531. return this.nextTokenOnChannel(i, this.channel);
  532. };
  533. CommonTokenStream.prototype.LB = function(k) {
  534. if (k===0 || this.index-k<0) {
  535. return null;
  536. }
  537. var i = this.index;
  538. var n = 1;
  539. // find k good tokens looking backwards
  540. while (n <= k) {
  541. // skip off-channel tokens
  542. i = this.previousTokenOnChannel(i - 1, this.channel);
  543. n += 1;
  544. }
  545. if (i < 0) {
  546. return null;
  547. }
  548. return this.tokens[i];
  549. };
  550. CommonTokenStream.prototype.LT = function(k) {
  551. this.lazyInit();
  552. if (k === 0) {
  553. return null;
  554. }
  555. if (k < 0) {
  556. return this.LB(-k);
  557. }
  558. var i = this.index;
  559. var n = 1; // we know tokens[pos] is a good one
  560. // find k good tokens
  561. while (n < k) {
  562. // skip off-channel tokens, but make sure to not look past EOF
  563. if (this.sync(i + 1)) {
  564. i = this.nextTokenOnChannel(i + 1, this.channel);
  565. }
  566. n += 1;
  567. }
  568. return this.tokens[i];
  569. };
  570. // Count EOF just once.///
  571. CommonTokenStream.prototype.getNumberOfOnChannelTokens = function() {
  572. var n = 0;
  573. this.fill();
  574. for (var i =0; i< this.tokens.length;i++) {
  575. var t = this.tokens[i];
  576. if( t.channel===this.channel) {
  577. n += 1;
  578. }
  579. if( t.type===Token.EOF) {
  580. break;
  581. }
  582. }
  583. return n;
  584. };
  585. exports.CommonTokenStream = CommonTokenStream;
  586. /***/ }),
  587. /***/ "./node_modules/antlr4/FileStream.js":
  588. /*!*******************************************!*\
  589. !*** ./node_modules/antlr4/FileStream.js ***!
  590. \*******************************************/
  591. /*! no static exports found */
  592. /***/ (function(module, exports, __webpack_require__) {
  593. //
  594. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  595. * Use of this file is governed by the BSD 3-clause license that
  596. * can be found in the LICENSE.txt file in the project root.
  597. */
  598. //
  599. //
  600. // This is an InputStream that is loaded from a file all at once
  601. // when you construct the object.
  602. //
  603. var InputStream = __webpack_require__(/*! ./InputStream */ "./node_modules/antlr4/InputStream.js").InputStream;
  604. var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined';
  605. var fs = isNodeJs ? __webpack_require__(/*! fs */ "./node_modules/node-libs-browser/mock/empty.js") : null;
  606. function FileStream(fileName, decodeToUnicodeCodePoints) {
  607. var data = fs.readFileSync(fileName, "utf8");
  608. InputStream.call(this, data, decodeToUnicodeCodePoints);
  609. this.fileName = fileName;
  610. return this;
  611. }
  612. FileStream.prototype = Object.create(InputStream.prototype);
  613. FileStream.prototype.constructor = FileStream;
  614. exports.FileStream = FileStream;
  615. /***/ }),
  616. /***/ "./node_modules/antlr4/InputStream.js":
  617. /*!********************************************!*\
  618. !*** ./node_modules/antlr4/InputStream.js ***!
  619. \********************************************/
  620. /*! no static exports found */
  621. /***/ (function(module, exports, __webpack_require__) {
  622. //
  623. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  624. * Use of this file is governed by the BSD 3-clause license that
  625. * can be found in the LICENSE.txt file in the project root.
  626. */
  627. //
  628. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  629. __webpack_require__(/*! ./polyfills/codepointat */ "./node_modules/antlr4/polyfills/codepointat.js");
  630. __webpack_require__(/*! ./polyfills/fromcodepoint */ "./node_modules/antlr4/polyfills/fromcodepoint.js");
  631. // Vacuum all input from a string and then treat it like a buffer.
  632. function _loadString(stream) {
  633. stream._index = 0;
  634. stream.data = [];
  635. if (stream.decodeToUnicodeCodePoints) {
  636. for (var i = 0; i < stream.strdata.length; ) {
  637. var codePoint = stream.strdata.codePointAt(i);
  638. stream.data.push(codePoint);
  639. i += codePoint <= 0xFFFF ? 1 : 2;
  640. }
  641. } else {
  642. for (var i = 0; i < stream.strdata.length; i++) {
  643. var codeUnit = stream.strdata.charCodeAt(i);
  644. stream.data.push(codeUnit);
  645. }
  646. }
  647. stream._size = stream.data.length;
  648. }
  649. // If decodeToUnicodeCodePoints is true, the input is treated
  650. // as a series of Unicode code points.
  651. //
  652. // Otherwise, the input is treated as a series of 16-bit UTF-16 code
  653. // units.
  654. function InputStream(data, decodeToUnicodeCodePoints) {
  655. this.name = "<empty>";
  656. this.strdata = data;
  657. this.decodeToUnicodeCodePoints = decodeToUnicodeCodePoints || false;
  658. _loadString(this);
  659. return this;
  660. }
  661. Object.defineProperty(InputStream.prototype, "index", {
  662. get : function() {
  663. return this._index;
  664. }
  665. });
  666. Object.defineProperty(InputStream.prototype, "size", {
  667. get : function() {
  668. return this._size;
  669. }
  670. });
  671. // Reset the stream so that it's in the same state it was
  672. // when the object was created *except* the data array is not
  673. // touched.
  674. //
  675. InputStream.prototype.reset = function() {
  676. this._index = 0;
  677. };
  678. InputStream.prototype.consume = function() {
  679. if (this._index >= this._size) {
  680. // assert this.LA(1) == Token.EOF
  681. throw ("cannot consume EOF");
  682. }
  683. this._index += 1;
  684. };
  685. InputStream.prototype.LA = function(offset) {
  686. if (offset === 0) {
  687. return 0; // undefined
  688. }
  689. if (offset < 0) {
  690. offset += 1; // e.g., translate LA(-1) to use offset=0
  691. }
  692. var pos = this._index + offset - 1;
  693. if (pos < 0 || pos >= this._size) { // invalid
  694. return Token.EOF;
  695. }
  696. return this.data[pos];
  697. };
  698. InputStream.prototype.LT = function(offset) {
  699. return this.LA(offset);
  700. };
  701. // mark/release do nothing; we have entire buffer
  702. InputStream.prototype.mark = function() {
  703. return -1;
  704. };
  705. InputStream.prototype.release = function(marker) {
  706. };
  707. // consume() ahead until p==_index; can't just set p=_index as we must
  708. // update line and column. If we seek backwards, just set p
  709. //
  710. InputStream.prototype.seek = function(_index) {
  711. if (_index <= this._index) {
  712. this._index = _index; // just jump; don't update stream state (line,
  713. // ...)
  714. return;
  715. }
  716. // seek forward
  717. this._index = Math.min(_index, this._size);
  718. };
  719. InputStream.prototype.getText = function(start, stop) {
  720. if (stop >= this._size) {
  721. stop = this._size - 1;
  722. }
  723. if (start >= this._size) {
  724. return "";
  725. } else {
  726. if (this.decodeToUnicodeCodePoints) {
  727. var result = "";
  728. for (var i = start; i <= stop; i++) {
  729. result += String.fromCodePoint(this.data[i]);
  730. }
  731. return result;
  732. } else {
  733. return this.strdata.slice(start, stop + 1);
  734. }
  735. }
  736. };
  737. InputStream.prototype.toString = function() {
  738. return this.strdata;
  739. };
  740. exports.InputStream = InputStream;
  741. /***/ }),
  742. /***/ "./node_modules/antlr4/IntervalSet.js":
  743. /*!********************************************!*\
  744. !*** ./node_modules/antlr4/IntervalSet.js ***!
  745. \********************************************/
  746. /*! no static exports found */
  747. /***/ (function(module, exports, __webpack_require__) {
  748. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  749. * Use of this file is governed by the BSD 3-clause license that
  750. * can be found in the LICENSE.txt file in the project root.
  751. */
  752. /*jslint smarttabs:true */
  753. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  754. /* stop is not included! */
  755. function Interval(start, stop) {
  756. this.start = start;
  757. this.stop = stop;
  758. return this;
  759. }
  760. Interval.prototype.contains = function(item) {
  761. return item >= this.start && item < this.stop;
  762. };
  763. Interval.prototype.toString = function() {
  764. if(this.start===this.stop-1) {
  765. return this.start.toString();
  766. } else {
  767. return this.start.toString() + ".." + (this.stop-1).toString();
  768. }
  769. };
  770. Object.defineProperty(Interval.prototype, "length", {
  771. get : function() {
  772. return this.stop - this.start;
  773. }
  774. });
  775. function IntervalSet() {
  776. this.intervals = null;
  777. this.readOnly = false;
  778. }
  779. IntervalSet.prototype.first = function(v) {
  780. if (this.intervals === null || this.intervals.length===0) {
  781. return Token.INVALID_TYPE;
  782. } else {
  783. return this.intervals[0].start;
  784. }
  785. };
  786. IntervalSet.prototype.addOne = function(v) {
  787. this.addInterval(new Interval(v, v + 1));
  788. };
  789. IntervalSet.prototype.addRange = function(l, h) {
  790. this.addInterval(new Interval(l, h + 1));
  791. };
  792. IntervalSet.prototype.addInterval = function(v) {
  793. if (this.intervals === null) {
  794. this.intervals = [];
  795. this.intervals.push(v);
  796. } else {
  797. // find insert pos
  798. for (var k = 0; k < this.intervals.length; k++) {
  799. var i = this.intervals[k];
  800. // distinct range -> insert
  801. if (v.stop < i.start) {
  802. this.intervals.splice(k, 0, v);
  803. return;
  804. }
  805. // contiguous range -> adjust
  806. else if (v.stop === i.start) {
  807. this.intervals[k].start = v.start;
  808. return;
  809. }
  810. // overlapping range -> adjust and reduce
  811. else if (v.start <= i.stop) {
  812. this.intervals[k] = new Interval(Math.min(i.start, v.start), Math.max(i.stop, v.stop));
  813. this.reduce(k);
  814. return;
  815. }
  816. }
  817. // greater than any existing
  818. this.intervals.push(v);
  819. }
  820. };
  821. IntervalSet.prototype.addSet = function(other) {
  822. if (other.intervals !== null) {
  823. for (var k = 0; k < other.intervals.length; k++) {
  824. var i = other.intervals[k];
  825. this.addInterval(new Interval(i.start, i.stop));
  826. }
  827. }
  828. return this;
  829. };
  830. IntervalSet.prototype.reduce = function(k) {
  831. // only need to reduce if k is not the last
  832. if (k < this.intervalslength - 1) {
  833. var l = this.intervals[k];
  834. var r = this.intervals[k + 1];
  835. // if r contained in l
  836. if (l.stop >= r.stop) {
  837. this.intervals.pop(k + 1);
  838. this.reduce(k);
  839. } else if (l.stop >= r.start) {
  840. this.intervals[k] = new Interval(l.start, r.stop);
  841. this.intervals.pop(k + 1);
  842. }
  843. }
  844. };
  845. IntervalSet.prototype.complement = function(start, stop) {
  846. var result = new IntervalSet();
  847. result.addInterval(new Interval(start,stop+1));
  848. for(var i=0; i<this.intervals.length; i++) {
  849. result.removeRange(this.intervals[i]);
  850. }
  851. return result;
  852. };
  853. IntervalSet.prototype.contains = function(item) {
  854. if (this.intervals === null) {
  855. return false;
  856. } else {
  857. for (var k = 0; k < this.intervals.length; k++) {
  858. if(this.intervals[k].contains(item)) {
  859. return true;
  860. }
  861. }
  862. return false;
  863. }
  864. };
  865. Object.defineProperty(IntervalSet.prototype, "length", {
  866. get : function() {
  867. var len = 0;
  868. this.intervals.map(function(i) {len += i.length;});
  869. return len;
  870. }
  871. });
  872. IntervalSet.prototype.removeRange = function(v) {
  873. if(v.start===v.stop-1) {
  874. this.removeOne(v.start);
  875. } else if (this.intervals!==null) {
  876. var k = 0;
  877. for(var n=0; n<this.intervals.length; n++) {
  878. var i = this.intervals[k];
  879. // intervals are ordered
  880. if (v.stop<=i.start) {
  881. return;
  882. }
  883. // check for including range, split it
  884. else if(v.start>i.start && v.stop<i.stop) {
  885. this.intervals[k] = new Interval(i.start, v.start);
  886. var x = new Interval(v.stop, i.stop);
  887. this.intervals.splice(k, 0, x);
  888. return;
  889. }
  890. // check for included range, remove it
  891. else if(v.start<=i.start && v.stop>=i.stop) {
  892. this.intervals.splice(k, 1);
  893. k = k - 1; // need another pass
  894. }
  895. // check for lower boundary
  896. else if(v.start<i.stop) {
  897. this.intervals[k] = new Interval(i.start, v.start);
  898. }
  899. // check for upper boundary
  900. else if(v.stop<i.stop) {
  901. this.intervals[k] = new Interval(v.stop, i.stop);
  902. }
  903. k += 1;
  904. }
  905. }
  906. };
  907. IntervalSet.prototype.removeOne = function(v) {
  908. if (this.intervals !== null) {
  909. for (var k = 0; k < this.intervals.length; k++) {
  910. var i = this.intervals[k];
  911. // intervals is ordered
  912. if (v < i.start) {
  913. return;
  914. }
  915. // check for single value range
  916. else if (v === i.start && v === i.stop - 1) {
  917. this.intervals.splice(k, 1);
  918. return;
  919. }
  920. // check for lower boundary
  921. else if (v === i.start) {
  922. this.intervals[k] = new Interval(i.start + 1, i.stop);
  923. return;
  924. }
  925. // check for upper boundary
  926. else if (v === i.stop - 1) {
  927. this.intervals[k] = new Interval(i.start, i.stop - 1);
  928. return;
  929. }
  930. // split existing range
  931. else if (v < i.stop - 1) {
  932. var x = new Interval(i.start, v);
  933. i.start = v + 1;
  934. this.intervals.splice(k, 0, x);
  935. return;
  936. }
  937. }
  938. }
  939. };
  940. IntervalSet.prototype.toString = function(literalNames, symbolicNames, elemsAreChar) {
  941. literalNames = literalNames || null;
  942. symbolicNames = symbolicNames || null;
  943. elemsAreChar = elemsAreChar || false;
  944. if (this.intervals === null) {
  945. return "{}";
  946. } else if(literalNames!==null || symbolicNames!==null) {
  947. return this.toTokenString(literalNames, symbolicNames);
  948. } else if(elemsAreChar) {
  949. return this.toCharString();
  950. } else {
  951. return this.toIndexString();
  952. }
  953. };
  954. IntervalSet.prototype.toCharString = function() {
  955. var names = [];
  956. for (var i = 0; i < this.intervals.length; i++) {
  957. var v = this.intervals[i];
  958. if(v.stop===v.start+1) {
  959. if ( v.start===Token.EOF ) {
  960. names.push("<EOF>");
  961. } else {
  962. names.push("'" + String.fromCharCode(v.start) + "'");
  963. }
  964. } else {
  965. names.push("'" + String.fromCharCode(v.start) + "'..'" + String.fromCharCode(v.stop-1) + "'");
  966. }
  967. }
  968. if (names.length > 1) {
  969. return "{" + names.join(", ") + "}";
  970. } else {
  971. return names[0];
  972. }
  973. };
  974. IntervalSet.prototype.toIndexString = function() {
  975. var names = [];
  976. for (var i = 0; i < this.intervals.length; i++) {
  977. var v = this.intervals[i];
  978. if(v.stop===v.start+1) {
  979. if ( v.start===Token.EOF ) {
  980. names.push("<EOF>");
  981. } else {
  982. names.push(v.start.toString());
  983. }
  984. } else {
  985. names.push(v.start.toString() + ".." + (v.stop-1).toString());
  986. }
  987. }
  988. if (names.length > 1) {
  989. return "{" + names.join(", ") + "}";
  990. } else {
  991. return names[0];
  992. }
  993. };
  994. IntervalSet.prototype.toTokenString = function(literalNames, symbolicNames) {
  995. var names = [];
  996. for (var i = 0; i < this.intervals.length; i++) {
  997. var v = this.intervals[i];
  998. for (var j = v.start; j < v.stop; j++) {
  999. names.push(this.elementName(literalNames, symbolicNames, j));
  1000. }
  1001. }
  1002. if (names.length > 1) {
  1003. return "{" + names.join(", ") + "}";
  1004. } else {
  1005. return names[0];
  1006. }
  1007. };
  1008. IntervalSet.prototype.elementName = function(literalNames, symbolicNames, a) {
  1009. if (a === Token.EOF) {
  1010. return "<EOF>";
  1011. } else if (a === Token.EPSILON) {
  1012. return "<EPSILON>";
  1013. } else {
  1014. return literalNames[a] || symbolicNames[a];
  1015. }
  1016. };
  1017. exports.Interval = Interval;
  1018. exports.IntervalSet = IntervalSet;
  1019. /***/ }),
  1020. /***/ "./node_modules/antlr4/LL1Analyzer.js":
  1021. /*!********************************************!*\
  1022. !*** ./node_modules/antlr4/LL1Analyzer.js ***!
  1023. \********************************************/
  1024. /*! no static exports found */
  1025. /***/ (function(module, exports, __webpack_require__) {
  1026. //
  1027. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  1028. * Use of this file is governed by the BSD 3-clause license that
  1029. * can be found in the LICENSE.txt file in the project root.
  1030. */
  1031. ///
  1032. var Set = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").Set;
  1033. var BitSet = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").BitSet;
  1034. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  1035. var ATNConfig = __webpack_require__(/*! ./atn/ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").ATNConfig;
  1036. var Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  1037. var IntervalSet = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  1038. var RuleStopState = __webpack_require__(/*! ./atn/ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
  1039. var RuleTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").RuleTransition;
  1040. var NotSetTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").NotSetTransition;
  1041. var WildcardTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").WildcardTransition;
  1042. var AbstractPredicateTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").AbstractPredicateTransition;
  1043. var pc = __webpack_require__(/*! ./PredictionContext */ "./node_modules/antlr4/PredictionContext.js");
  1044. var predictionContextFromRuleContext = pc.predictionContextFromRuleContext;
  1045. var PredictionContext = pc.PredictionContext;
  1046. var SingletonPredictionContext = pc.SingletonPredictionContext;
  1047. function LL1Analyzer (atn) {
  1048. this.atn = atn;
  1049. }
  1050. //* Special value added to the lookahead sets to indicate that we hit
  1051. // a predicate during analysis if {@code seeThruPreds==false}.
  1052. ///
  1053. LL1Analyzer.HIT_PRED = Token.INVALID_TYPE;
  1054. //*
  1055. // Calculates the SLL(1) expected lookahead set for each outgoing transition
  1056. // of an {@link ATNState}. The returned array has one element for each
  1057. // outgoing transition in {@code s}. If the closure from transition
  1058. // <em>i</em> leads to a semantic predicate before matching a symbol, the
  1059. // element at index <em>i</em> of the result will be {@code null}.
  1060. //
  1061. // @param s the ATN state
  1062. // @return the expected symbols for each outgoing transition of {@code s}.
  1063. ///
  1064. LL1Analyzer.prototype.getDecisionLookahead = function(s) {
  1065. if (s === null) {
  1066. return null;
  1067. }
  1068. var count = s.transitions.length;
  1069. var look = [];
  1070. for(var alt=0; alt< count; alt++) {
  1071. look[alt] = new IntervalSet();
  1072. var lookBusy = new Set();
  1073. var seeThruPreds = false; // fail to get lookahead upon pred
  1074. this._LOOK(s.transition(alt).target, null, PredictionContext.EMPTY,
  1075. look[alt], lookBusy, new BitSet(), seeThruPreds, false);
  1076. // Wipe out lookahead for this alternative if we found nothing
  1077. // or we had a predicate when we !seeThruPreds
  1078. if (look[alt].length===0 || look[alt].contains(LL1Analyzer.HIT_PRED)) {
  1079. look[alt] = null;
  1080. }
  1081. }
  1082. return look;
  1083. };
  1084. //*
  1085. // Compute set of tokens that can follow {@code s} in the ATN in the
  1086. // specified {@code ctx}.
  1087. //
  1088. // <p>If {@code ctx} is {@code null} and the end of the rule containing
  1089. // {@code s} is reached, {@link Token//EPSILON} is added to the result set.
  1090. // If {@code ctx} is not {@code null} and the end of the outermost rule is
  1091. // reached, {@link Token//EOF} is added to the result set.</p>
  1092. //
  1093. // @param s the ATN state
  1094. // @param stopState the ATN state to stop at. This can be a
  1095. // {@link BlockEndState} to detect epsilon paths through a closure.
  1096. // @param ctx the complete parser context, or {@code null} if the context
  1097. // should be ignored
  1098. //
  1099. // @return The set of tokens that can follow {@code s} in the ATN in the
  1100. // specified {@code ctx}.
  1101. ///
  1102. LL1Analyzer.prototype.LOOK = function(s, stopState, ctx) {
  1103. var r = new IntervalSet();
  1104. var seeThruPreds = true; // ignore preds; get all lookahead
  1105. ctx = ctx || null;
  1106. var lookContext = ctx!==null ? predictionContextFromRuleContext(s.atn, ctx) : null;
  1107. this._LOOK(s, stopState, lookContext, r, new Set(), new BitSet(), seeThruPreds, true);
  1108. return r;
  1109. };
  1110. //*
  1111. // Compute set of tokens that can follow {@code s} in the ATN in the
  1112. // specified {@code ctx}.
  1113. //
  1114. // <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the
  1115. // rule containing {@code s} is reached, {@link Token//EPSILON} is added to
  1116. // the result set. If {@code ctx} is not {@code null} and {@code addEOF} is
  1117. // {@code true} and {@code stopState} or the end of the outermost rule is
  1118. // reached, {@link Token//EOF} is added to the result set.</p>
  1119. //
  1120. // @param s the ATN state.
  1121. // @param stopState the ATN state to stop at. This can be a
  1122. // {@link BlockEndState} to detect epsilon paths through a closure.
  1123. // @param ctx The outer context, or {@code null} if the outer context should
  1124. // not be used.
  1125. // @param look The result lookahead set.
  1126. // @param lookBusy A set used for preventing epsilon closures in the ATN
  1127. // from causing a stack overflow. Outside code should pass
  1128. // {@code new Set<ATNConfig>} for this argument.
  1129. // @param calledRuleStack A set used for preventing left recursion in the
  1130. // ATN from causing a stack overflow. Outside code should pass
  1131. // {@code new BitSet()} for this argument.
  1132. // @param seeThruPreds {@code true} to true semantic predicates as
  1133. // implicitly {@code true} and "see through them", otherwise {@code false}
  1134. // to treat semantic predicates as opaque and add {@link //HIT_PRED} to the
  1135. // result if one is encountered.
  1136. // @param addEOF Add {@link Token//EOF} to the result if the end of the
  1137. // outermost context is reached. This parameter has no effect if {@code ctx}
  1138. // is {@code null}.
  1139. ///
  1140. LL1Analyzer.prototype._LOOK = function(s, stopState , ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) {
  1141. var c = new ATNConfig({state:s, alt:0, context: ctx}, null);
  1142. if (lookBusy.contains(c)) {
  1143. return;
  1144. }
  1145. lookBusy.add(c);
  1146. if (s === stopState) {
  1147. if (ctx ===null) {
  1148. look.addOne(Token.EPSILON);
  1149. return;
  1150. } else if (ctx.isEmpty() && addEOF) {
  1151. look.addOne(Token.EOF);
  1152. return;
  1153. }
  1154. }
  1155. if (s instanceof RuleStopState ) {
  1156. if (ctx ===null) {
  1157. look.addOne(Token.EPSILON);
  1158. return;
  1159. } else if (ctx.isEmpty() && addEOF) {
  1160. look.addOne(Token.EOF);
  1161. return;
  1162. }
  1163. if (ctx !== PredictionContext.EMPTY) {
  1164. // run thru all possible stack tops in ctx
  1165. for(var i=0; i<ctx.length; i++) {
  1166. var returnState = this.atn.states[ctx.getReturnState(i)];
  1167. var removed = calledRuleStack.contains(returnState.ruleIndex);
  1168. try {
  1169. calledRuleStack.remove(returnState.ruleIndex);
  1170. this._LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
  1171. } finally {
  1172. if (removed) {
  1173. calledRuleStack.add(returnState.ruleIndex);
  1174. }
  1175. }
  1176. }
  1177. return;
  1178. }
  1179. }
  1180. for(var j=0; j<s.transitions.length; j++) {
  1181. var t = s.transitions[j];
  1182. if (t.constructor === RuleTransition) {
  1183. if (calledRuleStack.contains(t.target.ruleIndex)) {
  1184. continue;
  1185. }
  1186. var newContext = SingletonPredictionContext.create(ctx, t.followState.stateNumber);
  1187. try {
  1188. calledRuleStack.add(t.target.ruleIndex);
  1189. this._LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
  1190. } finally {
  1191. calledRuleStack.remove(t.target.ruleIndex);
  1192. }
  1193. } else if (t instanceof AbstractPredicateTransition ) {
  1194. if (seeThruPreds) {
  1195. this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
  1196. } else {
  1197. look.addOne(LL1Analyzer.HIT_PRED);
  1198. }
  1199. } else if( t.isEpsilon) {
  1200. this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
  1201. } else if (t.constructor === WildcardTransition) {
  1202. look.addRange( Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType );
  1203. } else {
  1204. var set = t.label;
  1205. if (set !== null) {
  1206. if (t instanceof NotSetTransition) {
  1207. set = set.complement(Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType);
  1208. }
  1209. look.addSet(set);
  1210. }
  1211. }
  1212. }
  1213. };
  1214. exports.LL1Analyzer = LL1Analyzer;
  1215. /***/ }),
  1216. /***/ "./node_modules/antlr4/Lexer.js":
  1217. /*!**************************************!*\
  1218. !*** ./node_modules/antlr4/Lexer.js ***!
  1219. \**************************************/
  1220. /*! no static exports found */
  1221. /***/ (function(module, exports, __webpack_require__) {
  1222. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  1223. * Use of this file is governed by the BSD 3-clause license that
  1224. * can be found in the LICENSE.txt file in the project root.
  1225. */
  1226. ///
  1227. // A lexer is recognizer that draws input symbols from a character stream.
  1228. // lexer grammars result in a subclass of this object. A Lexer object
  1229. // uses simplified match() and error recovery mechanisms in the interest of speed.
  1230. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  1231. var Recognizer = __webpack_require__(/*! ./Recognizer */ "./node_modules/antlr4/Recognizer.js").Recognizer;
  1232. var CommonTokenFactory = __webpack_require__(/*! ./CommonTokenFactory */ "./node_modules/antlr4/CommonTokenFactory.js").CommonTokenFactory;
  1233. var RecognitionException = __webpack_require__(/*! ./error/Errors */ "./node_modules/antlr4/error/Errors.js").RecognitionException;
  1234. var LexerNoViableAltException = __webpack_require__(/*! ./error/Errors */ "./node_modules/antlr4/error/Errors.js").LexerNoViableAltException;
  1235. function TokenSource() {
  1236. return this;
  1237. }
  1238. function Lexer(input) {
  1239. Recognizer.call(this);
  1240. this._input = input;
  1241. this._factory = CommonTokenFactory.DEFAULT;
  1242. this._tokenFactorySourcePair = [ this, input ];
  1243. this._interp = null; // child classes must populate this
  1244. // The goal of all lexer rules/methods is to create a token object.
  1245. // this is an instance variable as multiple rules may collaborate to
  1246. // create a single token. nextToken will return this object after
  1247. // matching lexer rule(s). If you subclass to allow multiple token
  1248. // emissions, then set this to the last token to be matched or
  1249. // something nonnull so that the auto token emit mechanism will not
  1250. // emit another token.
  1251. this._token = null;
  1252. // What character index in the stream did the current token start at?
  1253. // Needed, for example, to get the text for current token. Set at
  1254. // the start of nextToken.
  1255. this._tokenStartCharIndex = -1;
  1256. // The line on which the first character of the token resides///
  1257. this._tokenStartLine = -1;
  1258. // The character position of first character within the line///
  1259. this._tokenStartColumn = -1;
  1260. // Once we see EOF on char stream, next token will be EOF.
  1261. // If you have DONE : EOF ; then you see DONE EOF.
  1262. this._hitEOF = false;
  1263. // The channel number for the current token///
  1264. this._channel = Token.DEFAULT_CHANNEL;
  1265. // The token type for the current token///
  1266. this._type = Token.INVALID_TYPE;
  1267. this._modeStack = [];
  1268. this._mode = Lexer.DEFAULT_MODE;
  1269. // You can set the text for the current token to override what is in
  1270. // the input char buffer. Use setText() or can set this instance var.
  1271. // /
  1272. this._text = null;
  1273. return this;
  1274. }
  1275. Lexer.prototype = Object.create(Recognizer.prototype);
  1276. Lexer.prototype.constructor = Lexer;
  1277. Lexer.DEFAULT_MODE = 0;
  1278. Lexer.MORE = -2;
  1279. Lexer.SKIP = -3;
  1280. Lexer.DEFAULT_TOKEN_CHANNEL = Token.DEFAULT_CHANNEL;
  1281. Lexer.HIDDEN = Token.HIDDEN_CHANNEL;
  1282. Lexer.MIN_CHAR_VALUE = 0x0000;
  1283. Lexer.MAX_CHAR_VALUE = 0x10FFFF;
  1284. Lexer.prototype.reset = function() {
  1285. // wack Lexer state variables
  1286. if (this._input !== null) {
  1287. this._input.seek(0); // rewind the input
  1288. }
  1289. this._token = null;
  1290. this._type = Token.INVALID_TYPE;
  1291. this._channel = Token.DEFAULT_CHANNEL;
  1292. this._tokenStartCharIndex = -1;
  1293. this._tokenStartColumn = -1;
  1294. this._tokenStartLine = -1;
  1295. this._text = null;
  1296. this._hitEOF = false;
  1297. this._mode = Lexer.DEFAULT_MODE;
  1298. this._modeStack = [];
  1299. this._interp.reset();
  1300. };
  1301. // Return a token from this source; i.e., match a token on the char stream.
  1302. Lexer.prototype.nextToken = function() {
  1303. if (this._input === null) {
  1304. throw "nextToken requires a non-null input stream.";
  1305. }
  1306. // Mark start location in char stream so unbuffered streams are
  1307. // guaranteed at least have text of current token
  1308. var tokenStartMarker = this._input.mark();
  1309. try {
  1310. while (true) {
  1311. if (this._hitEOF) {
  1312. this.emitEOF();
  1313. return this._token;
  1314. }
  1315. this._token = null;
  1316. this._channel = Token.DEFAULT_CHANNEL;
  1317. this._tokenStartCharIndex = this._input.index;
  1318. this._tokenStartColumn = this._interp.column;
  1319. this._tokenStartLine = this._interp.line;
  1320. this._text = null;
  1321. var continueOuter = false;
  1322. while (true) {
  1323. this._type = Token.INVALID_TYPE;
  1324. var ttype = Lexer.SKIP;
  1325. try {
  1326. ttype = this._interp.match(this._input, this._mode);
  1327. } catch (e) {
  1328. if(e instanceof RecognitionException) {
  1329. this.notifyListeners(e); // report error
  1330. this.recover(e);
  1331. } else {
  1332. console.log(e.stack);
  1333. throw e;
  1334. }
  1335. }
  1336. if (this._input.LA(1) === Token.EOF) {
  1337. this._hitEOF = true;
  1338. }
  1339. if (this._type === Token.INVALID_TYPE) {
  1340. this._type = ttype;
  1341. }
  1342. if (this._type === Lexer.SKIP) {
  1343. continueOuter = true;
  1344. break;
  1345. }
  1346. if (this._type !== Lexer.MORE) {
  1347. break;
  1348. }
  1349. }
  1350. if (continueOuter) {
  1351. continue;
  1352. }
  1353. if (this._token === null) {
  1354. this.emit();
  1355. }
  1356. return this._token;
  1357. }
  1358. } finally {
  1359. // make sure we release marker after match or
  1360. // unbuffered char stream will keep buffering
  1361. this._input.release(tokenStartMarker);
  1362. }
  1363. };
  1364. // Instruct the lexer to skip creating a token for current lexer rule
  1365. // and look for another token. nextToken() knows to keep looking when
  1366. // a lexer rule finishes with token set to SKIP_TOKEN. Recall that
  1367. // if token==null at end of any token rule, it creates one for you
  1368. // and emits it.
  1369. // /
  1370. Lexer.prototype.skip = function() {
  1371. this._type = Lexer.SKIP;
  1372. };
  1373. Lexer.prototype.more = function() {
  1374. this._type = Lexer.MORE;
  1375. };
  1376. Lexer.prototype.mode = function(m) {
  1377. this._mode = m;
  1378. };
  1379. Lexer.prototype.pushMode = function(m) {
  1380. if (this._interp.debug) {
  1381. console.log("pushMode " + m);
  1382. }
  1383. this._modeStack.push(this._mode);
  1384. this.mode(m);
  1385. };
  1386. Lexer.prototype.popMode = function() {
  1387. if (this._modeStack.length === 0) {
  1388. throw "Empty Stack";
  1389. }
  1390. if (this._interp.debug) {
  1391. console.log("popMode back to " + this._modeStack.slice(0, -1));
  1392. }
  1393. this.mode(this._modeStack.pop());
  1394. return this._mode;
  1395. };
  1396. // Set the char stream and reset the lexer
  1397. Object.defineProperty(Lexer.prototype, "inputStream", {
  1398. get : function() {
  1399. return this._input;
  1400. },
  1401. set : function(input) {
  1402. this._input = null;
  1403. this._tokenFactorySourcePair = [ this, this._input ];
  1404. this.reset();
  1405. this._input = input;
  1406. this._tokenFactorySourcePair = [ this, this._input ];
  1407. }
  1408. });
  1409. Object.defineProperty(Lexer.prototype, "sourceName", {
  1410. get : function sourceName() {
  1411. return this._input.sourceName;
  1412. }
  1413. });
  1414. // By default does not support multiple emits per nextToken invocation
  1415. // for efficiency reasons. Subclass and override this method, nextToken,
  1416. // and getToken (to push tokens into a list and pull from that list
  1417. // rather than a single variable as this implementation does).
  1418. // /
  1419. Lexer.prototype.emitToken = function(token) {
  1420. this._token = token;
  1421. };
  1422. // The standard method called to automatically emit a token at the
  1423. // outermost lexical rule. The token object should point into the
  1424. // char buffer start..stop. If there is a text override in 'text',
  1425. // use that to set the token's text. Override this method to emit
  1426. // custom Token objects or provide a new factory.
  1427. // /
  1428. Lexer.prototype.emit = function() {
  1429. var t = this._factory.create(this._tokenFactorySourcePair, this._type,
  1430. this._text, this._channel, this._tokenStartCharIndex, this
  1431. .getCharIndex() - 1, this._tokenStartLine,
  1432. this._tokenStartColumn);
  1433. this.emitToken(t);
  1434. return t;
  1435. };
  1436. Lexer.prototype.emitEOF = function() {
  1437. var cpos = this.column;
  1438. var lpos = this.line;
  1439. var eof = this._factory.create(this._tokenFactorySourcePair, Token.EOF,
  1440. null, Token.DEFAULT_CHANNEL, this._input.index,
  1441. this._input.index - 1, lpos, cpos);
  1442. this.emitToken(eof);
  1443. return eof;
  1444. };
  1445. Object.defineProperty(Lexer.prototype, "type", {
  1446. get : function() {
  1447. return this.type;
  1448. },
  1449. set : function(type) {
  1450. this._type = type;
  1451. }
  1452. });
  1453. Object.defineProperty(Lexer.prototype, "line", {
  1454. get : function() {
  1455. return this._interp.line;
  1456. },
  1457. set : function(line) {
  1458. this._interp.line = line;
  1459. }
  1460. });
  1461. Object.defineProperty(Lexer.prototype, "column", {
  1462. get : function() {
  1463. return this._interp.column;
  1464. },
  1465. set : function(column) {
  1466. this._interp.column = column;
  1467. }
  1468. });
  1469. // What is the index of the current character of lookahead?///
  1470. Lexer.prototype.getCharIndex = function() {
  1471. return this._input.index;
  1472. };
  1473. // Return the text matched so far for the current token or any text override.
  1474. //Set the complete text of this token; it wipes any previous changes to the text.
  1475. Object.defineProperty(Lexer.prototype, "text", {
  1476. get : function() {
  1477. if (this._text !== null) {
  1478. return this._text;
  1479. } else {
  1480. return this._interp.getText(this._input);
  1481. }
  1482. },
  1483. set : function(text) {
  1484. this._text = text;
  1485. }
  1486. });
  1487. // Return a list of all Token objects in input char stream.
  1488. // Forces load of all tokens. Does not include EOF token.
  1489. // /
  1490. Lexer.prototype.getAllTokens = function() {
  1491. var tokens = [];
  1492. var t = this.nextToken();
  1493. while (t.type !== Token.EOF) {
  1494. tokens.push(t);
  1495. t = this.nextToken();
  1496. }
  1497. return tokens;
  1498. };
  1499. Lexer.prototype.notifyListeners = function(e) {
  1500. var start = this._tokenStartCharIndex;
  1501. var stop = this._input.index;
  1502. var text = this._input.getText(start, stop);
  1503. var msg = "token recognition error at: '" + this.getErrorDisplay(text) + "'";
  1504. var listener = this.getErrorListenerDispatch();
  1505. listener.syntaxError(this, null, this._tokenStartLine,
  1506. this._tokenStartColumn, msg, e);
  1507. };
  1508. Lexer.prototype.getErrorDisplay = function(s) {
  1509. var d = [];
  1510. for (var i = 0; i < s.length; i++) {
  1511. d.push(s[i]);
  1512. }
  1513. return d.join('');
  1514. };
  1515. Lexer.prototype.getErrorDisplayForChar = function(c) {
  1516. if (c.charCodeAt(0) === Token.EOF) {
  1517. return "<EOF>";
  1518. } else if (c === '\n') {
  1519. return "\\n";
  1520. } else if (c === '\t') {
  1521. return "\\t";
  1522. } else if (c === '\r') {
  1523. return "\\r";
  1524. } else {
  1525. return c;
  1526. }
  1527. };
  1528. Lexer.prototype.getCharErrorDisplay = function(c) {
  1529. return "'" + this.getErrorDisplayForChar(c) + "'";
  1530. };
  1531. // Lexers can normally match any char in it's vocabulary after matching
  1532. // a token, so do the easy thing and just kill a character and hope
  1533. // it all works out. You can instead use the rule invocation stack
  1534. // to do sophisticated error recovery if you are in a fragment rule.
  1535. // /
  1536. Lexer.prototype.recover = function(re) {
  1537. if (this._input.LA(1) !== Token.EOF) {
  1538. if (re instanceof LexerNoViableAltException) {
  1539. // skip a char and try again
  1540. this._interp.consume(this._input);
  1541. } else {
  1542. // TODO: Do we lose character or line position information?
  1543. this._input.consume();
  1544. }
  1545. }
  1546. };
  1547. exports.Lexer = Lexer;
  1548. /***/ }),
  1549. /***/ "./node_modules/antlr4/Parser.js":
  1550. /*!***************************************!*\
  1551. !*** ./node_modules/antlr4/Parser.js ***!
  1552. \***************************************/
  1553. /*! no static exports found */
  1554. /***/ (function(module, exports, __webpack_require__) {
  1555. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  1556. * Use of this file is governed by the BSD 3-clause license that
  1557. * can be found in the LICENSE.txt file in the project root.
  1558. */
  1559. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  1560. var ParseTreeListener = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").ParseTreeListener;
  1561. var Recognizer = __webpack_require__(/*! ./Recognizer */ "./node_modules/antlr4/Recognizer.js").Recognizer;
  1562. var DefaultErrorStrategy = __webpack_require__(/*! ./error/ErrorStrategy */ "./node_modules/antlr4/error/ErrorStrategy.js").DefaultErrorStrategy;
  1563. var ATNDeserializer = __webpack_require__(/*! ./atn/ATNDeserializer */ "./node_modules/antlr4/atn/ATNDeserializer.js").ATNDeserializer;
  1564. var ATNDeserializationOptions = __webpack_require__(/*! ./atn/ATNDeserializationOptions */ "./node_modules/antlr4/atn/ATNDeserializationOptions.js").ATNDeserializationOptions;
  1565. var TerminalNode = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").TerminalNode;
  1566. var ErrorNode = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").ErrorNode;
  1567. function TraceListener(parser) {
  1568. ParseTreeListener.call(this);
  1569. this.parser = parser;
  1570. return this;
  1571. }
  1572. TraceListener.prototype = Object.create(ParseTreeListener.prototype);
  1573. TraceListener.prototype.constructor = TraceListener;
  1574. TraceListener.prototype.enterEveryRule = function(ctx) {
  1575. console.log("enter " + this.parser.ruleNames[ctx.ruleIndex] + ", LT(1)=" + this.parser._input.LT(1).text);
  1576. };
  1577. TraceListener.prototype.visitTerminal = function( node) {
  1578. console.log("consume " + node.symbol + " rule " + this.parser.ruleNames[this.parser._ctx.ruleIndex]);
  1579. };
  1580. TraceListener.prototype.exitEveryRule = function(ctx) {
  1581. console.log("exit " + this.parser.ruleNames[ctx.ruleIndex] + ", LT(1)=" + this.parser._input.LT(1).text);
  1582. };
  1583. // this is all the parsing support code essentially; most of it is error
  1584. // recovery stuff.//
  1585. function Parser(input) {
  1586. Recognizer.call(this);
  1587. // The input stream.
  1588. this._input = null;
  1589. // The error handling strategy for the parser. The default value is a new
  1590. // instance of {@link DefaultErrorStrategy}.
  1591. this._errHandler = new DefaultErrorStrategy();
  1592. this._precedenceStack = [];
  1593. this._precedenceStack.push(0);
  1594. // The {@link ParserRuleContext} object for the currently executing rule.
  1595. // this is always non-null during the parsing process.
  1596. this._ctx = null;
  1597. // Specifies whether or not the parser should construct a parse tree during
  1598. // the parsing process. The default value is {@code true}.
  1599. this.buildParseTrees = true;
  1600. // When {@link //setTrace}{@code (true)} is called, a reference to the
  1601. // {@link TraceListener} is stored here so it can be easily removed in a
  1602. // later call to {@link //setTrace}{@code (false)}. The listener itself is
  1603. // implemented as a parser listener so this field is not directly used by
  1604. // other parser methods.
  1605. this._tracer = null;
  1606. // The list of {@link ParseTreeListener} listeners registered to receive
  1607. // events during the parse.
  1608. this._parseListeners = null;
  1609. // The number of syntax errors reported during parsing. this value is
  1610. // incremented each time {@link //notifyErrorListeners} is called.
  1611. this._syntaxErrors = 0;
  1612. this.setInputStream(input);
  1613. return this;
  1614. }
  1615. Parser.prototype = Object.create(Recognizer.prototype);
  1616. Parser.prototype.contructor = Parser;
  1617. // this field maps from the serialized ATN string to the deserialized {@link
  1618. // ATN} with
  1619. // bypass alternatives.
  1620. //
  1621. // @see ATNDeserializationOptions//isGenerateRuleBypassTransitions()
  1622. //
  1623. Parser.bypassAltsAtnCache = {};
  1624. // reset the parser's state//
  1625. Parser.prototype.reset = function() {
  1626. if (this._input !== null) {
  1627. this._input.seek(0);
  1628. }
  1629. this._errHandler.reset(this);
  1630. this._ctx = null;
  1631. this._syntaxErrors = 0;
  1632. this.setTrace(false);
  1633. this._precedenceStack = [];
  1634. this._precedenceStack.push(0);
  1635. if (this._interp !== null) {
  1636. this._interp.reset();
  1637. }
  1638. };
  1639. // Match current input symbol against {@code ttype}. If the symbol type
  1640. // matches, {@link ANTLRErrorStrategy//reportMatch} and {@link //consume} are
  1641. // called to complete the match process.
  1642. //
  1643. // <p>If the symbol type does not match,
  1644. // {@link ANTLRErrorStrategy//recoverInline} is called on the current error
  1645. // strategy to attempt recovery. If {@link //getBuildParseTree} is
  1646. // {@code true} and the token index of the symbol returned by
  1647. // {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to
  1648. // the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>
  1649. //
  1650. // @param ttype the token type to match
  1651. // @return the matched symbol
  1652. // @throws RecognitionException if the current input symbol did not match
  1653. // {@code ttype} and the error strategy could not recover from the
  1654. // mismatched symbol
  1655. Parser.prototype.match = function(ttype) {
  1656. var t = this.getCurrentToken();
  1657. if (t.type === ttype) {
  1658. this._errHandler.reportMatch(this);
  1659. this.consume();
  1660. } else {
  1661. t = this._errHandler.recoverInline(this);
  1662. if (this.buildParseTrees && t.tokenIndex === -1) {
  1663. // we must have conjured up a new token during single token
  1664. // insertion
  1665. // if it's not the current symbol
  1666. this._ctx.addErrorNode(t);
  1667. }
  1668. }
  1669. return t;
  1670. };
  1671. // Match current input symbol as a wildcard. If the symbol type matches
  1672. // (i.e. has a value greater than 0), {@link ANTLRErrorStrategy//reportMatch}
  1673. // and {@link //consume} are called to complete the match process.
  1674. //
  1675. // <p>If the symbol type does not match,
  1676. // {@link ANTLRErrorStrategy//recoverInline} is called on the current error
  1677. // strategy to attempt recovery. If {@link //getBuildParseTree} is
  1678. // {@code true} and the token index of the symbol returned by
  1679. // {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to
  1680. // the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>
  1681. //
  1682. // @return the matched symbol
  1683. // @throws RecognitionException if the current input symbol did not match
  1684. // a wildcard and the error strategy could not recover from the mismatched
  1685. // symbol
  1686. Parser.prototype.matchWildcard = function() {
  1687. var t = this.getCurrentToken();
  1688. if (t.type > 0) {
  1689. this._errHandler.reportMatch(this);
  1690. this.consume();
  1691. } else {
  1692. t = this._errHandler.recoverInline(this);
  1693. if (this._buildParseTrees && t.tokenIndex === -1) {
  1694. // we must have conjured up a new token during single token
  1695. // insertion
  1696. // if it's not the current symbol
  1697. this._ctx.addErrorNode(t);
  1698. }
  1699. }
  1700. return t;
  1701. };
  1702. Parser.prototype.getParseListeners = function() {
  1703. return this._parseListeners || [];
  1704. };
  1705. // Registers {@code listener} to receive events during the parsing process.
  1706. //
  1707. // <p>To support output-preserving grammar transformations (including but not
  1708. // limited to left-recursion removal, automated left-factoring, and
  1709. // optimized code generation), calls to listener methods during the parse
  1710. // may differ substantially from calls made by
  1711. // {@link ParseTreeWalker//DEFAULT} used after the parse is complete. In
  1712. // particular, rule entry and exit events may occur in a different order
  1713. // during the parse than after the parser. In addition, calls to certain
  1714. // rule entry methods may be omitted.</p>
  1715. //
  1716. // <p>With the following specific exceptions, calls to listener events are
  1717. // <em>deterministic</em>, i.e. for identical input the calls to listener
  1718. // methods will be the same.</p>
  1719. //
  1720. // <ul>
  1721. // <li>Alterations to the grammar used to generate code may change the
  1722. // behavior of the listener calls.</li>
  1723. // <li>Alterations to the command line options passed to ANTLR 4 when
  1724. // generating the parser may change the behavior of the listener calls.</li>
  1725. // <li>Changing the version of the ANTLR Tool used to generate the parser
  1726. // may change the behavior of the listener calls.</li>
  1727. // </ul>
  1728. //
  1729. // @param listener the listener to add
  1730. //
  1731. // @throws NullPointerException if {@code} listener is {@code null}
  1732. //
  1733. Parser.prototype.addParseListener = function(listener) {
  1734. if (listener === null) {
  1735. throw "listener";
  1736. }
  1737. if (this._parseListeners === null) {
  1738. this._parseListeners = [];
  1739. }
  1740. this._parseListeners.push(listener);
  1741. };
  1742. //
  1743. // Remove {@code listener} from the list of parse listeners.
  1744. //
  1745. // <p>If {@code listener} is {@code null} or has not been added as a parse
  1746. // listener, this method does nothing.</p>
  1747. // @param listener the listener to remove
  1748. //
  1749. Parser.prototype.removeParseListener = function(listener) {
  1750. if (this._parseListeners !== null) {
  1751. var idx = this._parseListeners.indexOf(listener);
  1752. if (idx >= 0) {
  1753. this._parseListeners.splice(idx, 1);
  1754. }
  1755. if (this._parseListeners.length === 0) {
  1756. this._parseListeners = null;
  1757. }
  1758. }
  1759. };
  1760. // Remove all parse listeners.
  1761. Parser.prototype.removeParseListeners = function() {
  1762. this._parseListeners = null;
  1763. };
  1764. // Notify any parse listeners of an enter rule event.
  1765. Parser.prototype.triggerEnterRuleEvent = function() {
  1766. if (this._parseListeners !== null) {
  1767. var ctx = this._ctx;
  1768. this._parseListeners.map(function(listener) {
  1769. listener.enterEveryRule(ctx);
  1770. ctx.enterRule(listener);
  1771. });
  1772. }
  1773. };
  1774. //
  1775. // Notify any parse listeners of an exit rule event.
  1776. //
  1777. // @see //addParseListener
  1778. //
  1779. Parser.prototype.triggerExitRuleEvent = function() {
  1780. if (this._parseListeners !== null) {
  1781. // reverse order walk of listeners
  1782. var ctx = this._ctx;
  1783. this._parseListeners.slice(0).reverse().map(function(listener) {
  1784. ctx.exitRule(listener);
  1785. listener.exitEveryRule(ctx);
  1786. });
  1787. }
  1788. };
  1789. Parser.prototype.getTokenFactory = function() {
  1790. return this._input.tokenSource._factory;
  1791. };
  1792. // Tell our token source and error strategy about a new way to create tokens.//
  1793. Parser.prototype.setTokenFactory = function(factory) {
  1794. this._input.tokenSource._factory = factory;
  1795. };
  1796. // The ATN with bypass alternatives is expensive to create so we create it
  1797. // lazily.
  1798. //
  1799. // @throws UnsupportedOperationException if the current parser does not
  1800. // implement the {@link //getSerializedATN()} method.
  1801. //
  1802. Parser.prototype.getATNWithBypassAlts = function() {
  1803. var serializedAtn = this.getSerializedATN();
  1804. if (serializedAtn === null) {
  1805. throw "The current parser does not support an ATN with bypass alternatives.";
  1806. }
  1807. var result = this.bypassAltsAtnCache[serializedAtn];
  1808. if (result === null) {
  1809. var deserializationOptions = new ATNDeserializationOptions();
  1810. deserializationOptions.generateRuleBypassTransitions = true;
  1811. result = new ATNDeserializer(deserializationOptions)
  1812. .deserialize(serializedAtn);
  1813. this.bypassAltsAtnCache[serializedAtn] = result;
  1814. }
  1815. return result;
  1816. };
  1817. // The preferred method of getting a tree pattern. For example, here's a
  1818. // sample use:
  1819. //
  1820. // <pre>
  1821. // ParseTree t = parser.expr();
  1822. // ParseTreePattern p = parser.compileParseTreePattern("&lt;ID&gt;+0",
  1823. // MyParser.RULE_expr);
  1824. // ParseTreeMatch m = p.match(t);
  1825. // String id = m.get("ID");
  1826. // </pre>
  1827. var Lexer = __webpack_require__(/*! ./Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
  1828. Parser.prototype.compileParseTreePattern = function(pattern, patternRuleIndex, lexer) {
  1829. lexer = lexer || null;
  1830. if (lexer === null) {
  1831. if (this.getTokenStream() !== null) {
  1832. var tokenSource = this.getTokenStream().tokenSource;
  1833. if (tokenSource instanceof Lexer) {
  1834. lexer = tokenSource;
  1835. }
  1836. }
  1837. }
  1838. if (lexer === null) {
  1839. throw "Parser can't discover a lexer to use";
  1840. }
  1841. var m = new ParseTreePatternMatcher(lexer, this);
  1842. return m.compile(pattern, patternRuleIndex);
  1843. };
  1844. Parser.prototype.getInputStream = function() {
  1845. return this.getTokenStream();
  1846. };
  1847. Parser.prototype.setInputStream = function(input) {
  1848. this.setTokenStream(input);
  1849. };
  1850. Parser.prototype.getTokenStream = function() {
  1851. return this._input;
  1852. };
  1853. // Set the token stream and reset the parser.//
  1854. Parser.prototype.setTokenStream = function(input) {
  1855. this._input = null;
  1856. this.reset();
  1857. this._input = input;
  1858. };
  1859. // Match needs to return the current input symbol, which gets put
  1860. // into the label for the associated token ref; e.g., x=ID.
  1861. //
  1862. Parser.prototype.getCurrentToken = function() {
  1863. return this._input.LT(1);
  1864. };
  1865. Parser.prototype.notifyErrorListeners = function(msg, offendingToken, err) {
  1866. offendingToken = offendingToken || null;
  1867. err = err || null;
  1868. if (offendingToken === null) {
  1869. offendingToken = this.getCurrentToken();
  1870. }
  1871. this._syntaxErrors += 1;
  1872. var line = offendingToken.line;
  1873. var column = offendingToken.column;
  1874. var listener = this.getErrorListenerDispatch();
  1875. listener.syntaxError(this, offendingToken, line, column, msg, err);
  1876. };
  1877. //
  1878. // Consume and return the {@linkplain //getCurrentToken current symbol}.
  1879. //
  1880. // <p>E.g., given the following input with {@code A} being the current
  1881. // lookahead symbol, this function moves the cursor to {@code B} and returns
  1882. // {@code A}.</p>
  1883. //
  1884. // <pre>
  1885. // A B
  1886. // ^
  1887. // </pre>
  1888. //
  1889. // If the parser is not in error recovery mode, the consumed symbol is added
  1890. // to the parse tree using {@link ParserRuleContext//addChild(Token)}, and
  1891. // {@link ParseTreeListener//visitTerminal} is called on any parse listeners.
  1892. // If the parser <em>is</em> in error recovery mode, the consumed symbol is
  1893. // added to the parse tree using
  1894. // {@link ParserRuleContext//addErrorNode(Token)}, and
  1895. // {@link ParseTreeListener//visitErrorNode} is called on any parse
  1896. // listeners.
  1897. //
  1898. Parser.prototype.consume = function() {
  1899. var o = this.getCurrentToken();
  1900. if (o.type !== Token.EOF) {
  1901. this.getInputStream().consume();
  1902. }
  1903. var hasListener = this._parseListeners !== null && this._parseListeners.length > 0;
  1904. if (this.buildParseTrees || hasListener) {
  1905. var node;
  1906. if (this._errHandler.inErrorRecoveryMode(this)) {
  1907. node = this._ctx.addErrorNode(o);
  1908. } else {
  1909. node = this._ctx.addTokenNode(o);
  1910. }
  1911. node.invokingState = this.state;
  1912. if (hasListener) {
  1913. this._parseListeners.map(function(listener) {
  1914. if (node instanceof ErrorNode || (node.isErrorNode !== undefined && node.isErrorNode())) {
  1915. listener.visitErrorNode(node);
  1916. } else if (node instanceof TerminalNode) {
  1917. listener.visitTerminal(node);
  1918. }
  1919. });
  1920. }
  1921. }
  1922. return o;
  1923. };
  1924. Parser.prototype.addContextToParseTree = function() {
  1925. // add current context to parent if we have a parent
  1926. if (this._ctx.parentCtx !== null) {
  1927. this._ctx.parentCtx.addChild(this._ctx);
  1928. }
  1929. };
  1930. // Always called by generated parsers upon entry to a rule. Access field
  1931. // {@link //_ctx} get the current context.
  1932. Parser.prototype.enterRule = function(localctx, state, ruleIndex) {
  1933. this.state = state;
  1934. this._ctx = localctx;
  1935. this._ctx.start = this._input.LT(1);
  1936. if (this.buildParseTrees) {
  1937. this.addContextToParseTree();
  1938. }
  1939. if (this._parseListeners !== null) {
  1940. this.triggerEnterRuleEvent();
  1941. }
  1942. };
  1943. Parser.prototype.exitRule = function() {
  1944. this._ctx.stop = this._input.LT(-1);
  1945. // trigger event on _ctx, before it reverts to parent
  1946. if (this._parseListeners !== null) {
  1947. this.triggerExitRuleEvent();
  1948. }
  1949. this.state = this._ctx.invokingState;
  1950. this._ctx = this._ctx.parentCtx;
  1951. };
  1952. Parser.prototype.enterOuterAlt = function(localctx, altNum) {
  1953. localctx.setAltNumber(altNum);
  1954. // if we have new localctx, make sure we replace existing ctx
  1955. // that is previous child of parse tree
  1956. if (this.buildParseTrees && this._ctx !== localctx) {
  1957. if (this._ctx.parentCtx !== null) {
  1958. this._ctx.parentCtx.removeLastChild();
  1959. this._ctx.parentCtx.addChild(localctx);
  1960. }
  1961. }
  1962. this._ctx = localctx;
  1963. };
  1964. // Get the precedence level for the top-most precedence rule.
  1965. //
  1966. // @return The precedence level for the top-most precedence rule, or -1 if
  1967. // the parser context is not nested within a precedence rule.
  1968. Parser.prototype.getPrecedence = function() {
  1969. if (this._precedenceStack.length === 0) {
  1970. return -1;
  1971. } else {
  1972. return this._precedenceStack[this._precedenceStack.length-1];
  1973. }
  1974. };
  1975. Parser.prototype.enterRecursionRule = function(localctx, state, ruleIndex,
  1976. precedence) {
  1977. this.state = state;
  1978. this._precedenceStack.push(precedence);
  1979. this._ctx = localctx;
  1980. this._ctx.start = this._input.LT(1);
  1981. if (this._parseListeners !== null) {
  1982. this.triggerEnterRuleEvent(); // simulates rule entry for
  1983. // left-recursive rules
  1984. }
  1985. };
  1986. //
  1987. // Like {@link //enterRule} but for recursive rules.
  1988. Parser.prototype.pushNewRecursionContext = function(localctx, state, ruleIndex) {
  1989. var previous = this._ctx;
  1990. previous.parentCtx = localctx;
  1991. previous.invokingState = state;
  1992. previous.stop = this._input.LT(-1);
  1993. this._ctx = localctx;
  1994. this._ctx.start = previous.start;
  1995. if (this.buildParseTrees) {
  1996. this._ctx.addChild(previous);
  1997. }
  1998. if (this._parseListeners !== null) {
  1999. this.triggerEnterRuleEvent(); // simulates rule entry for
  2000. // left-recursive rules
  2001. }
  2002. };
  2003. Parser.prototype.unrollRecursionContexts = function(parentCtx) {
  2004. this._precedenceStack.pop();
  2005. this._ctx.stop = this._input.LT(-1);
  2006. var retCtx = this._ctx; // save current ctx (return value)
  2007. // unroll so _ctx is as it was before call to recursive method
  2008. if (this._parseListeners !== null) {
  2009. while (this._ctx !== parentCtx) {
  2010. this.triggerExitRuleEvent();
  2011. this._ctx = this._ctx.parentCtx;
  2012. }
  2013. } else {
  2014. this._ctx = parentCtx;
  2015. }
  2016. // hook into tree
  2017. retCtx.parentCtx = parentCtx;
  2018. if (this.buildParseTrees && parentCtx !== null) {
  2019. // add return ctx into invoking rule's tree
  2020. parentCtx.addChild(retCtx);
  2021. }
  2022. };
  2023. Parser.prototype.getInvokingContext = function(ruleIndex) {
  2024. var ctx = this._ctx;
  2025. while (ctx !== null) {
  2026. if (ctx.ruleIndex === ruleIndex) {
  2027. return ctx;
  2028. }
  2029. ctx = ctx.parentCtx;
  2030. }
  2031. return null;
  2032. };
  2033. Parser.prototype.precpred = function(localctx, precedence) {
  2034. return precedence >= this._precedenceStack[this._precedenceStack.length-1];
  2035. };
  2036. Parser.prototype.inContext = function(context) {
  2037. // TODO: useful in parser?
  2038. return false;
  2039. };
  2040. //
  2041. // Checks whether or not {@code symbol} can follow the current state in the
  2042. // ATN. The behavior of this method is equivalent to the following, but is
  2043. // implemented such that the complete context-sensitive follow set does not
  2044. // need to be explicitly constructed.
  2045. //
  2046. // <pre>
  2047. // return getExpectedTokens().contains(symbol);
  2048. // </pre>
  2049. //
  2050. // @param symbol the symbol type to check
  2051. // @return {@code true} if {@code symbol} can follow the current state in
  2052. // the ATN, otherwise {@code false}.
  2053. Parser.prototype.isExpectedToken = function(symbol) {
  2054. var atn = this._interp.atn;
  2055. var ctx = this._ctx;
  2056. var s = atn.states[this.state];
  2057. var following = atn.nextTokens(s);
  2058. if (following.contains(symbol)) {
  2059. return true;
  2060. }
  2061. if (!following.contains(Token.EPSILON)) {
  2062. return false;
  2063. }
  2064. while (ctx !== null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) {
  2065. var invokingState = atn.states[ctx.invokingState];
  2066. var rt = invokingState.transitions[0];
  2067. following = atn.nextTokens(rt.followState);
  2068. if (following.contains(symbol)) {
  2069. return true;
  2070. }
  2071. ctx = ctx.parentCtx;
  2072. }
  2073. if (following.contains(Token.EPSILON) && symbol === Token.EOF) {
  2074. return true;
  2075. } else {
  2076. return false;
  2077. }
  2078. };
  2079. // Computes the set of input symbols which could follow the current parser
  2080. // state and context, as given by {@link //getState} and {@link //getContext},
  2081. // respectively.
  2082. //
  2083. // @see ATN//getExpectedTokens(int, RuleContext)
  2084. //
  2085. Parser.prototype.getExpectedTokens = function() {
  2086. return this._interp.atn.getExpectedTokens(this.state, this._ctx);
  2087. };
  2088. Parser.prototype.getExpectedTokensWithinCurrentRule = function() {
  2089. var atn = this._interp.atn;
  2090. var s = atn.states[this.state];
  2091. return atn.nextTokens(s);
  2092. };
  2093. // Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found.//
  2094. Parser.prototype.getRuleIndex = function(ruleName) {
  2095. var ruleIndex = this.getRuleIndexMap()[ruleName];
  2096. if (ruleIndex !== null) {
  2097. return ruleIndex;
  2098. } else {
  2099. return -1;
  2100. }
  2101. };
  2102. // Return List&lt;String&gt; of the rule names in your parser instance
  2103. // leading up to a call to the current rule. You could override if
  2104. // you want more details such as the file/line info of where
  2105. // in the ATN a rule is invoked.
  2106. //
  2107. // this is very useful for error messages.
  2108. //
  2109. Parser.prototype.getRuleInvocationStack = function(p) {
  2110. p = p || null;
  2111. if (p === null) {
  2112. p = this._ctx;
  2113. }
  2114. var stack = [];
  2115. while (p !== null) {
  2116. // compute what follows who invoked us
  2117. var ruleIndex = p.ruleIndex;
  2118. if (ruleIndex < 0) {
  2119. stack.push("n/a");
  2120. } else {
  2121. stack.push(this.ruleNames[ruleIndex]);
  2122. }
  2123. p = p.parentCtx;
  2124. }
  2125. return stack;
  2126. };
  2127. // For debugging and other purposes.//
  2128. Parser.prototype.getDFAStrings = function() {
  2129. return this._interp.decisionToDFA.toString();
  2130. };
  2131. // For debugging and other purposes.//
  2132. Parser.prototype.dumpDFA = function() {
  2133. var seenOne = false;
  2134. for (var i = 0; i < this._interp.decisionToDFA.length; i++) {
  2135. var dfa = this._interp.decisionToDFA[i];
  2136. if (dfa.states.length > 0) {
  2137. if (seenOne) {
  2138. console.log();
  2139. }
  2140. this.printer.println("Decision " + dfa.decision + ":");
  2141. this.printer.print(dfa.toString(this.literalNames, this.symbolicNames));
  2142. seenOne = true;
  2143. }
  2144. }
  2145. };
  2146. /*
  2147. " printer = function() {\r\n" +
  2148. " this.println = function(s) { document.getElementById('output') += s + '\\n'; }\r\n" +
  2149. " this.print = function(s) { document.getElementById('output') += s; }\r\n" +
  2150. " };\r\n" +
  2151. */
  2152. Parser.prototype.getSourceName = function() {
  2153. return this._input.sourceName;
  2154. };
  2155. // During a parse is sometimes useful to listen in on the rule entry and exit
  2156. // events as well as token matches. this is for quick and dirty debugging.
  2157. //
  2158. Parser.prototype.setTrace = function(trace) {
  2159. if (!trace) {
  2160. this.removeParseListener(this._tracer);
  2161. this._tracer = null;
  2162. } else {
  2163. if (this._tracer !== null) {
  2164. this.removeParseListener(this._tracer);
  2165. }
  2166. this._tracer = new TraceListener(this);
  2167. this.addParseListener(this._tracer);
  2168. }
  2169. };
  2170. exports.Parser = Parser;
  2171. /***/ }),
  2172. /***/ "./node_modules/antlr4/ParserRuleContext.js":
  2173. /*!**************************************************!*\
  2174. !*** ./node_modules/antlr4/ParserRuleContext.js ***!
  2175. \**************************************************/
  2176. /*! no static exports found */
  2177. /***/ (function(module, exports, __webpack_require__) {
  2178. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  2179. * Use of this file is governed by the BSD 3-clause license that
  2180. * can be found in the LICENSE.txt file in the project root.
  2181. */
  2182. //* A rule invocation record for parsing.
  2183. //
  2184. // Contains all of the information about the current rule not stored in the
  2185. // RuleContext. It handles parse tree children list, Any ATN state
  2186. // tracing, and the default values available for rule indications:
  2187. // start, stop, rule index, current alt number, current
  2188. // ATN state.
  2189. //
  2190. // Subclasses made for each rule and grammar track the parameters,
  2191. // return values, locals, and labels specific to that rule. These
  2192. // are the objects that are returned from rules.
  2193. //
  2194. // Note text is not an actual field of a rule return value; it is computed
  2195. // from start and stop using the input stream's toString() method. I
  2196. // could add a ctor to this so that we can pass in and store the input
  2197. // stream, but I'm not sure we want to do that. It would seem to be undefined
  2198. // to get the .text property anyway if the rule matches tokens from multiple
  2199. // input streams.
  2200. //
  2201. // I do not use getters for fields of objects that are used simply to
  2202. // group values such as this aggregate. The getters/setters are there to
  2203. // satisfy the superclass interface.
  2204. var RuleContext = __webpack_require__(/*! ./RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
  2205. var Tree = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js");
  2206. var INVALID_INTERVAL = Tree.INVALID_INTERVAL;
  2207. var TerminalNode = Tree.TerminalNode;
  2208. var TerminalNodeImpl = Tree.TerminalNodeImpl;
  2209. var ErrorNodeImpl = Tree.ErrorNodeImpl;
  2210. var Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  2211. function ParserRuleContext(parent, invokingStateNumber) {
  2212. parent = parent || null;
  2213. invokingStateNumber = invokingStateNumber || null;
  2214. RuleContext.call(this, parent, invokingStateNumber);
  2215. this.ruleIndex = -1;
  2216. // * If we are debugging or building a parse tree for a visitor,
  2217. // we need to track all of the tokens and rule invocations associated
  2218. // with this rule's context. This is empty for parsing w/o tree constr.
  2219. // operation because we don't the need to track the details about
  2220. // how we parse this rule.
  2221. // /
  2222. this.children = null;
  2223. this.start = null;
  2224. this.stop = null;
  2225. // The exception that forced this rule to return. If the rule successfully
  2226. // completed, this is {@code null}.
  2227. this.exception = null;
  2228. }
  2229. ParserRuleContext.prototype = Object.create(RuleContext.prototype);
  2230. ParserRuleContext.prototype.constructor = ParserRuleContext;
  2231. // * COPY a ctx (I'm deliberately not using copy constructor)///
  2232. ParserRuleContext.prototype.copyFrom = function(ctx) {
  2233. // from RuleContext
  2234. this.parentCtx = ctx.parentCtx;
  2235. this.invokingState = ctx.invokingState;
  2236. this.children = null;
  2237. this.start = ctx.start;
  2238. this.stop = ctx.stop;
  2239. // copy any error nodes to alt label node
  2240. if(ctx.children) {
  2241. this.children = [];
  2242. // reset parent pointer for any error nodes
  2243. ctx.children.map(function(child) {
  2244. if (child instanceof ErrorNodeImpl) {
  2245. this.children.push(child);
  2246. child.parentCtx = this;
  2247. }
  2248. }, this);
  2249. }
  2250. };
  2251. // Double dispatch methods for listeners
  2252. ParserRuleContext.prototype.enterRule = function(listener) {
  2253. };
  2254. ParserRuleContext.prototype.exitRule = function(listener) {
  2255. };
  2256. // * Does not set parent link; other add methods do that///
  2257. ParserRuleContext.prototype.addChild = function(child) {
  2258. if (this.children === null) {
  2259. this.children = [];
  2260. }
  2261. this.children.push(child);
  2262. return child;
  2263. };
  2264. // * Used by enterOuterAlt to toss out a RuleContext previously added as
  2265. // we entered a rule. If we have // label, we will need to remove
  2266. // generic ruleContext object.
  2267. // /
  2268. ParserRuleContext.prototype.removeLastChild = function() {
  2269. if (this.children !== null) {
  2270. this.children.pop();
  2271. }
  2272. };
  2273. ParserRuleContext.prototype.addTokenNode = function(token) {
  2274. var node = new TerminalNodeImpl(token);
  2275. this.addChild(node);
  2276. node.parentCtx = this;
  2277. return node;
  2278. };
  2279. ParserRuleContext.prototype.addErrorNode = function(badToken) {
  2280. var node = new ErrorNodeImpl(badToken);
  2281. this.addChild(node);
  2282. node.parentCtx = this;
  2283. return node;
  2284. };
  2285. ParserRuleContext.prototype.getChild = function(i, type) {
  2286. type = type || null;
  2287. if (this.children === null || i < 0 || i >= this.children.length) {
  2288. return null;
  2289. }
  2290. if (type === null) {
  2291. return this.children[i];
  2292. } else {
  2293. for(var j=0; j<this.children.length; j++) {
  2294. var child = this.children[j];
  2295. if(child instanceof type) {
  2296. if(i===0) {
  2297. return child;
  2298. } else {
  2299. i -= 1;
  2300. }
  2301. }
  2302. }
  2303. return null;
  2304. }
  2305. };
  2306. ParserRuleContext.prototype.getToken = function(ttype, i) {
  2307. if (this.children === null || i < 0 || i >= this.children.length) {
  2308. return null;
  2309. }
  2310. for(var j=0; j<this.children.length; j++) {
  2311. var child = this.children[j];
  2312. if (child instanceof TerminalNode) {
  2313. if (child.symbol.type === ttype) {
  2314. if(i===0) {
  2315. return child;
  2316. } else {
  2317. i -= 1;
  2318. }
  2319. }
  2320. }
  2321. }
  2322. return null;
  2323. };
  2324. ParserRuleContext.prototype.getTokens = function(ttype ) {
  2325. if (this.children=== null) {
  2326. return [];
  2327. } else {
  2328. var tokens = [];
  2329. for(var j=0; j<this.children.length; j++) {
  2330. var child = this.children[j];
  2331. if (child instanceof TerminalNode) {
  2332. if (child.symbol.type === ttype) {
  2333. tokens.push(child);
  2334. }
  2335. }
  2336. }
  2337. return tokens;
  2338. }
  2339. };
  2340. ParserRuleContext.prototype.getTypedRuleContext = function(ctxType, i) {
  2341. return this.getChild(i, ctxType);
  2342. };
  2343. ParserRuleContext.prototype.getTypedRuleContexts = function(ctxType) {
  2344. if (this.children=== null) {
  2345. return [];
  2346. } else {
  2347. var contexts = [];
  2348. for(var j=0; j<this.children.length; j++) {
  2349. var child = this.children[j];
  2350. if (child instanceof ctxType) {
  2351. contexts.push(child);
  2352. }
  2353. }
  2354. return contexts;
  2355. }
  2356. };
  2357. ParserRuleContext.prototype.getChildCount = function() {
  2358. if (this.children=== null) {
  2359. return 0;
  2360. } else {
  2361. return this.children.length;
  2362. }
  2363. };
  2364. ParserRuleContext.prototype.getSourceInterval = function() {
  2365. if( this.start === null || this.stop === null) {
  2366. return INVALID_INTERVAL;
  2367. } else {
  2368. return new Interval(this.start.tokenIndex, this.stop.tokenIndex);
  2369. }
  2370. };
  2371. RuleContext.EMPTY = new ParserRuleContext();
  2372. function InterpreterRuleContext(parent, invokingStateNumber, ruleIndex) {
  2373. ParserRuleContext.call(parent, invokingStateNumber);
  2374. this.ruleIndex = ruleIndex;
  2375. return this;
  2376. }
  2377. InterpreterRuleContext.prototype = Object.create(ParserRuleContext.prototype);
  2378. InterpreterRuleContext.prototype.constructor = InterpreterRuleContext;
  2379. exports.ParserRuleContext = ParserRuleContext;
  2380. /***/ }),
  2381. /***/ "./node_modules/antlr4/PredictionContext.js":
  2382. /*!**************************************************!*\
  2383. !*** ./node_modules/antlr4/PredictionContext.js ***!
  2384. \**************************************************/
  2385. /*! no static exports found */
  2386. /***/ (function(module, exports, __webpack_require__) {
  2387. //
  2388. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  2389. * Use of this file is governed by the BSD 3-clause license that
  2390. * can be found in the LICENSE.txt file in the project root.
  2391. */
  2392. ///
  2393. var RuleContext = __webpack_require__(/*! ./RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
  2394. var Hash = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").Hash;
  2395. function PredictionContext(cachedHashCode) {
  2396. this.cachedHashCode = cachedHashCode;
  2397. }
  2398. // Represents {@code $} in local context prediction, which means wildcard.
  2399. // {@code//+x =//}.
  2400. // /
  2401. PredictionContext.EMPTY = null;
  2402. // Represents {@code $} in an array in full context mode, when {@code $}
  2403. // doesn't mean wildcard: {@code $ + x = [$,x]}. Here,
  2404. // {@code $} = {@link //EMPTY_RETURN_STATE}.
  2405. // /
  2406. PredictionContext.EMPTY_RETURN_STATE = 0x7FFFFFFF;
  2407. PredictionContext.globalNodeCount = 1;
  2408. PredictionContext.id = PredictionContext.globalNodeCount;
  2409. // Stores the computed hash code of this {@link PredictionContext}. The hash
  2410. // code is computed in parts to match the following reference algorithm.
  2411. //
  2412. // <pre>
  2413. // private int referenceHashCode() {
  2414. // int hash = {@link MurmurHash//initialize MurmurHash.initialize}({@link
  2415. // //INITIAL_HASH});
  2416. //
  2417. // for (int i = 0; i &lt; {@link //size()}; i++) {
  2418. // hash = {@link MurmurHash//update MurmurHash.update}(hash, {@link //getParent
  2419. // getParent}(i));
  2420. // }
  2421. //
  2422. // for (int i = 0; i &lt; {@link //size()}; i++) {
  2423. // hash = {@link MurmurHash//update MurmurHash.update}(hash, {@link
  2424. // //getReturnState getReturnState}(i));
  2425. // }
  2426. //
  2427. // hash = {@link MurmurHash//finish MurmurHash.finish}(hash, 2// {@link
  2428. // //size()});
  2429. // return hash;
  2430. // }
  2431. // </pre>
  2432. // /
  2433. // This means only the {@link //EMPTY} context is in set.
  2434. PredictionContext.prototype.isEmpty = function() {
  2435. return this === PredictionContext.EMPTY;
  2436. };
  2437. PredictionContext.prototype.hasEmptyPath = function() {
  2438. return this.getReturnState(this.length - 1) === PredictionContext.EMPTY_RETURN_STATE;
  2439. };
  2440. PredictionContext.prototype.hashCode = function() {
  2441. return this.cachedHashCode;
  2442. };
  2443. PredictionContext.prototype.updateHashCode = function(hash) {
  2444. hash.update(this.cachedHashCode);
  2445. };
  2446. /*
  2447. function calculateHashString(parent, returnState) {
  2448. return "" + parent + returnState;
  2449. }
  2450. */
  2451. // Used to cache {@link PredictionContext} objects. Its used for the shared
  2452. // context cash associated with contexts in DFA states. This cache
  2453. // can be used for both lexers and parsers.
  2454. function PredictionContextCache() {
  2455. this.cache = {};
  2456. return this;
  2457. }
  2458. // Add a context to the cache and return it. If the context already exists,
  2459. // return that one instead and do not add a new context to the cache.
  2460. // Protect shared cache from unsafe thread access.
  2461. //
  2462. PredictionContextCache.prototype.add = function(ctx) {
  2463. if (ctx === PredictionContext.EMPTY) {
  2464. return PredictionContext.EMPTY;
  2465. }
  2466. var existing = this.cache[ctx] || null;
  2467. if (existing !== null) {
  2468. return existing;
  2469. }
  2470. this.cache[ctx] = ctx;
  2471. return ctx;
  2472. };
  2473. PredictionContextCache.prototype.get = function(ctx) {
  2474. return this.cache[ctx] || null;
  2475. };
  2476. Object.defineProperty(PredictionContextCache.prototype, "length", {
  2477. get : function() {
  2478. return this.cache.length;
  2479. }
  2480. });
  2481. function SingletonPredictionContext(parent, returnState) {
  2482. var hashCode = 0;
  2483. if(parent !== null) {
  2484. var hash = new Hash();
  2485. hash.update(parent, returnState);
  2486. hashCode = hash.finish();
  2487. }
  2488. PredictionContext.call(this, hashCode);
  2489. this.parentCtx = parent;
  2490. this.returnState = returnState;
  2491. }
  2492. SingletonPredictionContext.prototype = Object.create(PredictionContext.prototype);
  2493. SingletonPredictionContext.prototype.contructor = SingletonPredictionContext;
  2494. SingletonPredictionContext.create = function(parent, returnState) {
  2495. if (returnState === PredictionContext.EMPTY_RETURN_STATE && parent === null) {
  2496. // someone can pass in the bits of an array ctx that mean $
  2497. return PredictionContext.EMPTY;
  2498. } else {
  2499. return new SingletonPredictionContext(parent, returnState);
  2500. }
  2501. };
  2502. Object.defineProperty(SingletonPredictionContext.prototype, "length", {
  2503. get : function() {
  2504. return 1;
  2505. }
  2506. });
  2507. SingletonPredictionContext.prototype.getParent = function(index) {
  2508. return this.parentCtx;
  2509. };
  2510. SingletonPredictionContext.prototype.getReturnState = function(index) {
  2511. return this.returnState;
  2512. };
  2513. SingletonPredictionContext.prototype.equals = function(other) {
  2514. if (this === other) {
  2515. return true;
  2516. } else if (!(other instanceof SingletonPredictionContext)) {
  2517. return false;
  2518. } else if (this.hashCode() !== other.hashCode()) {
  2519. return false; // can't be same if hash is different
  2520. } else {
  2521. if(this.returnState !== other.returnState)
  2522. return false;
  2523. else if(this.parentCtx==null)
  2524. return other.parentCtx==null
  2525. else
  2526. return this.parentCtx.equals(other.parentCtx);
  2527. }
  2528. };
  2529. SingletonPredictionContext.prototype.toString = function() {
  2530. var up = this.parentCtx === null ? "" : this.parentCtx.toString();
  2531. if (up.length === 0) {
  2532. if (this.returnState === PredictionContext.EMPTY_RETURN_STATE) {
  2533. return "$";
  2534. } else {
  2535. return "" + this.returnState;
  2536. }
  2537. } else {
  2538. return "" + this.returnState + " " + up;
  2539. }
  2540. };
  2541. function EmptyPredictionContext() {
  2542. SingletonPredictionContext.call(this, null, PredictionContext.EMPTY_RETURN_STATE);
  2543. return this;
  2544. }
  2545. EmptyPredictionContext.prototype = Object.create(SingletonPredictionContext.prototype);
  2546. EmptyPredictionContext.prototype.constructor = EmptyPredictionContext;
  2547. EmptyPredictionContext.prototype.isEmpty = function() {
  2548. return true;
  2549. };
  2550. EmptyPredictionContext.prototype.getParent = function(index) {
  2551. return null;
  2552. };
  2553. EmptyPredictionContext.prototype.getReturnState = function(index) {
  2554. return this.returnState;
  2555. };
  2556. EmptyPredictionContext.prototype.equals = function(other) {
  2557. return this === other;
  2558. };
  2559. EmptyPredictionContext.prototype.toString = function() {
  2560. return "$";
  2561. };
  2562. PredictionContext.EMPTY = new EmptyPredictionContext();
  2563. function ArrayPredictionContext(parents, returnStates) {
  2564. // Parent can be null only if full ctx mode and we make an array
  2565. // from {@link //EMPTY} and non-empty. We merge {@link //EMPTY} by using
  2566. // null parent and
  2567. // returnState == {@link //EMPTY_RETURN_STATE}.
  2568. var h = new Hash();
  2569. h.update(parents, returnStates);
  2570. var hashCode = h.finish();
  2571. PredictionContext.call(this, hashCode);
  2572. this.parents = parents;
  2573. this.returnStates = returnStates;
  2574. return this;
  2575. }
  2576. ArrayPredictionContext.prototype = Object.create(PredictionContext.prototype);
  2577. ArrayPredictionContext.prototype.constructor = ArrayPredictionContext;
  2578. ArrayPredictionContext.prototype.isEmpty = function() {
  2579. // since EMPTY_RETURN_STATE can only appear in the last position, we
  2580. // don't need to verify that size==1
  2581. return this.returnStates[0] === PredictionContext.EMPTY_RETURN_STATE;
  2582. };
  2583. Object.defineProperty(ArrayPredictionContext.prototype, "length", {
  2584. get : function() {
  2585. return this.returnStates.length;
  2586. }
  2587. });
  2588. ArrayPredictionContext.prototype.getParent = function(index) {
  2589. return this.parents[index];
  2590. };
  2591. ArrayPredictionContext.prototype.getReturnState = function(index) {
  2592. return this.returnStates[index];
  2593. };
  2594. ArrayPredictionContext.prototype.equals = function(other) {
  2595. if (this === other) {
  2596. return true;
  2597. } else if (!(other instanceof ArrayPredictionContext)) {
  2598. return false;
  2599. } else if (this.hashCode() !== other.hashCode()) {
  2600. return false; // can't be same if hash is different
  2601. } else {
  2602. return this.returnStates === other.returnStates &&
  2603. this.parents === other.parents;
  2604. }
  2605. };
  2606. ArrayPredictionContext.prototype.toString = function() {
  2607. if (this.isEmpty()) {
  2608. return "[]";
  2609. } else {
  2610. var s = "[";
  2611. for (var i = 0; i < this.returnStates.length; i++) {
  2612. if (i > 0) {
  2613. s = s + ", ";
  2614. }
  2615. if (this.returnStates[i] === PredictionContext.EMPTY_RETURN_STATE) {
  2616. s = s + "$";
  2617. continue;
  2618. }
  2619. s = s + this.returnStates[i];
  2620. if (this.parents[i] !== null) {
  2621. s = s + " " + this.parents[i];
  2622. } else {
  2623. s = s + "null";
  2624. }
  2625. }
  2626. return s + "]";
  2627. }
  2628. };
  2629. // Convert a {@link RuleContext} tree to a {@link PredictionContext} graph.
  2630. // Return {@link //EMPTY} if {@code outerContext} is empty or null.
  2631. // /
  2632. function predictionContextFromRuleContext(atn, outerContext) {
  2633. if (outerContext === undefined || outerContext === null) {
  2634. outerContext = RuleContext.EMPTY;
  2635. }
  2636. // if we are in RuleContext of start rule, s, then PredictionContext
  2637. // is EMPTY. Nobody called us. (if we are empty, return empty)
  2638. if (outerContext.parentCtx === null || outerContext === RuleContext.EMPTY) {
  2639. return PredictionContext.EMPTY;
  2640. }
  2641. // If we have a parent, convert it to a PredictionContext graph
  2642. var parent = predictionContextFromRuleContext(atn, outerContext.parentCtx);
  2643. var state = atn.states[outerContext.invokingState];
  2644. var transition = state.transitions[0];
  2645. return SingletonPredictionContext.create(parent, transition.followState.stateNumber);
  2646. }
  2647. /*
  2648. function calculateListsHashString(parents, returnStates) {
  2649. var s = "";
  2650. parents.map(function(p) {
  2651. s = s + p;
  2652. });
  2653. returnStates.map(function(r) {
  2654. s = s + r;
  2655. });
  2656. return s;
  2657. }
  2658. */
  2659. function merge(a, b, rootIsWildcard, mergeCache) {
  2660. // share same graph if both same
  2661. if (a === b) {
  2662. return a;
  2663. }
  2664. if (a instanceof SingletonPredictionContext && b instanceof SingletonPredictionContext) {
  2665. return mergeSingletons(a, b, rootIsWildcard, mergeCache);
  2666. }
  2667. // At least one of a or b is array
  2668. // If one is $ and rootIsWildcard, return $ as// wildcard
  2669. if (rootIsWildcard) {
  2670. if (a instanceof EmptyPredictionContext) {
  2671. return a;
  2672. }
  2673. if (b instanceof EmptyPredictionContext) {
  2674. return b;
  2675. }
  2676. }
  2677. // convert singleton so both are arrays to normalize
  2678. if (a instanceof SingletonPredictionContext) {
  2679. a = new ArrayPredictionContext([a.getParent()], [a.returnState]);
  2680. }
  2681. if (b instanceof SingletonPredictionContext) {
  2682. b = new ArrayPredictionContext([b.getParent()], [b.returnState]);
  2683. }
  2684. return mergeArrays(a, b, rootIsWildcard, mergeCache);
  2685. }
  2686. //
  2687. // Merge two {@link SingletonPredictionContext} instances.
  2688. //
  2689. // <p>Stack tops equal, parents merge is same; return left graph.<br>
  2690. // <embed src="images/SingletonMerge_SameRootSamePar.svg"
  2691. // type="image/svg+xml"/></p>
  2692. //
  2693. // <p>Same stack top, parents differ; merge parents giving array node, then
  2694. // remainders of those graphs. A new root node is created to point to the
  2695. // merged parents.<br>
  2696. // <embed src="images/SingletonMerge_SameRootDiffPar.svg"
  2697. // type="image/svg+xml"/></p>
  2698. //
  2699. // <p>Different stack tops pointing to same parent. Make array node for the
  2700. // root where both element in the root point to the same (original)
  2701. // parent.<br>
  2702. // <embed src="images/SingletonMerge_DiffRootSamePar.svg"
  2703. // type="image/svg+xml"/></p>
  2704. //
  2705. // <p>Different stack tops pointing to different parents. Make array node for
  2706. // the root where each element points to the corresponding original
  2707. // parent.<br>
  2708. // <embed src="images/SingletonMerge_DiffRootDiffPar.svg"
  2709. // type="image/svg+xml"/></p>
  2710. //
  2711. // @param a the first {@link SingletonPredictionContext}
  2712. // @param b the second {@link SingletonPredictionContext}
  2713. // @param rootIsWildcard {@code true} if this is a local-context merge,
  2714. // otherwise false to indicate a full-context merge
  2715. // @param mergeCache
  2716. // /
  2717. function mergeSingletons(a, b, rootIsWildcard, mergeCache) {
  2718. if (mergeCache !== null) {
  2719. var previous = mergeCache.get(a, b);
  2720. if (previous !== null) {
  2721. return previous;
  2722. }
  2723. previous = mergeCache.get(b, a);
  2724. if (previous !== null) {
  2725. return previous;
  2726. }
  2727. }
  2728. var rootMerge = mergeRoot(a, b, rootIsWildcard);
  2729. if (rootMerge !== null) {
  2730. if (mergeCache !== null) {
  2731. mergeCache.set(a, b, rootMerge);
  2732. }
  2733. return rootMerge;
  2734. }
  2735. if (a.returnState === b.returnState) {
  2736. var parent = merge(a.parentCtx, b.parentCtx, rootIsWildcard, mergeCache);
  2737. // if parent is same as existing a or b parent or reduced to a parent,
  2738. // return it
  2739. if (parent === a.parentCtx) {
  2740. return a; // ax + bx = ax, if a=b
  2741. }
  2742. if (parent === b.parentCtx) {
  2743. return b; // ax + bx = bx, if a=b
  2744. }
  2745. // else: ax + ay = a'[x,y]
  2746. // merge parents x and y, giving array node with x,y then remainders
  2747. // of those graphs. dup a, a' points at merged array
  2748. // new joined parent so create new singleton pointing to it, a'
  2749. var spc = SingletonPredictionContext.create(parent, a.returnState);
  2750. if (mergeCache !== null) {
  2751. mergeCache.set(a, b, spc);
  2752. }
  2753. return spc;
  2754. } else { // a != b payloads differ
  2755. // see if we can collapse parents due to $+x parents if local ctx
  2756. var singleParent = null;
  2757. if (a === b || (a.parentCtx !== null && a.parentCtx === b.parentCtx)) { // ax +
  2758. // bx =
  2759. // [a,b]x
  2760. singleParent = a.parentCtx;
  2761. }
  2762. if (singleParent !== null) { // parents are same
  2763. // sort payloads and use same parent
  2764. var payloads = [ a.returnState, b.returnState ];
  2765. if (a.returnState > b.returnState) {
  2766. payloads[0] = b.returnState;
  2767. payloads[1] = a.returnState;
  2768. }
  2769. var parents = [ singleParent, singleParent ];
  2770. var apc = new ArrayPredictionContext(parents, payloads);
  2771. if (mergeCache !== null) {
  2772. mergeCache.set(a, b, apc);
  2773. }
  2774. return apc;
  2775. }
  2776. // parents differ and can't merge them. Just pack together
  2777. // into array; can't merge.
  2778. // ax + by = [ax,by]
  2779. var payloads = [ a.returnState, b.returnState ];
  2780. var parents = [ a.parentCtx, b.parentCtx ];
  2781. if (a.returnState > b.returnState) { // sort by payload
  2782. payloads[0] = b.returnState;
  2783. payloads[1] = a.returnState;
  2784. parents = [ b.parentCtx, a.parentCtx ];
  2785. }
  2786. var a_ = new ArrayPredictionContext(parents, payloads);
  2787. if (mergeCache !== null) {
  2788. mergeCache.set(a, b, a_);
  2789. }
  2790. return a_;
  2791. }
  2792. }
  2793. //
  2794. // Handle case where at least one of {@code a} or {@code b} is
  2795. // {@link //EMPTY}. In the following diagrams, the symbol {@code $} is used
  2796. // to represent {@link //EMPTY}.
  2797. //
  2798. // <h2>Local-Context Merges</h2>
  2799. //
  2800. // <p>These local-context merge operations are used when {@code rootIsWildcard}
  2801. // is true.</p>
  2802. //
  2803. // <p>{@link //EMPTY} is superset of any graph; return {@link //EMPTY}.<br>
  2804. // <embed src="images/LocalMerge_EmptyRoot.svg" type="image/svg+xml"/></p>
  2805. //
  2806. // <p>{@link //EMPTY} and anything is {@code //EMPTY}, so merged parent is
  2807. // {@code //EMPTY}; return left graph.<br>
  2808. // <embed src="images/LocalMerge_EmptyParent.svg" type="image/svg+xml"/></p>
  2809. //
  2810. // <p>Special case of last merge if local context.<br>
  2811. // <embed src="images/LocalMerge_DiffRoots.svg" type="image/svg+xml"/></p>
  2812. //
  2813. // <h2>Full-Context Merges</h2>
  2814. //
  2815. // <p>These full-context merge operations are used when {@code rootIsWildcard}
  2816. // is false.</p>
  2817. //
  2818. // <p><embed src="images/FullMerge_EmptyRoots.svg" type="image/svg+xml"/></p>
  2819. //
  2820. // <p>Must keep all contexts; {@link //EMPTY} in array is a special value (and
  2821. // null parent).<br>
  2822. // <embed src="images/FullMerge_EmptyRoot.svg" type="image/svg+xml"/></p>
  2823. //
  2824. // <p><embed src="images/FullMerge_SameRoot.svg" type="image/svg+xml"/></p>
  2825. //
  2826. // @param a the first {@link SingletonPredictionContext}
  2827. // @param b the second {@link SingletonPredictionContext}
  2828. // @param rootIsWildcard {@code true} if this is a local-context merge,
  2829. // otherwise false to indicate a full-context merge
  2830. // /
  2831. function mergeRoot(a, b, rootIsWildcard) {
  2832. if (rootIsWildcard) {
  2833. if (a === PredictionContext.EMPTY) {
  2834. return PredictionContext.EMPTY; // // + b =//
  2835. }
  2836. if (b === PredictionContext.EMPTY) {
  2837. return PredictionContext.EMPTY; // a +// =//
  2838. }
  2839. } else {
  2840. if (a === PredictionContext.EMPTY && b === PredictionContext.EMPTY) {
  2841. return PredictionContext.EMPTY; // $ + $ = $
  2842. } else if (a === PredictionContext.EMPTY) { // $ + x = [$,x]
  2843. var payloads = [ b.returnState,
  2844. PredictionContext.EMPTY_RETURN_STATE ];
  2845. var parents = [ b.parentCtx, null ];
  2846. return new ArrayPredictionContext(parents, payloads);
  2847. } else if (b === PredictionContext.EMPTY) { // x + $ = [$,x] ($ is always first if present)
  2848. var payloads = [ a.returnState, PredictionContext.EMPTY_RETURN_STATE ];
  2849. var parents = [ a.parentCtx, null ];
  2850. return new ArrayPredictionContext(parents, payloads);
  2851. }
  2852. }
  2853. return null;
  2854. }
  2855. //
  2856. // Merge two {@link ArrayPredictionContext} instances.
  2857. //
  2858. // <p>Different tops, different parents.<br>
  2859. // <embed src="images/ArrayMerge_DiffTopDiffPar.svg" type="image/svg+xml"/></p>
  2860. //
  2861. // <p>Shared top, same parents.<br>
  2862. // <embed src="images/ArrayMerge_ShareTopSamePar.svg" type="image/svg+xml"/></p>
  2863. //
  2864. // <p>Shared top, different parents.<br>
  2865. // <embed src="images/ArrayMerge_ShareTopDiffPar.svg" type="image/svg+xml"/></p>
  2866. //
  2867. // <p>Shared top, all shared parents.<br>
  2868. // <embed src="images/ArrayMerge_ShareTopSharePar.svg"
  2869. // type="image/svg+xml"/></p>
  2870. //
  2871. // <p>Equal tops, merge parents and reduce top to
  2872. // {@link SingletonPredictionContext}.<br>
  2873. // <embed src="images/ArrayMerge_EqualTop.svg" type="image/svg+xml"/></p>
  2874. // /
  2875. function mergeArrays(a, b, rootIsWildcard, mergeCache) {
  2876. if (mergeCache !== null) {
  2877. var previous = mergeCache.get(a, b);
  2878. if (previous !== null) {
  2879. return previous;
  2880. }
  2881. previous = mergeCache.get(b, a);
  2882. if (previous !== null) {
  2883. return previous;
  2884. }
  2885. }
  2886. // merge sorted payloads a + b => M
  2887. var i = 0; // walks a
  2888. var j = 0; // walks b
  2889. var k = 0; // walks target M array
  2890. var mergedReturnStates = [];
  2891. var mergedParents = [];
  2892. // walk and merge to yield mergedParents, mergedReturnStates
  2893. while (i < a.returnStates.length && j < b.returnStates.length) {
  2894. var a_parent = a.parents[i];
  2895. var b_parent = b.parents[j];
  2896. if (a.returnStates[i] === b.returnStates[j]) {
  2897. // same payload (stack tops are equal), must yield merged singleton
  2898. var payload = a.returnStates[i];
  2899. // $+$ = $
  2900. var bothDollars = payload === PredictionContext.EMPTY_RETURN_STATE &&
  2901. a_parent === null && b_parent === null;
  2902. var ax_ax = (a_parent !== null && b_parent !== null && a_parent === b_parent); // ax+ax
  2903. // ->
  2904. // ax
  2905. if (bothDollars || ax_ax) {
  2906. mergedParents[k] = a_parent; // choose left
  2907. mergedReturnStates[k] = payload;
  2908. } else { // ax+ay -> a'[x,y]
  2909. var mergedParent = merge(a_parent, b_parent, rootIsWildcard, mergeCache);
  2910. mergedParents[k] = mergedParent;
  2911. mergedReturnStates[k] = payload;
  2912. }
  2913. i += 1; // hop over left one as usual
  2914. j += 1; // but also skip one in right side since we merge
  2915. } else if (a.returnStates[i] < b.returnStates[j]) { // copy a[i] to M
  2916. mergedParents[k] = a_parent;
  2917. mergedReturnStates[k] = a.returnStates[i];
  2918. i += 1;
  2919. } else { // b > a, copy b[j] to M
  2920. mergedParents[k] = b_parent;
  2921. mergedReturnStates[k] = b.returnStates[j];
  2922. j += 1;
  2923. }
  2924. k += 1;
  2925. }
  2926. // copy over any payloads remaining in either array
  2927. if (i < a.returnStates.length) {
  2928. for (var p = i; p < a.returnStates.length; p++) {
  2929. mergedParents[k] = a.parents[p];
  2930. mergedReturnStates[k] = a.returnStates[p];
  2931. k += 1;
  2932. }
  2933. } else {
  2934. for (var p = j; p < b.returnStates.length; p++) {
  2935. mergedParents[k] = b.parents[p];
  2936. mergedReturnStates[k] = b.returnStates[p];
  2937. k += 1;
  2938. }
  2939. }
  2940. // trim merged if we combined a few that had same stack tops
  2941. if (k < mergedParents.length) { // write index < last position; trim
  2942. if (k === 1) { // for just one merged element, return singleton top
  2943. var a_ = SingletonPredictionContext.create(mergedParents[0],
  2944. mergedReturnStates[0]);
  2945. if (mergeCache !== null) {
  2946. mergeCache.set(a, b, a_);
  2947. }
  2948. return a_;
  2949. }
  2950. mergedParents = mergedParents.slice(0, k);
  2951. mergedReturnStates = mergedReturnStates.slice(0, k);
  2952. }
  2953. var M = new ArrayPredictionContext(mergedParents, mergedReturnStates);
  2954. // if we created same array as a or b, return that instead
  2955. // TODO: track whether this is possible above during merge sort for speed
  2956. if (M === a) {
  2957. if (mergeCache !== null) {
  2958. mergeCache.set(a, b, a);
  2959. }
  2960. return a;
  2961. }
  2962. if (M === b) {
  2963. if (mergeCache !== null) {
  2964. mergeCache.set(a, b, b);
  2965. }
  2966. return b;
  2967. }
  2968. combineCommonParents(mergedParents);
  2969. if (mergeCache !== null) {
  2970. mergeCache.set(a, b, M);
  2971. }
  2972. return M;
  2973. }
  2974. //
  2975. // Make pass over all <em>M</em> {@code parents}; merge any {@code equals()}
  2976. // ones.
  2977. // /
  2978. function combineCommonParents(parents) {
  2979. var uniqueParents = {};
  2980. for (var p = 0; p < parents.length; p++) {
  2981. var parent = parents[p];
  2982. if (!(parent in uniqueParents)) {
  2983. uniqueParents[parent] = parent;
  2984. }
  2985. }
  2986. for (var q = 0; q < parents.length; q++) {
  2987. parents[q] = uniqueParents[parents[q]];
  2988. }
  2989. }
  2990. function getCachedPredictionContext(context, contextCache, visited) {
  2991. if (context.isEmpty()) {
  2992. return context;
  2993. }
  2994. var existing = visited[context] || null;
  2995. if (existing !== null) {
  2996. return existing;
  2997. }
  2998. existing = contextCache.get(context);
  2999. if (existing !== null) {
  3000. visited[context] = existing;
  3001. return existing;
  3002. }
  3003. var changed = false;
  3004. var parents = [];
  3005. for (var i = 0; i < parents.length; i++) {
  3006. var parent = getCachedPredictionContext(context.getParent(i), contextCache, visited);
  3007. if (changed || parent !== context.getParent(i)) {
  3008. if (!changed) {
  3009. parents = [];
  3010. for (var j = 0; j < context.length; j++) {
  3011. parents[j] = context.getParent(j);
  3012. }
  3013. changed = true;
  3014. }
  3015. parents[i] = parent;
  3016. }
  3017. }
  3018. if (!changed) {
  3019. contextCache.add(context);
  3020. visited[context] = context;
  3021. return context;
  3022. }
  3023. var updated = null;
  3024. if (parents.length === 0) {
  3025. updated = PredictionContext.EMPTY;
  3026. } else if (parents.length === 1) {
  3027. updated = SingletonPredictionContext.create(parents[0], context
  3028. .getReturnState(0));
  3029. } else {
  3030. updated = new ArrayPredictionContext(parents, context.returnStates);
  3031. }
  3032. contextCache.add(updated);
  3033. visited[updated] = updated;
  3034. visited[context] = updated;
  3035. return updated;
  3036. }
  3037. // ter's recursive version of Sam's getAllNodes()
  3038. function getAllContextNodes(context, nodes, visited) {
  3039. if (nodes === null) {
  3040. nodes = [];
  3041. return getAllContextNodes(context, nodes, visited);
  3042. } else if (visited === null) {
  3043. visited = {};
  3044. return getAllContextNodes(context, nodes, visited);
  3045. } else {
  3046. if (context === null || visited[context] !== null) {
  3047. return nodes;
  3048. }
  3049. visited[context] = context;
  3050. nodes.push(context);
  3051. for (var i = 0; i < context.length; i++) {
  3052. getAllContextNodes(context.getParent(i), nodes, visited);
  3053. }
  3054. return nodes;
  3055. }
  3056. }
  3057. exports.merge = merge;
  3058. exports.PredictionContext = PredictionContext;
  3059. exports.PredictionContextCache = PredictionContextCache;
  3060. exports.SingletonPredictionContext = SingletonPredictionContext;
  3061. exports.predictionContextFromRuleContext = predictionContextFromRuleContext;
  3062. exports.getCachedPredictionContext = getCachedPredictionContext;
  3063. /***/ }),
  3064. /***/ "./node_modules/antlr4/Recognizer.js":
  3065. /*!*******************************************!*\
  3066. !*** ./node_modules/antlr4/Recognizer.js ***!
  3067. \*******************************************/
  3068. /*! no static exports found */
  3069. /***/ (function(module, exports, __webpack_require__) {
  3070. //
  3071. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3072. * Use of this file is governed by the BSD 3-clause license that
  3073. * can be found in the LICENSE.txt file in the project root.
  3074. */
  3075. //
  3076. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  3077. var ConsoleErrorListener = __webpack_require__(/*! ./error/ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ConsoleErrorListener;
  3078. var ProxyErrorListener = __webpack_require__(/*! ./error/ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ProxyErrorListener;
  3079. function Recognizer() {
  3080. this._listeners = [ ConsoleErrorListener.INSTANCE ];
  3081. this._interp = null;
  3082. this._stateNumber = -1;
  3083. return this;
  3084. }
  3085. Recognizer.tokenTypeMapCache = {};
  3086. Recognizer.ruleIndexMapCache = {};
  3087. Recognizer.prototype.checkVersion = function(toolVersion) {
  3088. var runtimeVersion = "4.7.2";
  3089. if (runtimeVersion!==toolVersion) {
  3090. console.log("ANTLR runtime and generated code versions disagree: "+runtimeVersion+"!="+toolVersion);
  3091. }
  3092. };
  3093. Recognizer.prototype.addErrorListener = function(listener) {
  3094. this._listeners.push(listener);
  3095. };
  3096. Recognizer.prototype.removeErrorListeners = function() {
  3097. this._listeners = [];
  3098. };
  3099. Recognizer.prototype.getTokenTypeMap = function() {
  3100. var tokenNames = this.getTokenNames();
  3101. if (tokenNames===null) {
  3102. throw("The current recognizer does not provide a list of token names.");
  3103. }
  3104. var result = this.tokenTypeMapCache[tokenNames];
  3105. if(result===undefined) {
  3106. result = tokenNames.reduce(function(o, k, i) { o[k] = i; });
  3107. result.EOF = Token.EOF;
  3108. this.tokenTypeMapCache[tokenNames] = result;
  3109. }
  3110. return result;
  3111. };
  3112. // Get a map from rule names to rule indexes.
  3113. //
  3114. // <p>Used for XPath and tree pattern compilation.</p>
  3115. //
  3116. Recognizer.prototype.getRuleIndexMap = function() {
  3117. var ruleNames = this.ruleNames;
  3118. if (ruleNames===null) {
  3119. throw("The current recognizer does not provide a list of rule names.");
  3120. }
  3121. var result = this.ruleIndexMapCache[ruleNames];
  3122. if(result===undefined) {
  3123. result = ruleNames.reduce(function(o, k, i) { o[k] = i; });
  3124. this.ruleIndexMapCache[ruleNames] = result;
  3125. }
  3126. return result;
  3127. };
  3128. Recognizer.prototype.getTokenType = function(tokenName) {
  3129. var ttype = this.getTokenTypeMap()[tokenName];
  3130. if (ttype !==undefined) {
  3131. return ttype;
  3132. } else {
  3133. return Token.INVALID_TYPE;
  3134. }
  3135. };
  3136. // What is the error header, normally line/character position information?//
  3137. Recognizer.prototype.getErrorHeader = function(e) {
  3138. var line = e.getOffendingToken().line;
  3139. var column = e.getOffendingToken().column;
  3140. return "line " + line + ":" + column;
  3141. };
  3142. // How should a token be displayed in an error message? The default
  3143. // is to display just the text, but during development you might
  3144. // want to have a lot of information spit out. Override in that case
  3145. // to use t.toString() (which, for CommonToken, dumps everything about
  3146. // the token). This is better than forcing you to override a method in
  3147. // your token objects because you don't have to go modify your lexer
  3148. // so that it creates a new Java type.
  3149. //
  3150. // @deprecated This method is not called by the ANTLR 4 Runtime. Specific
  3151. // implementations of {@link ANTLRErrorStrategy} may provide a similar
  3152. // feature when necessary. For example, see
  3153. // {@link DefaultErrorStrategy//getTokenErrorDisplay}.
  3154. //
  3155. Recognizer.prototype.getTokenErrorDisplay = function(t) {
  3156. if (t===null) {
  3157. return "<no token>";
  3158. }
  3159. var s = t.text;
  3160. if (s===null) {
  3161. if (t.type===Token.EOF) {
  3162. s = "<EOF>";
  3163. } else {
  3164. s = "<" + t.type + ">";
  3165. }
  3166. }
  3167. s = s.replace("\n","\\n").replace("\r","\\r").replace("\t","\\t");
  3168. return "'" + s + "'";
  3169. };
  3170. Recognizer.prototype.getErrorListenerDispatch = function() {
  3171. return new ProxyErrorListener(this._listeners);
  3172. };
  3173. // subclass needs to override these if there are sempreds or actions
  3174. // that the ATN interp needs to execute
  3175. Recognizer.prototype.sempred = function(localctx, ruleIndex, actionIndex) {
  3176. return true;
  3177. };
  3178. Recognizer.prototype.precpred = function(localctx , precedence) {
  3179. return true;
  3180. };
  3181. //Indicate that the recognizer has changed internal state that is
  3182. //consistent with the ATN state passed in. This way we always know
  3183. //where we are in the ATN as the parser goes along. The rule
  3184. //context objects form a stack that lets us see the stack of
  3185. //invoking rules. Combine this and we have complete ATN
  3186. //configuration information.
  3187. Object.defineProperty(Recognizer.prototype, "state", {
  3188. get : function() {
  3189. return this._stateNumber;
  3190. },
  3191. set : function(state) {
  3192. this._stateNumber = state;
  3193. }
  3194. });
  3195. exports.Recognizer = Recognizer;
  3196. /***/ }),
  3197. /***/ "./node_modules/antlr4/RuleContext.js":
  3198. /*!********************************************!*\
  3199. !*** ./node_modules/antlr4/RuleContext.js ***!
  3200. \********************************************/
  3201. /*! no static exports found */
  3202. /***/ (function(module, exports, __webpack_require__) {
  3203. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3204. * Use of this file is governed by the BSD 3-clause license that
  3205. * can be found in the LICENSE.txt file in the project root.
  3206. */
  3207. ///
  3208. // A rule context is a record of a single rule invocation. It knows
  3209. // which context invoked it, if any. If there is no parent context, then
  3210. // naturally the invoking state is not valid. The parent link
  3211. // provides a chain upwards from the current rule invocation to the root
  3212. // of the invocation tree, forming a stack. We actually carry no
  3213. // information about the rule associated with this context (except
  3214. // when parsing). We keep only the state number of the invoking state from
  3215. // the ATN submachine that invoked this. Contrast this with the s
  3216. // pointer inside ParserRuleContext that tracks the current state
  3217. // being "executed" for the current rule.
  3218. //
  3219. // The parent contexts are useful for computing lookahead sets and
  3220. // getting error information.
  3221. //
  3222. // These objects are used during parsing and prediction.
  3223. // For the special case of parsers, we use the subclass
  3224. // ParserRuleContext.
  3225. //
  3226. // @see ParserRuleContext
  3227. ///
  3228. var RuleNode = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").RuleNode;
  3229. var INVALID_INTERVAL = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").INVALID_INTERVAL;
  3230. var INVALID_ALT_NUMBER = __webpack_require__(/*! ./atn/ATN */ "./node_modules/antlr4/atn/ATN.js").INVALID_ALT_NUMBER;
  3231. function RuleContext(parent, invokingState) {
  3232. RuleNode.call(this);
  3233. // What context invoked this rule?
  3234. this.parentCtx = parent || null;
  3235. // What state invoked the rule associated with this context?
  3236. // The "return address" is the followState of invokingState
  3237. // If parent is null, this should be -1.
  3238. this.invokingState = invokingState || -1;
  3239. return this;
  3240. }
  3241. RuleContext.prototype = Object.create(RuleNode.prototype);
  3242. RuleContext.prototype.constructor = RuleContext;
  3243. RuleContext.prototype.depth = function() {
  3244. var n = 0;
  3245. var p = this;
  3246. while (p !== null) {
  3247. p = p.parentCtx;
  3248. n += 1;
  3249. }
  3250. return n;
  3251. };
  3252. // A context is empty if there is no invoking state; meaning nobody call
  3253. // current context.
  3254. RuleContext.prototype.isEmpty = function() {
  3255. return this.invokingState === -1;
  3256. };
  3257. // satisfy the ParseTree / SyntaxTree interface
  3258. RuleContext.prototype.getSourceInterval = function() {
  3259. return INVALID_INTERVAL;
  3260. };
  3261. RuleContext.prototype.getRuleContext = function() {
  3262. return this;
  3263. };
  3264. RuleContext.prototype.getPayload = function() {
  3265. return this;
  3266. };
  3267. // Return the combined text of all child nodes. This method only considers
  3268. // tokens which have been added to the parse tree.
  3269. // <p>
  3270. // Since tokens on hidden channels (e.g. whitespace or comments) are not
  3271. // added to the parse trees, they will not appear in the output of this
  3272. // method.
  3273. // /
  3274. RuleContext.prototype.getText = function() {
  3275. if (this.getChildCount() === 0) {
  3276. return "";
  3277. } else {
  3278. return this.children.map(function(child) {
  3279. return child.getText();
  3280. }).join("");
  3281. }
  3282. };
  3283. // For rule associated with this parse tree internal node, return
  3284. // the outer alternative number used to match the input. Default
  3285. // implementation does not compute nor store this alt num. Create
  3286. // a subclass of ParserRuleContext with backing field and set
  3287. // option contextSuperClass.
  3288. // to set it.
  3289. RuleContext.prototype.getAltNumber = function() { return INVALID_ALT_NUMBER; }
  3290. // Set the outer alternative number for this context node. Default
  3291. // implementation does nothing to avoid backing field overhead for
  3292. // trees that don't need it. Create
  3293. // a subclass of ParserRuleContext with backing field and set
  3294. // option contextSuperClass.
  3295. RuleContext.prototype.setAltNumber = function(altNumber) { }
  3296. RuleContext.prototype.getChild = function(i) {
  3297. return null;
  3298. };
  3299. RuleContext.prototype.getChildCount = function() {
  3300. return 0;
  3301. };
  3302. RuleContext.prototype.accept = function(visitor) {
  3303. return visitor.visitChildren(this);
  3304. };
  3305. //need to manage circular dependencies, so export now
  3306. exports.RuleContext = RuleContext;
  3307. var Trees = __webpack_require__(/*! ./tree/Trees */ "./node_modules/antlr4/tree/Trees.js").Trees;
  3308. // Print out a whole tree, not just a node, in LISP format
  3309. // (root child1 .. childN). Print just a node if this is a leaf.
  3310. //
  3311. RuleContext.prototype.toStringTree = function(ruleNames, recog) {
  3312. return Trees.toStringTree(this, ruleNames, recog);
  3313. };
  3314. RuleContext.prototype.toString = function(ruleNames, stop) {
  3315. ruleNames = ruleNames || null;
  3316. stop = stop || null;
  3317. var p = this;
  3318. var s = "[";
  3319. while (p !== null && p !== stop) {
  3320. if (ruleNames === null) {
  3321. if (!p.isEmpty()) {
  3322. s += p.invokingState;
  3323. }
  3324. } else {
  3325. var ri = p.ruleIndex;
  3326. var ruleName = (ri >= 0 && ri < ruleNames.length) ? ruleNames[ri]
  3327. : "" + ri;
  3328. s += ruleName;
  3329. }
  3330. if (p.parentCtx !== null && (ruleNames !== null || !p.parentCtx.isEmpty())) {
  3331. s += " ";
  3332. }
  3333. p = p.parentCtx;
  3334. }
  3335. s += "]";
  3336. return s;
  3337. };
  3338. /***/ }),
  3339. /***/ "./node_modules/antlr4/Token.js":
  3340. /*!**************************************!*\
  3341. !*** ./node_modules/antlr4/Token.js ***!
  3342. \**************************************/
  3343. /*! no static exports found */
  3344. /***/ (function(module, exports) {
  3345. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3346. * Use of this file is governed by the BSD 3-clause license that
  3347. * can be found in the LICENSE.txt file in the project root.
  3348. */
  3349. //
  3350. // A token has properties: text, type, line, character position in the line
  3351. // (so we can ignore tabs), token channel, index, and source from which
  3352. // we obtained this token.
  3353. function Token() {
  3354. this.source = null;
  3355. this.type = null; // token type of the token
  3356. this.channel = null; // The parser ignores everything not on DEFAULT_CHANNEL
  3357. this.start = null; // optional; return -1 if not implemented.
  3358. this.stop = null; // optional; return -1 if not implemented.
  3359. this.tokenIndex = null; // from 0..n-1 of the token object in the input stream
  3360. this.line = null; // line=1..n of the 1st character
  3361. this.column = null; // beginning of the line at which it occurs, 0..n-1
  3362. this._text = null; // text of the token.
  3363. return this;
  3364. }
  3365. Token.INVALID_TYPE = 0;
  3366. // During lookahead operations, this "token" signifies we hit rule end ATN state
  3367. // and did not follow it despite needing to.
  3368. Token.EPSILON = -2;
  3369. Token.MIN_USER_TOKEN_TYPE = 1;
  3370. Token.EOF = -1;
  3371. // All tokens go to the parser (unless skip() is called in that rule)
  3372. // on a particular "channel". The parser tunes to a particular channel
  3373. // so that whitespace etc... can go to the parser on a "hidden" channel.
  3374. Token.DEFAULT_CHANNEL = 0;
  3375. // Anything on different channel than DEFAULT_CHANNEL is not parsed
  3376. // by parser.
  3377. Token.HIDDEN_CHANNEL = 1;
  3378. // Explicitly set the text for this token. If {code text} is not
  3379. // {@code null}, then {@link //getText} will return this value rather than
  3380. // extracting the text from the input.
  3381. //
  3382. // @param text The explicit text of the token, or {@code null} if the text
  3383. // should be obtained from the input along with the start and stop indexes
  3384. // of the token.
  3385. Object.defineProperty(Token.prototype, "text", {
  3386. get : function() {
  3387. return this._text;
  3388. },
  3389. set : function(text) {
  3390. this._text = text;
  3391. }
  3392. });
  3393. Token.prototype.getTokenSource = function() {
  3394. return this.source[0];
  3395. };
  3396. Token.prototype.getInputStream = function() {
  3397. return this.source[1];
  3398. };
  3399. function CommonToken(source, type, channel, start, stop) {
  3400. Token.call(this);
  3401. this.source = source !== undefined ? source : CommonToken.EMPTY_SOURCE;
  3402. this.type = type !== undefined ? type : null;
  3403. this.channel = channel !== undefined ? channel : Token.DEFAULT_CHANNEL;
  3404. this.start = start !== undefined ? start : -1;
  3405. this.stop = stop !== undefined ? stop : -1;
  3406. this.tokenIndex = -1;
  3407. if (this.source[0] !== null) {
  3408. this.line = source[0].line;
  3409. this.column = source[0].column;
  3410. } else {
  3411. this.column = -1;
  3412. }
  3413. return this;
  3414. }
  3415. CommonToken.prototype = Object.create(Token.prototype);
  3416. CommonToken.prototype.constructor = CommonToken;
  3417. // An empty {@link Pair} which is used as the default value of
  3418. // {@link //source} for tokens that do not have a source.
  3419. CommonToken.EMPTY_SOURCE = [ null, null ];
  3420. // Constructs a new {@link CommonToken} as a copy of another {@link Token}.
  3421. //
  3422. // <p>
  3423. // If {@code oldToken} is also a {@link CommonToken} instance, the newly
  3424. // constructed token will share a reference to the {@link //text} field and
  3425. // the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will
  3426. // be assigned the result of calling {@link //getText}, and {@link //source}
  3427. // will be constructed from the result of {@link Token//getTokenSource} and
  3428. // {@link Token//getInputStream}.</p>
  3429. //
  3430. // @param oldToken The token to copy.
  3431. //
  3432. CommonToken.prototype.clone = function() {
  3433. var t = new CommonToken(this.source, this.type, this.channel, this.start,
  3434. this.stop);
  3435. t.tokenIndex = this.tokenIndex;
  3436. t.line = this.line;
  3437. t.column = this.column;
  3438. t.text = this.text;
  3439. return t;
  3440. };
  3441. Object.defineProperty(CommonToken.prototype, "text", {
  3442. get : function() {
  3443. if (this._text !== null) {
  3444. return this._text;
  3445. }
  3446. var input = this.getInputStream();
  3447. if (input === null) {
  3448. return null;
  3449. }
  3450. var n = input.size;
  3451. if (this.start < n && this.stop < n) {
  3452. return input.getText(this.start, this.stop);
  3453. } else {
  3454. return "<EOF>";
  3455. }
  3456. },
  3457. set : function(text) {
  3458. this._text = text;
  3459. }
  3460. });
  3461. CommonToken.prototype.toString = function() {
  3462. var txt = this.text;
  3463. if (txt !== null) {
  3464. txt = txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
  3465. } else {
  3466. txt = "<no text>";
  3467. }
  3468. return "[@" + this.tokenIndex + "," + this.start + ":" + this.stop + "='" +
  3469. txt + "',<" + this.type + ">" +
  3470. (this.channel > 0 ? ",channel=" + this.channel : "") + "," +
  3471. this.line + ":" + this.column + "]";
  3472. };
  3473. exports.Token = Token;
  3474. exports.CommonToken = CommonToken;
  3475. /***/ }),
  3476. /***/ "./node_modules/antlr4/Utils.js":
  3477. /*!**************************************!*\
  3478. !*** ./node_modules/antlr4/Utils.js ***!
  3479. \**************************************/
  3480. /*! no static exports found */
  3481. /***/ (function(module, exports) {
  3482. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3483. * Use of this file is governed by the BSD 3-clause license that
  3484. * can be found in the LICENSE.txt file in the project root.
  3485. */
  3486. function arrayToString(a) {
  3487. return "[" + a.join(", ") + "]";
  3488. }
  3489. String.prototype.seed = String.prototype.seed || Math.round(Math.random() * Math.pow(2, 32));
  3490. String.prototype.hashCode = function () {
  3491. var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i,
  3492. key = this.toString();
  3493. remainder = key.length & 3; // key.length % 4
  3494. bytes = key.length - remainder;
  3495. h1 = String.prototype.seed;
  3496. c1 = 0xcc9e2d51;
  3497. c2 = 0x1b873593;
  3498. i = 0;
  3499. while (i < bytes) {
  3500. k1 =
  3501. ((key.charCodeAt(i) & 0xff)) |
  3502. ((key.charCodeAt(++i) & 0xff) << 8) |
  3503. ((key.charCodeAt(++i) & 0xff) << 16) |
  3504. ((key.charCodeAt(++i) & 0xff) << 24);
  3505. ++i;
  3506. k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
  3507. k1 = (k1 << 15) | (k1 >>> 17);
  3508. k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
  3509. h1 ^= k1;
  3510. h1 = (h1 << 13) | (h1 >>> 19);
  3511. h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
  3512. h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
  3513. }
  3514. k1 = 0;
  3515. switch (remainder) {
  3516. case 3:
  3517. k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
  3518. case 2:
  3519. k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
  3520. case 1:
  3521. k1 ^= (key.charCodeAt(i) & 0xff);
  3522. k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
  3523. k1 = (k1 << 15) | (k1 >>> 17);
  3524. k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
  3525. h1 ^= k1;
  3526. }
  3527. h1 ^= key.length;
  3528. h1 ^= h1 >>> 16;
  3529. h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
  3530. h1 ^= h1 >>> 13;
  3531. h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
  3532. h1 ^= h1 >>> 16;
  3533. return h1 >>> 0;
  3534. };
  3535. function standardEqualsFunction(a, b) {
  3536. return a.equals(b);
  3537. }
  3538. function standardHashCodeFunction(a) {
  3539. return a.hashCode();
  3540. }
  3541. function Set(hashFunction, equalsFunction) {
  3542. this.data = {};
  3543. this.hashFunction = hashFunction || standardHashCodeFunction;
  3544. this.equalsFunction = equalsFunction || standardEqualsFunction;
  3545. return this;
  3546. }
  3547. Object.defineProperty(Set.prototype, "length", {
  3548. get: function () {
  3549. var l = 0;
  3550. for (var key in this.data) {
  3551. if (key.indexOf("hash_") === 0) {
  3552. l = l + this.data[key].length;
  3553. }
  3554. }
  3555. return l;
  3556. }
  3557. });
  3558. Set.prototype.add = function (value) {
  3559. var hash = this.hashFunction(value);
  3560. var key = "hash_" + hash;
  3561. if (key in this.data) {
  3562. var values = this.data[key];
  3563. for (var i = 0; i < values.length; i++) {
  3564. if (this.equalsFunction(value, values[i])) {
  3565. return values[i];
  3566. }
  3567. }
  3568. values.push(value);
  3569. return value;
  3570. } else {
  3571. this.data[key] = [value];
  3572. return value;
  3573. }
  3574. };
  3575. Set.prototype.contains = function (value) {
  3576. return this.get(value) != null;
  3577. };
  3578. Set.prototype.get = function (value) {
  3579. var hash = this.hashFunction(value);
  3580. var key = "hash_" + hash;
  3581. if (key in this.data) {
  3582. var values = this.data[key];
  3583. for (var i = 0; i < values.length; i++) {
  3584. if (this.equalsFunction(value, values[i])) {
  3585. return values[i];
  3586. }
  3587. }
  3588. }
  3589. return null;
  3590. };
  3591. Set.prototype.values = function () {
  3592. var l = [];
  3593. for (var key in this.data) {
  3594. if (key.indexOf("hash_") === 0) {
  3595. l = l.concat(this.data[key]);
  3596. }
  3597. }
  3598. return l;
  3599. };
  3600. Set.prototype.toString = function () {
  3601. return arrayToString(this.values());
  3602. };
  3603. function BitSet() {
  3604. this.data = [];
  3605. return this;
  3606. }
  3607. BitSet.prototype.add = function (value) {
  3608. this.data[value] = true;
  3609. };
  3610. BitSet.prototype.or = function (set) {
  3611. var bits = this;
  3612. Object.keys(set.data).map(function (alt) {
  3613. bits.add(alt);
  3614. });
  3615. };
  3616. BitSet.prototype.remove = function (value) {
  3617. delete this.data[value];
  3618. };
  3619. BitSet.prototype.contains = function (value) {
  3620. return this.data[value] === true;
  3621. };
  3622. BitSet.prototype.values = function () {
  3623. return Object.keys(this.data);
  3624. };
  3625. BitSet.prototype.minValue = function () {
  3626. return Math.min.apply(null, this.values());
  3627. };
  3628. BitSet.prototype.hashCode = function () {
  3629. var hash = new Hash();
  3630. hash.update(this.values());
  3631. return hash.finish();
  3632. };
  3633. BitSet.prototype.equals = function (other) {
  3634. if (!(other instanceof BitSet)) {
  3635. return false;
  3636. }
  3637. return this.hashCode() === other.hashCode();
  3638. };
  3639. Object.defineProperty(BitSet.prototype, "length", {
  3640. get: function () {
  3641. return this.values().length;
  3642. }
  3643. });
  3644. BitSet.prototype.toString = function () {
  3645. return "{" + this.values().join(", ") + "}";
  3646. };
  3647. function Map(hashFunction, equalsFunction) {
  3648. this.data = {};
  3649. this.hashFunction = hashFunction || standardHashCodeFunction;
  3650. this.equalsFunction = equalsFunction || standardEqualsFunction;
  3651. return this;
  3652. }
  3653. Object.defineProperty(Map.prototype, "length", {
  3654. get: function () {
  3655. var l = 0;
  3656. for (var hashKey in this.data) {
  3657. if (hashKey.indexOf("hash_") === 0) {
  3658. l = l + this.data[hashKey].length;
  3659. }
  3660. }
  3661. return l;
  3662. }
  3663. });
  3664. Map.prototype.put = function (key, value) {
  3665. var hashKey = "hash_" + this.hashFunction(key);
  3666. if (hashKey in this.data) {
  3667. var entries = this.data[hashKey];
  3668. for (var i = 0; i < entries.length; i++) {
  3669. var entry = entries[i];
  3670. if (this.equalsFunction(key, entry.key)) {
  3671. var oldValue = entry.value;
  3672. entry.value = value;
  3673. return oldValue;
  3674. }
  3675. }
  3676. entries.push({key:key, value:value});
  3677. return value;
  3678. } else {
  3679. this.data[hashKey] = [{key:key, value:value}];
  3680. return value;
  3681. }
  3682. };
  3683. Map.prototype.containsKey = function (key) {
  3684. var hashKey = "hash_" + this.hashFunction(key);
  3685. if(hashKey in this.data) {
  3686. var entries = this.data[hashKey];
  3687. for (var i = 0; i < entries.length; i++) {
  3688. var entry = entries[i];
  3689. if (this.equalsFunction(key, entry.key))
  3690. return true;
  3691. }
  3692. }
  3693. return false;
  3694. };
  3695. Map.prototype.get = function (key) {
  3696. var hashKey = "hash_" + this.hashFunction(key);
  3697. if(hashKey in this.data) {
  3698. var entries = this.data[hashKey];
  3699. for (var i = 0; i < entries.length; i++) {
  3700. var entry = entries[i];
  3701. if (this.equalsFunction(key, entry.key))
  3702. return entry.value;
  3703. }
  3704. }
  3705. return null;
  3706. };
  3707. Map.prototype.entries = function () {
  3708. var l = [];
  3709. for (var key in this.data) {
  3710. if (key.indexOf("hash_") === 0) {
  3711. l = l.concat(this.data[key]);
  3712. }
  3713. }
  3714. return l;
  3715. };
  3716. Map.prototype.getKeys = function () {
  3717. return this.entries().map(function(e) {
  3718. return e.key;
  3719. });
  3720. };
  3721. Map.prototype.getValues = function () {
  3722. return this.entries().map(function(e) {
  3723. return e.value;
  3724. });
  3725. };
  3726. Map.prototype.toString = function () {
  3727. var ss = this.entries().map(function(entry) {
  3728. return '{' + entry.key + ':' + entry.value + '}';
  3729. });
  3730. return '[' + ss.join(", ") + ']';
  3731. };
  3732. function AltDict() {
  3733. this.data = {};
  3734. return this;
  3735. }
  3736. AltDict.prototype.get = function (key) {
  3737. key = "k-" + key;
  3738. if (key in this.data) {
  3739. return this.data[key];
  3740. } else {
  3741. return null;
  3742. }
  3743. };
  3744. AltDict.prototype.put = function (key, value) {
  3745. key = "k-" + key;
  3746. this.data[key] = value;
  3747. };
  3748. AltDict.prototype.values = function () {
  3749. var data = this.data;
  3750. var keys = Object.keys(this.data);
  3751. return keys.map(function (key) {
  3752. return data[key];
  3753. });
  3754. };
  3755. function DoubleDict() {
  3756. return this;
  3757. }
  3758. function Hash() {
  3759. this.count = 0;
  3760. this.hash = 0;
  3761. return this;
  3762. }
  3763. Hash.prototype.update = function () {
  3764. for(var i=0;i<arguments.length;i++) {
  3765. var value = arguments[i];
  3766. if (value == null)
  3767. continue;
  3768. if(Array.isArray(value))
  3769. this.update.apply(value);
  3770. else {
  3771. var k = 0;
  3772. switch (typeof(value)) {
  3773. case 'undefined':
  3774. case 'function':
  3775. continue;
  3776. case 'number':
  3777. case 'boolean':
  3778. k = value;
  3779. break;
  3780. case 'string':
  3781. k = value.hashCode();
  3782. break;
  3783. default:
  3784. value.updateHashCode(this);
  3785. continue;
  3786. }
  3787. k = k * 0xCC9E2D51;
  3788. k = (k << 15) | (k >>> (32 - 15));
  3789. k = k * 0x1B873593;
  3790. this.count = this.count + 1;
  3791. var hash = this.hash ^ k;
  3792. hash = (hash << 13) | (hash >>> (32 - 13));
  3793. hash = hash * 5 + 0xE6546B64;
  3794. this.hash = hash;
  3795. }
  3796. }
  3797. }
  3798. Hash.prototype.finish = function () {
  3799. var hash = this.hash ^ (this.count * 4);
  3800. hash = hash ^ (hash >>> 16);
  3801. hash = hash * 0x85EBCA6B;
  3802. hash = hash ^ (hash >>> 13);
  3803. hash = hash * 0xC2B2AE35;
  3804. hash = hash ^ (hash >>> 16);
  3805. return hash;
  3806. }
  3807. function hashStuff() {
  3808. var hash = new Hash();
  3809. hash.update.apply(arguments);
  3810. return hash.finish();
  3811. }
  3812. DoubleDict.prototype.get = function (a, b) {
  3813. var d = this[a] || null;
  3814. return d === null ? null : (d[b] || null);
  3815. };
  3816. DoubleDict.prototype.set = function (a, b, o) {
  3817. var d = this[a] || null;
  3818. if (d === null) {
  3819. d = {};
  3820. this[a] = d;
  3821. }
  3822. d[b] = o;
  3823. };
  3824. function escapeWhitespace(s, escapeSpaces) {
  3825. s = s.replace(/\t/g, "\\t")
  3826. .replace(/\n/g, "\\n")
  3827. .replace(/\r/g, "\\r");
  3828. if (escapeSpaces) {
  3829. s = s.replace(/ /g, "\u00B7");
  3830. }
  3831. return s;
  3832. }
  3833. function titleCase(str) {
  3834. return str.replace(/\w\S*/g, function (txt) {
  3835. return txt.charAt(0).toUpperCase() + txt.substr(1);
  3836. });
  3837. };
  3838. function equalArrays(a, b)
  3839. {
  3840. if (!Array.isArray(a) || !Array.isArray(b))
  3841. return false;
  3842. if (a == b)
  3843. return true;
  3844. if (a.length != b.length)
  3845. return false;
  3846. for (var i = 0; i < a.length; i++) {
  3847. if (a[i] == b[i])
  3848. continue;
  3849. if (!a[i].equals(b[i]))
  3850. return false;
  3851. }
  3852. return true;
  3853. };
  3854. exports.Hash = Hash;
  3855. exports.Set = Set;
  3856. exports.Map = Map;
  3857. exports.BitSet = BitSet;
  3858. exports.AltDict = AltDict;
  3859. exports.DoubleDict = DoubleDict;
  3860. exports.hashStuff = hashStuff;
  3861. exports.escapeWhitespace = escapeWhitespace;
  3862. exports.arrayToString = arrayToString;
  3863. exports.titleCase = titleCase;
  3864. exports.equalArrays = equalArrays;
  3865. /***/ }),
  3866. /***/ "./node_modules/antlr4/atn/ATN.js":
  3867. /*!****************************************!*\
  3868. !*** ./node_modules/antlr4/atn/ATN.js ***!
  3869. \****************************************/
  3870. /*! no static exports found */
  3871. /***/ (function(module, exports, __webpack_require__) {
  3872. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3873. * Use of this file is governed by the BSD 3-clause license that
  3874. * can be found in the LICENSE.txt file in the project root.
  3875. */
  3876. var LL1Analyzer = __webpack_require__(/*! ./../LL1Analyzer */ "./node_modules/antlr4/LL1Analyzer.js").LL1Analyzer;
  3877. var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  3878. function ATN(grammarType , maxTokenType) {
  3879. // Used for runtime deserialization of ATNs from strings///
  3880. // The type of the ATN.
  3881. this.grammarType = grammarType;
  3882. // The maximum value for any symbol recognized by a transition in the ATN.
  3883. this.maxTokenType = maxTokenType;
  3884. this.states = [];
  3885. // Each subrule/rule is a decision point and we must track them so we
  3886. // can go back later and build DFA predictors for them. This includes
  3887. // all the rules, subrules, optional blocks, ()+, ()* etc...
  3888. this.decisionToState = [];
  3889. // Maps from rule index to starting state number.
  3890. this.ruleToStartState = [];
  3891. // Maps from rule index to stop state number.
  3892. this.ruleToStopState = null;
  3893. this.modeNameToStartState = {};
  3894. // For lexer ATNs, this maps the rule index to the resulting token type.
  3895. // For parser ATNs, this maps the rule index to the generated bypass token
  3896. // type if the
  3897. // {@link ATNDeserializationOptions//isGenerateRuleBypassTransitions}
  3898. // deserialization option was specified; otherwise, this is {@code null}.
  3899. this.ruleToTokenType = null;
  3900. // For lexer ATNs, this is an array of {@link LexerAction} objects which may
  3901. // be referenced by action transitions in the ATN.
  3902. this.lexerActions = null;
  3903. this.modeToStartState = [];
  3904. return this;
  3905. }
  3906. // Compute the set of valid tokens that can occur starting in state {@code s}.
  3907. // If {@code ctx} is null, the set of tokens will not include what can follow
  3908. // the rule surrounding {@code s}. In other words, the set will be
  3909. // restricted to tokens reachable staying within {@code s}'s rule.
  3910. ATN.prototype.nextTokensInContext = function(s, ctx) {
  3911. var anal = new LL1Analyzer(this);
  3912. return anal.LOOK(s, null, ctx);
  3913. };
  3914. // Compute the set of valid tokens that can occur starting in {@code s} and
  3915. // staying in same rule. {@link Token//EPSILON} is in set if we reach end of
  3916. // rule.
  3917. ATN.prototype.nextTokensNoContext = function(s) {
  3918. if (s.nextTokenWithinRule !== null ) {
  3919. return s.nextTokenWithinRule;
  3920. }
  3921. s.nextTokenWithinRule = this.nextTokensInContext(s, null);
  3922. s.nextTokenWithinRule.readOnly = true;
  3923. return s.nextTokenWithinRule;
  3924. };
  3925. ATN.prototype.nextTokens = function(s, ctx) {
  3926. if ( ctx===undefined ) {
  3927. return this.nextTokensNoContext(s);
  3928. } else {
  3929. return this.nextTokensInContext(s, ctx);
  3930. }
  3931. };
  3932. ATN.prototype.addState = function( state) {
  3933. if ( state !== null ) {
  3934. state.atn = this;
  3935. state.stateNumber = this.states.length;
  3936. }
  3937. this.states.push(state);
  3938. };
  3939. ATN.prototype.removeState = function( state) {
  3940. this.states[state.stateNumber] = null; // just free mem, don't shift states in list
  3941. };
  3942. ATN.prototype.defineDecisionState = function( s) {
  3943. this.decisionToState.push(s);
  3944. s.decision = this.decisionToState.length-1;
  3945. return s.decision;
  3946. };
  3947. ATN.prototype.getDecisionState = function( decision) {
  3948. if (this.decisionToState.length===0) {
  3949. return null;
  3950. } else {
  3951. return this.decisionToState[decision];
  3952. }
  3953. };
  3954. // Computes the set of input symbols which could follow ATN state number
  3955. // {@code stateNumber} in the specified full {@code context}. This method
  3956. // considers the complete parser context, but does not evaluate semantic
  3957. // predicates (i.e. all predicates encountered during the calculation are
  3958. // assumed true). If a path in the ATN exists from the starting state to the
  3959. // {@link RuleStopState} of the outermost context without matching any
  3960. // symbols, {@link Token//EOF} is added to the returned set.
  3961. //
  3962. // <p>If {@code context} is {@code null}, it is treated as
  3963. // {@link ParserRuleContext//EMPTY}.</p>
  3964. //
  3965. // @param stateNumber the ATN state number
  3966. // @param context the full parse context
  3967. // @return The set of potentially valid input symbols which could follow the
  3968. // specified state in the specified context.
  3969. // @throws IllegalArgumentException if the ATN does not contain a state with
  3970. // number {@code stateNumber}
  3971. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  3972. ATN.prototype.getExpectedTokens = function( stateNumber, ctx ) {
  3973. if ( stateNumber < 0 || stateNumber >= this.states.length ) {
  3974. throw("Invalid state number.");
  3975. }
  3976. var s = this.states[stateNumber];
  3977. var following = this.nextTokens(s);
  3978. if (!following.contains(Token.EPSILON)) {
  3979. return following;
  3980. }
  3981. var expected = new IntervalSet();
  3982. expected.addSet(following);
  3983. expected.removeOne(Token.EPSILON);
  3984. while (ctx !== null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) {
  3985. var invokingState = this.states[ctx.invokingState];
  3986. var rt = invokingState.transitions[0];
  3987. following = this.nextTokens(rt.followState);
  3988. expected.addSet(following);
  3989. expected.removeOne(Token.EPSILON);
  3990. ctx = ctx.parentCtx;
  3991. }
  3992. if (following.contains(Token.EPSILON)) {
  3993. expected.addOne(Token.EOF);
  3994. }
  3995. return expected;
  3996. };
  3997. ATN.INVALID_ALT_NUMBER = 0;
  3998. exports.ATN = ATN;
  3999. /***/ }),
  4000. /***/ "./node_modules/antlr4/atn/ATNConfig.js":
  4001. /*!**********************************************!*\
  4002. !*** ./node_modules/antlr4/atn/ATNConfig.js ***!
  4003. \**********************************************/
  4004. /*! no static exports found */
  4005. /***/ (function(module, exports, __webpack_require__) {
  4006. //
  4007. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  4008. * Use of this file is governed by the BSD 3-clause license that
  4009. * can be found in the LICENSE.txt file in the project root.
  4010. */
  4011. ///
  4012. // A tuple: (ATN state, predicted alt, syntactic, semantic context).
  4013. // The syntactic context is a graph-structured stack node whose
  4014. // path(s) to the root is the rule invocation(s)
  4015. // chain used to arrive at the state. The semantic context is
  4016. // the tree of semantic predicates encountered before reaching
  4017. // an ATN state.
  4018. ///
  4019. var DecisionState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").DecisionState;
  4020. var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
  4021. var Hash = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").Hash;
  4022. function checkParams(params, isCfg) {
  4023. if(params===null) {
  4024. var result = { state:null, alt:null, context:null, semanticContext:null };
  4025. if(isCfg) {
  4026. result.reachesIntoOuterContext = 0;
  4027. }
  4028. return result;
  4029. } else {
  4030. var props = {};
  4031. props.state = params.state || null;
  4032. props.alt = (params.alt === undefined) ? null : params.alt;
  4033. props.context = params.context || null;
  4034. props.semanticContext = params.semanticContext || null;
  4035. if(isCfg) {
  4036. props.reachesIntoOuterContext = params.reachesIntoOuterContext || 0;
  4037. props.precedenceFilterSuppressed = params.precedenceFilterSuppressed || false;
  4038. }
  4039. return props;
  4040. }
  4041. }
  4042. function ATNConfig(params, config) {
  4043. this.checkContext(params, config);
  4044. params = checkParams(params);
  4045. config = checkParams(config, true);
  4046. // The ATN state associated with this configuration///
  4047. this.state = params.state!==null ? params.state : config.state;
  4048. // What alt (or lexer rule) is predicted by this configuration///
  4049. this.alt = params.alt!==null ? params.alt : config.alt;
  4050. // The stack of invoking states leading to the rule/states associated
  4051. // with this config. We track only those contexts pushed during
  4052. // execution of the ATN simulator.
  4053. this.context = params.context!==null ? params.context : config.context;
  4054. this.semanticContext = params.semanticContext!==null ? params.semanticContext :
  4055. (config.semanticContext!==null ? config.semanticContext : SemanticContext.NONE);
  4056. // We cannot execute predicates dependent upon local context unless
  4057. // we know for sure we are in the correct context. Because there is
  4058. // no way to do this efficiently, we simply cannot evaluate
  4059. // dependent predicates unless we are in the rule that initially
  4060. // invokes the ATN simulator.
  4061. //
  4062. // closure() tracks the depth of how far we dip into the
  4063. // outer context: depth &gt; 0. Note that it may not be totally
  4064. // accurate depth since I don't ever decrement. TODO: make it a boolean then
  4065. this.reachesIntoOuterContext = config.reachesIntoOuterContext;
  4066. this.precedenceFilterSuppressed = config.precedenceFilterSuppressed;
  4067. return this;
  4068. }
  4069. ATNConfig.prototype.checkContext = function(params, config) {
  4070. if((params.context===null || params.context===undefined) &&
  4071. (config===null || config.context===null || config.context===undefined)) {
  4072. this.context = null;
  4073. }
  4074. };
  4075. ATNConfig.prototype.hashCode = function() {
  4076. var hash = new Hash();
  4077. this.updateHashCode(hash);
  4078. return hash.finish();
  4079. };
  4080. ATNConfig.prototype.updateHashCode = function(hash) {
  4081. hash.update(this.state.stateNumber, this.alt, this.context, this.semanticContext);
  4082. };
  4083. // An ATN configuration is equal to another if both have
  4084. // the same state, they predict the same alternative, and
  4085. // syntactic/semantic contexts are the same.
  4086. ATNConfig.prototype.equals = function(other) {
  4087. if (this === other) {
  4088. return true;
  4089. } else if (! (other instanceof ATNConfig)) {
  4090. return false;
  4091. } else {
  4092. return this.state.stateNumber===other.state.stateNumber &&
  4093. this.alt===other.alt &&
  4094. (this.context===null ? other.context===null : this.context.equals(other.context)) &&
  4095. this.semanticContext.equals(other.semanticContext) &&
  4096. this.precedenceFilterSuppressed===other.precedenceFilterSuppressed;
  4097. }
  4098. };
  4099. ATNConfig.prototype.hashCodeForConfigSet = function() {
  4100. var hash = new Hash();
  4101. hash.update(this.state.stateNumber, this.alt, this.semanticContext);
  4102. return hash.finish();
  4103. };
  4104. ATNConfig.prototype.equalsForConfigSet = function(other) {
  4105. if (this === other) {
  4106. return true;
  4107. } else if (! (other instanceof ATNConfig)) {
  4108. return false;
  4109. } else {
  4110. return this.state.stateNumber===other.state.stateNumber &&
  4111. this.alt===other.alt &&
  4112. this.semanticContext.equals(other.semanticContext);
  4113. }
  4114. };
  4115. ATNConfig.prototype.toString = function() {
  4116. return "(" + this.state + "," + this.alt +
  4117. (this.context!==null ? ",[" + this.context.toString() + "]" : "") +
  4118. (this.semanticContext !== SemanticContext.NONE ?
  4119. ("," + this.semanticContext.toString())
  4120. : "") +
  4121. (this.reachesIntoOuterContext>0 ?
  4122. (",up=" + this.reachesIntoOuterContext)
  4123. : "") + ")";
  4124. };
  4125. function LexerATNConfig(params, config) {
  4126. ATNConfig.call(this, params, config);
  4127. // This is the backing field for {@link //getLexerActionExecutor}.
  4128. var lexerActionExecutor = params.lexerActionExecutor || null;
  4129. this.lexerActionExecutor = lexerActionExecutor || (config!==null ? config.lexerActionExecutor : null);
  4130. this.passedThroughNonGreedyDecision = config!==null ? this.checkNonGreedyDecision(config, this.state) : false;
  4131. return this;
  4132. }
  4133. LexerATNConfig.prototype = Object.create(ATNConfig.prototype);
  4134. LexerATNConfig.prototype.constructor = LexerATNConfig;
  4135. LexerATNConfig.prototype.updateHashCode = function(hash) {
  4136. hash.update(this.state.stateNumber, this.alt, this.context, this.semanticContext, this.passedThroughNonGreedyDecision, this.lexerActionExecutor);
  4137. };
  4138. LexerATNConfig.prototype.equals = function(other) {
  4139. return this === other ||
  4140. (other instanceof LexerATNConfig &&
  4141. this.passedThroughNonGreedyDecision == other.passedThroughNonGreedyDecision &&
  4142. (this.lexerActionExecutor ? this.lexerActionExecutor.equals(other.lexerActionExecutor) : !other.lexerActionExecutor) &&
  4143. ATNConfig.prototype.equals.call(this, other));
  4144. };
  4145. LexerATNConfig.prototype.hashCodeForConfigSet = LexerATNConfig.prototype.hashCode;
  4146. LexerATNConfig.prototype.equalsForConfigSet = LexerATNConfig.prototype.equals;
  4147. LexerATNConfig.prototype.checkNonGreedyDecision = function(source, target) {
  4148. return source.passedThroughNonGreedyDecision ||
  4149. (target instanceof DecisionState) && target.nonGreedy;
  4150. };
  4151. exports.ATNConfig = ATNConfig;
  4152. exports.LexerATNConfig = LexerATNConfig;
  4153. /***/ }),
  4154. /***/ "./node_modules/antlr4/atn/ATNConfigSet.js":
  4155. /*!*************************************************!*\
  4156. !*** ./node_modules/antlr4/atn/ATNConfigSet.js ***!
  4157. \*************************************************/
  4158. /*! no static exports found */
  4159. /***/ (function(module, exports, __webpack_require__) {
  4160. //
  4161. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  4162. * Use of this file is governed by the BSD 3-clause license that
  4163. * can be found in the LICENSE.txt file in the project root.
  4164. */
  4165. //
  4166. // Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track
  4167. // info about the set, with support for combining similar configurations using a
  4168. // graph-structured stack.
  4169. ///
  4170. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  4171. var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
  4172. var Hash = Utils.Hash;
  4173. var Set = Utils.Set;
  4174. var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
  4175. var merge = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").merge;
  4176. function hashATNConfig(c) {
  4177. return c.hashCodeForConfigSet();
  4178. }
  4179. function equalATNConfigs(a, b) {
  4180. if ( a===b ) {
  4181. return true;
  4182. } else if ( a===null || b===null ) {
  4183. return false;
  4184. } else
  4185. return a.equalsForConfigSet(b);
  4186. }
  4187. function ATNConfigSet(fullCtx) {
  4188. //
  4189. // The reason that we need this is because we don't want the hash map to use
  4190. // the standard hash code and equals. We need all configurations with the
  4191. // same
  4192. // {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively
  4193. // doubles
  4194. // the number of objects associated with ATNConfigs. The other solution is
  4195. // to
  4196. // use a hash table that lets us specify the equals/hashcode operation.
  4197. // All configs but hashed by (s, i, _, pi) not including context. Wiped out
  4198. // when we go readonly as this set becomes a DFA state.
  4199. this.configLookup = new Set(hashATNConfig, equalATNConfigs);
  4200. // Indicates that this configuration set is part of a full context
  4201. // LL prediction. It will be used to determine how to merge $. With SLL
  4202. // it's a wildcard whereas it is not for LL context merge.
  4203. this.fullCtx = fullCtx === undefined ? true : fullCtx;
  4204. // Indicates that the set of configurations is read-only. Do not
  4205. // allow any code to manipulate the set; DFA states will point at
  4206. // the sets and they must not change. This does not protect the other
  4207. // fields; in particular, conflictingAlts is set after
  4208. // we've made this readonly.
  4209. this.readOnly = false;
  4210. // Track the elements as they are added to the set; supports get(i)///
  4211. this.configs = [];
  4212. // TODO: these fields make me pretty uncomfortable but nice to pack up info
  4213. // together, saves recomputation
  4214. // TODO: can we track conflicts as they are added to save scanning configs
  4215. // later?
  4216. this.uniqueAlt = 0;
  4217. this.conflictingAlts = null;
  4218. // Used in parser and lexer. In lexer, it indicates we hit a pred
  4219. // while computing a closure operation. Don't make a DFA state from this.
  4220. this.hasSemanticContext = false;
  4221. this.dipsIntoOuterContext = false;
  4222. this.cachedHashCode = -1;
  4223. return this;
  4224. }
  4225. // Adding a new config means merging contexts with existing configs for
  4226. // {@code (s, i, pi, _)}, where {@code s} is the
  4227. // {@link ATNConfig//state}, {@code i} is the {@link ATNConfig//alt}, and
  4228. // {@code pi} is the {@link ATNConfig//semanticContext}. We use
  4229. // {@code (s,i,pi)} as key.
  4230. //
  4231. // <p>This method updates {@link //dipsIntoOuterContext} and
  4232. // {@link //hasSemanticContext} when necessary.</p>
  4233. // /
  4234. ATNConfigSet.prototype.add = function(config, mergeCache) {
  4235. if (mergeCache === undefined) {
  4236. mergeCache = null;
  4237. }
  4238. if (this.readOnly) {
  4239. throw "This set is readonly";
  4240. }
  4241. if (config.semanticContext !== SemanticContext.NONE) {
  4242. this.hasSemanticContext = true;
  4243. }
  4244. if (config.reachesIntoOuterContext > 0) {
  4245. this.dipsIntoOuterContext = true;
  4246. }
  4247. var existing = this.configLookup.add(config);
  4248. if (existing === config) {
  4249. this.cachedHashCode = -1;
  4250. this.configs.push(config); // track order here
  4251. return true;
  4252. }
  4253. // a previous (s,i,pi,_), merge with it and save result
  4254. var rootIsWildcard = !this.fullCtx;
  4255. var merged = merge(existing.context, config.context, rootIsWildcard, mergeCache);
  4256. // no need to check for existing.context, config.context in cache
  4257. // since only way to create new graphs is "call rule" and here. We
  4258. // cache at both places.
  4259. existing.reachesIntoOuterContext = Math.max( existing.reachesIntoOuterContext, config.reachesIntoOuterContext);
  4260. // make sure to preserve the precedence filter suppression during the merge
  4261. if (config.precedenceFilterSuppressed) {
  4262. existing.precedenceFilterSuppressed = true;
  4263. }
  4264. existing.context = merged; // replace context; no need to alt mapping
  4265. return true;
  4266. };
  4267. ATNConfigSet.prototype.getStates = function() {
  4268. var states = new Set();
  4269. for (var i = 0; i < this.configs.length; i++) {
  4270. states.add(this.configs[i].state);
  4271. }
  4272. return states;
  4273. };
  4274. ATNConfigSet.prototype.getPredicates = function() {
  4275. var preds = [];
  4276. for (var i = 0; i < this.configs.length; i++) {
  4277. var c = this.configs[i].semanticContext;
  4278. if (c !== SemanticContext.NONE) {
  4279. preds.push(c.semanticContext);
  4280. }
  4281. }
  4282. return preds;
  4283. };
  4284. Object.defineProperty(ATNConfigSet.prototype, "items", {
  4285. get : function() {
  4286. return this.configs;
  4287. }
  4288. });
  4289. ATNConfigSet.prototype.optimizeConfigs = function(interpreter) {
  4290. if (this.readOnly) {
  4291. throw "This set is readonly";
  4292. }
  4293. if (this.configLookup.length === 0) {
  4294. return;
  4295. }
  4296. for (var i = 0; i < this.configs.length; i++) {
  4297. var config = this.configs[i];
  4298. config.context = interpreter.getCachedContext(config.context);
  4299. }
  4300. };
  4301. ATNConfigSet.prototype.addAll = function(coll) {
  4302. for (var i = 0; i < coll.length; i++) {
  4303. this.add(coll[i]);
  4304. }
  4305. return false;
  4306. };
  4307. ATNConfigSet.prototype.equals = function(other) {
  4308. return this === other ||
  4309. (other instanceof ATNConfigSet &&
  4310. Utils.equalArrays(this.configs, other.configs) &&
  4311. this.fullCtx === other.fullCtx &&
  4312. this.uniqueAlt === other.uniqueAlt &&
  4313. this.conflictingAlts === other.conflictingAlts &&
  4314. this.hasSemanticContext === other.hasSemanticContext &&
  4315. this.dipsIntoOuterContext === other.dipsIntoOuterContext);
  4316. };
  4317. ATNConfigSet.prototype.hashCode = function() {
  4318. var hash = new Hash();
  4319. this.updateHashCode(hash);
  4320. return hash.finish();
  4321. };
  4322. ATNConfigSet.prototype.updateHashCode = function(hash) {
  4323. if (this.readOnly) {
  4324. if (this.cachedHashCode === -1) {
  4325. var hash = new Hash();
  4326. hash.update(this.configs);
  4327. this.cachedHashCode = hash.finish();
  4328. }
  4329. hash.update(this.cachedHashCode);
  4330. } else {
  4331. hash.update(this.configs);
  4332. }
  4333. };
  4334. Object.defineProperty(ATNConfigSet.prototype, "length", {
  4335. get : function() {
  4336. return this.configs.length;
  4337. }
  4338. });
  4339. ATNConfigSet.prototype.isEmpty = function() {
  4340. return this.configs.length === 0;
  4341. };
  4342. ATNConfigSet.prototype.contains = function(item) {
  4343. if (this.configLookup === null) {
  4344. throw "This method is not implemented for readonly sets.";
  4345. }
  4346. return this.configLookup.contains(item);
  4347. };
  4348. ATNConfigSet.prototype.containsFast = function(item) {
  4349. if (this.configLookup === null) {
  4350. throw "This method is not implemented for readonly sets.";
  4351. }
  4352. return this.configLookup.containsFast(item);
  4353. };
  4354. ATNConfigSet.prototype.clear = function() {
  4355. if (this.readOnly) {
  4356. throw "This set is readonly";
  4357. }
  4358. this.configs = [];
  4359. this.cachedHashCode = -1;
  4360. this.configLookup = new Set();
  4361. };
  4362. ATNConfigSet.prototype.setReadonly = function(readOnly) {
  4363. this.readOnly = readOnly;
  4364. if (readOnly) {
  4365. this.configLookup = null; // can't mod, no need for lookup cache
  4366. }
  4367. };
  4368. ATNConfigSet.prototype.toString = function() {
  4369. return Utils.arrayToString(this.configs) +
  4370. (this.hasSemanticContext ? ",hasSemanticContext=" + this.hasSemanticContext : "") +
  4371. (this.uniqueAlt !== ATN.INVALID_ALT_NUMBER ? ",uniqueAlt=" + this.uniqueAlt : "") +
  4372. (this.conflictingAlts !== null ? ",conflictingAlts=" + this.conflictingAlts : "") +
  4373. (this.dipsIntoOuterContext ? ",dipsIntoOuterContext" : "");
  4374. };
  4375. function OrderedATNConfigSet() {
  4376. ATNConfigSet.call(this);
  4377. this.configLookup = new Set();
  4378. return this;
  4379. }
  4380. OrderedATNConfigSet.prototype = Object.create(ATNConfigSet.prototype);
  4381. OrderedATNConfigSet.prototype.constructor = OrderedATNConfigSet;
  4382. exports.ATNConfigSet = ATNConfigSet;
  4383. exports.OrderedATNConfigSet = OrderedATNConfigSet;
  4384. /***/ }),
  4385. /***/ "./node_modules/antlr4/atn/ATNDeserializationOptions.js":
  4386. /*!**************************************************************!*\
  4387. !*** ./node_modules/antlr4/atn/ATNDeserializationOptions.js ***!
  4388. \**************************************************************/
  4389. /*! no static exports found */
  4390. /***/ (function(module, exports) {
  4391. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  4392. * Use of this file is governed by the BSD 3-clause license that
  4393. * can be found in the LICENSE.txt file in the project root.
  4394. */
  4395. function ATNDeserializationOptions(copyFrom) {
  4396. if(copyFrom===undefined) {
  4397. copyFrom = null;
  4398. }
  4399. this.readOnly = false;
  4400. this.verifyATN = copyFrom===null ? true : copyFrom.verifyATN;
  4401. this.generateRuleBypassTransitions = copyFrom===null ? false : copyFrom.generateRuleBypassTransitions;
  4402. return this;
  4403. }
  4404. ATNDeserializationOptions.defaultOptions = new ATNDeserializationOptions();
  4405. ATNDeserializationOptions.defaultOptions.readOnly = true;
  4406. // def __setattr__(self, key, value):
  4407. // if key!="readOnly" and self.readOnly:
  4408. // raise Exception("The object is read only.")
  4409. // super(type(self), self).__setattr__(key,value)
  4410. exports.ATNDeserializationOptions = ATNDeserializationOptions;
  4411. /***/ }),
  4412. /***/ "./node_modules/antlr4/atn/ATNDeserializer.js":
  4413. /*!****************************************************!*\
  4414. !*** ./node_modules/antlr4/atn/ATNDeserializer.js ***!
  4415. \****************************************************/
  4416. /*! no static exports found */
  4417. /***/ (function(module, exports, __webpack_require__) {
  4418. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  4419. * Use of this file is governed by the BSD 3-clause license that
  4420. * can be found in the LICENSE.txt file in the project root.
  4421. */
  4422. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  4423. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  4424. var ATNType = __webpack_require__(/*! ./ATNType */ "./node_modules/antlr4/atn/ATNType.js").ATNType;
  4425. var ATNStates = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js");
  4426. var ATNState = ATNStates.ATNState;
  4427. var BasicState = ATNStates.BasicState;
  4428. var DecisionState = ATNStates.DecisionState;
  4429. var BlockStartState = ATNStates.BlockStartState;
  4430. var BlockEndState = ATNStates.BlockEndState;
  4431. var LoopEndState = ATNStates.LoopEndState;
  4432. var RuleStartState = ATNStates.RuleStartState;
  4433. var RuleStopState = ATNStates.RuleStopState;
  4434. var TokensStartState = ATNStates.TokensStartState;
  4435. var PlusLoopbackState = ATNStates.PlusLoopbackState;
  4436. var StarLoopbackState = ATNStates.StarLoopbackState;
  4437. var StarLoopEntryState = ATNStates.StarLoopEntryState;
  4438. var PlusBlockStartState = ATNStates.PlusBlockStartState;
  4439. var StarBlockStartState = ATNStates.StarBlockStartState;
  4440. var BasicBlockStartState = ATNStates.BasicBlockStartState;
  4441. var Transitions = __webpack_require__(/*! ./Transition */ "./node_modules/antlr4/atn/Transition.js");
  4442. var Transition = Transitions.Transition;
  4443. var AtomTransition = Transitions.AtomTransition;
  4444. var SetTransition = Transitions.SetTransition;
  4445. var NotSetTransition = Transitions.NotSetTransition;
  4446. var RuleTransition = Transitions.RuleTransition;
  4447. var RangeTransition = Transitions.RangeTransition;
  4448. var ActionTransition = Transitions.ActionTransition;
  4449. var EpsilonTransition = Transitions.EpsilonTransition;
  4450. var WildcardTransition = Transitions.WildcardTransition;
  4451. var PredicateTransition = Transitions.PredicateTransition;
  4452. var PrecedencePredicateTransition = Transitions.PrecedencePredicateTransition;
  4453. var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  4454. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  4455. var ATNDeserializationOptions = __webpack_require__(/*! ./ATNDeserializationOptions */ "./node_modules/antlr4/atn/ATNDeserializationOptions.js").ATNDeserializationOptions;
  4456. var LexerActions = __webpack_require__(/*! ./LexerAction */ "./node_modules/antlr4/atn/LexerAction.js");
  4457. var LexerActionType = LexerActions.LexerActionType;
  4458. var LexerSkipAction = LexerActions.LexerSkipAction;
  4459. var LexerChannelAction = LexerActions.LexerChannelAction;
  4460. var LexerCustomAction = LexerActions.LexerCustomAction;
  4461. var LexerMoreAction = LexerActions.LexerMoreAction;
  4462. var LexerTypeAction = LexerActions.LexerTypeAction;
  4463. var LexerPushModeAction = LexerActions.LexerPushModeAction;
  4464. var LexerPopModeAction = LexerActions.LexerPopModeAction;
  4465. var LexerModeAction = LexerActions.LexerModeAction;
  4466. // This is the earliest supported serialized UUID.
  4467. // stick to serialized version for now, we don't need a UUID instance
  4468. var BASE_SERIALIZED_UUID = "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E";
  4469. //
  4470. // This UUID indicates the serialized ATN contains two sets of
  4471. // IntervalSets, where the second set's values are encoded as
  4472. // 32-bit integers to support the full Unicode SMP range up to U+10FFFF.
  4473. //
  4474. var ADDED_UNICODE_SMP = "59627784-3BE5-417A-B9EB-8131A7286089";
  4475. // This list contains all of the currently supported UUIDs, ordered by when
  4476. // the feature first appeared in this branch.
  4477. var SUPPORTED_UUIDS = [ BASE_SERIALIZED_UUID, ADDED_UNICODE_SMP ];
  4478. var SERIALIZED_VERSION = 3;
  4479. // This is the current serialized UUID.
  4480. var SERIALIZED_UUID = ADDED_UNICODE_SMP;
  4481. function initArray( length, value) {
  4482. var tmp = [];
  4483. tmp[length-1] = value;
  4484. return tmp.map(function(i) {return value;});
  4485. }
  4486. function ATNDeserializer (options) {
  4487. if ( options=== undefined || options === null ) {
  4488. options = ATNDeserializationOptions.defaultOptions;
  4489. }
  4490. this.deserializationOptions = options;
  4491. this.stateFactories = null;
  4492. this.actionFactories = null;
  4493. return this;
  4494. }
  4495. // Determines if a particular serialized representation of an ATN supports
  4496. // a particular feature, identified by the {@link UUID} used for serializing
  4497. // the ATN at the time the feature was first introduced.
  4498. //
  4499. // @param feature The {@link UUID} marking the first time the feature was
  4500. // supported in the serialized ATN.
  4501. // @param actualUuid The {@link UUID} of the actual serialized ATN which is
  4502. // currently being deserialized.
  4503. // @return {@code true} if the {@code actualUuid} value represents a
  4504. // serialized ATN at or after the feature identified by {@code feature} was
  4505. // introduced; otherwise, {@code false}.
  4506. ATNDeserializer.prototype.isFeatureSupported = function(feature, actualUuid) {
  4507. var idx1 = SUPPORTED_UUIDS.indexOf(feature);
  4508. if (idx1<0) {
  4509. return false;
  4510. }
  4511. var idx2 = SUPPORTED_UUIDS.indexOf(actualUuid);
  4512. return idx2 >= idx1;
  4513. };
  4514. ATNDeserializer.prototype.deserialize = function(data) {
  4515. this.reset(data);
  4516. this.checkVersion();
  4517. this.checkUUID();
  4518. var atn = this.readATN();
  4519. this.readStates(atn);
  4520. this.readRules(atn);
  4521. this.readModes(atn);
  4522. var sets = [];
  4523. // First, deserialize sets with 16-bit arguments <= U+FFFF.
  4524. this.readSets(atn, sets, this.readInt.bind(this));
  4525. // Next, if the ATN was serialized with the Unicode SMP feature,
  4526. // deserialize sets with 32-bit arguments <= U+10FFFF.
  4527. if (this.isFeatureSupported(ADDED_UNICODE_SMP, this.uuid)) {
  4528. this.readSets(atn, sets, this.readInt32.bind(this));
  4529. }
  4530. this.readEdges(atn, sets);
  4531. this.readDecisions(atn);
  4532. this.readLexerActions(atn);
  4533. this.markPrecedenceDecisions(atn);
  4534. this.verifyATN(atn);
  4535. if (this.deserializationOptions.generateRuleBypassTransitions && atn.grammarType === ATNType.PARSER ) {
  4536. this.generateRuleBypassTransitions(atn);
  4537. // re-verify after modification
  4538. this.verifyATN(atn);
  4539. }
  4540. return atn;
  4541. };
  4542. ATNDeserializer.prototype.reset = function(data) {
  4543. var adjust = function(c) {
  4544. var v = c.charCodeAt(0);
  4545. return v>1 ? v-2 : v + 65533;
  4546. };
  4547. var temp = data.split("").map(adjust);
  4548. // don't adjust the first value since that's the version number
  4549. temp[0] = data.charCodeAt(0);
  4550. this.data = temp;
  4551. this.pos = 0;
  4552. };
  4553. ATNDeserializer.prototype.checkVersion = function() {
  4554. var version = this.readInt();
  4555. if ( version !== SERIALIZED_VERSION ) {
  4556. throw ("Could not deserialize ATN with version " + version + " (expected " + SERIALIZED_VERSION + ").");
  4557. }
  4558. };
  4559. ATNDeserializer.prototype.checkUUID = function() {
  4560. var uuid = this.readUUID();
  4561. if (SUPPORTED_UUIDS.indexOf(uuid)<0) {
  4562. throw ("Could not deserialize ATN with UUID: " + uuid +
  4563. " (expected " + SERIALIZED_UUID + " or a legacy UUID).", uuid, SERIALIZED_UUID);
  4564. }
  4565. this.uuid = uuid;
  4566. };
  4567. ATNDeserializer.prototype.readATN = function() {
  4568. var grammarType = this.readInt();
  4569. var maxTokenType = this.readInt();
  4570. return new ATN(grammarType, maxTokenType);
  4571. };
  4572. ATNDeserializer.prototype.readStates = function(atn) {
  4573. var j, pair, stateNumber;
  4574. var loopBackStateNumbers = [];
  4575. var endStateNumbers = [];
  4576. var nstates = this.readInt();
  4577. for(var i=0; i<nstates; i++) {
  4578. var stype = this.readInt();
  4579. // ignore bad type of states
  4580. if (stype===ATNState.INVALID_TYPE) {
  4581. atn.addState(null);
  4582. continue;
  4583. }
  4584. var ruleIndex = this.readInt();
  4585. if (ruleIndex === 0xFFFF) {
  4586. ruleIndex = -1;
  4587. }
  4588. var s = this.stateFactory(stype, ruleIndex);
  4589. if (stype === ATNState.LOOP_END) { // special case
  4590. var loopBackStateNumber = this.readInt();
  4591. loopBackStateNumbers.push([s, loopBackStateNumber]);
  4592. } else if(s instanceof BlockStartState) {
  4593. var endStateNumber = this.readInt();
  4594. endStateNumbers.push([s, endStateNumber]);
  4595. }
  4596. atn.addState(s);
  4597. }
  4598. // delay the assignment of loop back and end states until we know all the
  4599. // state instances have been initialized
  4600. for (j=0; j<loopBackStateNumbers.length; j++) {
  4601. pair = loopBackStateNumbers[j];
  4602. pair[0].loopBackState = atn.states[pair[1]];
  4603. }
  4604. for (j=0; j<endStateNumbers.length; j++) {
  4605. pair = endStateNumbers[j];
  4606. pair[0].endState = atn.states[pair[1]];
  4607. }
  4608. var numNonGreedyStates = this.readInt();
  4609. for (j=0; j<numNonGreedyStates; j++) {
  4610. stateNumber = this.readInt();
  4611. atn.states[stateNumber].nonGreedy = true;
  4612. }
  4613. var numPrecedenceStates = this.readInt();
  4614. for (j=0; j<numPrecedenceStates; j++) {
  4615. stateNumber = this.readInt();
  4616. atn.states[stateNumber].isPrecedenceRule = true;
  4617. }
  4618. };
  4619. ATNDeserializer.prototype.readRules = function(atn) {
  4620. var i;
  4621. var nrules = this.readInt();
  4622. if (atn.grammarType === ATNType.LEXER ) {
  4623. atn.ruleToTokenType = initArray(nrules, 0);
  4624. }
  4625. atn.ruleToStartState = initArray(nrules, 0);
  4626. for (i=0; i<nrules; i++) {
  4627. var s = this.readInt();
  4628. var startState = atn.states[s];
  4629. atn.ruleToStartState[i] = startState;
  4630. if ( atn.grammarType === ATNType.LEXER ) {
  4631. var tokenType = this.readInt();
  4632. if (tokenType === 0xFFFF) {
  4633. tokenType = Token.EOF;
  4634. }
  4635. atn.ruleToTokenType[i] = tokenType;
  4636. }
  4637. }
  4638. atn.ruleToStopState = initArray(nrules, 0);
  4639. for (i=0; i<atn.states.length; i++) {
  4640. var state = atn.states[i];
  4641. if (!(state instanceof RuleStopState)) {
  4642. continue;
  4643. }
  4644. atn.ruleToStopState[state.ruleIndex] = state;
  4645. atn.ruleToStartState[state.ruleIndex].stopState = state;
  4646. }
  4647. };
  4648. ATNDeserializer.prototype.readModes = function(atn) {
  4649. var nmodes = this.readInt();
  4650. for (var i=0; i<nmodes; i++) {
  4651. var s = this.readInt();
  4652. atn.modeToStartState.push(atn.states[s]);
  4653. }
  4654. };
  4655. ATNDeserializer.prototype.readSets = function(atn, sets, readUnicode) {
  4656. var m = this.readInt();
  4657. for (var i=0; i<m; i++) {
  4658. var iset = new IntervalSet();
  4659. sets.push(iset);
  4660. var n = this.readInt();
  4661. var containsEof = this.readInt();
  4662. if (containsEof!==0) {
  4663. iset.addOne(-1);
  4664. }
  4665. for (var j=0; j<n; j++) {
  4666. var i1 = readUnicode();
  4667. var i2 = readUnicode();
  4668. iset.addRange(i1, i2);
  4669. }
  4670. }
  4671. };
  4672. ATNDeserializer.prototype.readEdges = function(atn, sets) {
  4673. var i, j, state, trans, target;
  4674. var nedges = this.readInt();
  4675. for (i=0; i<nedges; i++) {
  4676. var src = this.readInt();
  4677. var trg = this.readInt();
  4678. var ttype = this.readInt();
  4679. var arg1 = this.readInt();
  4680. var arg2 = this.readInt();
  4681. var arg3 = this.readInt();
  4682. trans = this.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets);
  4683. var srcState = atn.states[src];
  4684. srcState.addTransition(trans);
  4685. }
  4686. // edges for rule stop states can be derived, so they aren't serialized
  4687. for (i=0; i<atn.states.length; i++) {
  4688. state = atn.states[i];
  4689. for (j=0; j<state.transitions.length; j++) {
  4690. var t = state.transitions[j];
  4691. if (!(t instanceof RuleTransition)) {
  4692. continue;
  4693. }
  4694. var outermostPrecedenceReturn = -1;
  4695. if (atn.ruleToStartState[t.target.ruleIndex].isPrecedenceRule) {
  4696. if (t.precedence === 0) {
  4697. outermostPrecedenceReturn = t.target.ruleIndex;
  4698. }
  4699. }
  4700. trans = new EpsilonTransition(t.followState, outermostPrecedenceReturn);
  4701. atn.ruleToStopState[t.target.ruleIndex].addTransition(trans);
  4702. }
  4703. }
  4704. for (i=0; i<atn.states.length; i++) {
  4705. state = atn.states[i];
  4706. if (state instanceof BlockStartState) {
  4707. // we need to know the end state to set its start state
  4708. if (state.endState === null) {
  4709. throw ("IllegalState");
  4710. }
  4711. // block end states can only be associated to a single block start
  4712. // state
  4713. if ( state.endState.startState !== null) {
  4714. throw ("IllegalState");
  4715. }
  4716. state.endState.startState = state;
  4717. }
  4718. if (state instanceof PlusLoopbackState) {
  4719. for (j=0; j<state.transitions.length; j++) {
  4720. target = state.transitions[j].target;
  4721. if (target instanceof PlusBlockStartState) {
  4722. target.loopBackState = state;
  4723. }
  4724. }
  4725. } else if (state instanceof StarLoopbackState) {
  4726. for (j=0; j<state.transitions.length; j++) {
  4727. target = state.transitions[j].target;
  4728. if (target instanceof StarLoopEntryState) {
  4729. target.loopBackState = state;
  4730. }
  4731. }
  4732. }
  4733. }
  4734. };
  4735. ATNDeserializer.prototype.readDecisions = function(atn) {
  4736. var ndecisions = this.readInt();
  4737. for (var i=0; i<ndecisions; i++) {
  4738. var s = this.readInt();
  4739. var decState = atn.states[s];
  4740. atn.decisionToState.push(decState);
  4741. decState.decision = i;
  4742. }
  4743. };
  4744. ATNDeserializer.prototype.readLexerActions = function(atn) {
  4745. if (atn.grammarType === ATNType.LEXER) {
  4746. var count = this.readInt();
  4747. atn.lexerActions = initArray(count, null);
  4748. for (var i=0; i<count; i++) {
  4749. var actionType = this.readInt();
  4750. var data1 = this.readInt();
  4751. if (data1 === 0xFFFF) {
  4752. data1 = -1;
  4753. }
  4754. var data2 = this.readInt();
  4755. if (data2 === 0xFFFF) {
  4756. data2 = -1;
  4757. }
  4758. var lexerAction = this.lexerActionFactory(actionType, data1, data2);
  4759. atn.lexerActions[i] = lexerAction;
  4760. }
  4761. }
  4762. };
  4763. ATNDeserializer.prototype.generateRuleBypassTransitions = function(atn) {
  4764. var i;
  4765. var count = atn.ruleToStartState.length;
  4766. for(i=0; i<count; i++) {
  4767. atn.ruleToTokenType[i] = atn.maxTokenType + i + 1;
  4768. }
  4769. for(i=0; i<count; i++) {
  4770. this.generateRuleBypassTransition(atn, i);
  4771. }
  4772. };
  4773. ATNDeserializer.prototype.generateRuleBypassTransition = function(atn, idx) {
  4774. var i, state;
  4775. var bypassStart = new BasicBlockStartState();
  4776. bypassStart.ruleIndex = idx;
  4777. atn.addState(bypassStart);
  4778. var bypassStop = new BlockEndState();
  4779. bypassStop.ruleIndex = idx;
  4780. atn.addState(bypassStop);
  4781. bypassStart.endState = bypassStop;
  4782. atn.defineDecisionState(bypassStart);
  4783. bypassStop.startState = bypassStart;
  4784. var excludeTransition = null;
  4785. var endState = null;
  4786. if (atn.ruleToStartState[idx].isPrecedenceRule) {
  4787. // wrap from the beginning of the rule to the StarLoopEntryState
  4788. endState = null;
  4789. for(i=0; i<atn.states.length; i++) {
  4790. state = atn.states[i];
  4791. if (this.stateIsEndStateFor(state, idx)) {
  4792. endState = state;
  4793. excludeTransition = state.loopBackState.transitions[0];
  4794. break;
  4795. }
  4796. }
  4797. if (excludeTransition === null) {
  4798. throw ("Couldn't identify final state of the precedence rule prefix section.");
  4799. }
  4800. } else {
  4801. endState = atn.ruleToStopState[idx];
  4802. }
  4803. // all non-excluded transitions that currently target end state need to
  4804. // target blockEnd instead
  4805. for(i=0; i<atn.states.length; i++) {
  4806. state = atn.states[i];
  4807. for(var j=0; j<state.transitions.length; j++) {
  4808. var transition = state.transitions[j];
  4809. if (transition === excludeTransition) {
  4810. continue;
  4811. }
  4812. if (transition.target === endState) {
  4813. transition.target = bypassStop;
  4814. }
  4815. }
  4816. }
  4817. // all transitions leaving the rule start state need to leave blockStart
  4818. // instead
  4819. var ruleToStartState = atn.ruleToStartState[idx];
  4820. var count = ruleToStartState.transitions.length;
  4821. while ( count > 0) {
  4822. bypassStart.addTransition(ruleToStartState.transitions[count-1]);
  4823. ruleToStartState.transitions = ruleToStartState.transitions.slice(-1);
  4824. }
  4825. // link the new states
  4826. atn.ruleToStartState[idx].addTransition(new EpsilonTransition(bypassStart));
  4827. bypassStop.addTransition(new EpsilonTransition(endState));
  4828. var matchState = new BasicState();
  4829. atn.addState(matchState);
  4830. matchState.addTransition(new AtomTransition(bypassStop, atn.ruleToTokenType[idx]));
  4831. bypassStart.addTransition(new EpsilonTransition(matchState));
  4832. };
  4833. ATNDeserializer.prototype.stateIsEndStateFor = function(state, idx) {
  4834. if ( state.ruleIndex !== idx) {
  4835. return null;
  4836. }
  4837. if (!( state instanceof StarLoopEntryState)) {
  4838. return null;
  4839. }
  4840. var maybeLoopEndState = state.transitions[state.transitions.length - 1].target;
  4841. if (!( maybeLoopEndState instanceof LoopEndState)) {
  4842. return null;
  4843. }
  4844. if (maybeLoopEndState.epsilonOnlyTransitions &&
  4845. (maybeLoopEndState.transitions[0].target instanceof RuleStopState)) {
  4846. return state;
  4847. } else {
  4848. return null;
  4849. }
  4850. };
  4851. //
  4852. // Analyze the {@link StarLoopEntryState} states in the specified ATN to set
  4853. // the {@link StarLoopEntryState//isPrecedenceDecision} field to the
  4854. // correct value.
  4855. //
  4856. // @param atn The ATN.
  4857. //
  4858. ATNDeserializer.prototype.markPrecedenceDecisions = function(atn) {
  4859. for(var i=0; i<atn.states.length; i++) {
  4860. var state = atn.states[i];
  4861. if (!( state instanceof StarLoopEntryState)) {
  4862. continue;
  4863. }
  4864. // We analyze the ATN to determine if this ATN decision state is the
  4865. // decision for the closure block that determines whether a
  4866. // precedence rule should continue or complete.
  4867. //
  4868. if ( atn.ruleToStartState[state.ruleIndex].isPrecedenceRule) {
  4869. var maybeLoopEndState = state.transitions[state.transitions.length - 1].target;
  4870. if (maybeLoopEndState instanceof LoopEndState) {
  4871. if ( maybeLoopEndState.epsilonOnlyTransitions &&
  4872. (maybeLoopEndState.transitions[0].target instanceof RuleStopState)) {
  4873. state.isPrecedenceDecision = true;
  4874. }
  4875. }
  4876. }
  4877. }
  4878. };
  4879. ATNDeserializer.prototype.verifyATN = function(atn) {
  4880. if (!this.deserializationOptions.verifyATN) {
  4881. return;
  4882. }
  4883. // verify assumptions
  4884. for(var i=0; i<atn.states.length; i++) {
  4885. var state = atn.states[i];
  4886. if (state === null) {
  4887. continue;
  4888. }
  4889. this.checkCondition(state.epsilonOnlyTransitions || state.transitions.length <= 1);
  4890. if (state instanceof PlusBlockStartState) {
  4891. this.checkCondition(state.loopBackState !== null);
  4892. } else if (state instanceof StarLoopEntryState) {
  4893. this.checkCondition(state.loopBackState !== null);
  4894. this.checkCondition(state.transitions.length === 2);
  4895. if (state.transitions[0].target instanceof StarBlockStartState) {
  4896. this.checkCondition(state.transitions[1].target instanceof LoopEndState);
  4897. this.checkCondition(!state.nonGreedy);
  4898. } else if (state.transitions[0].target instanceof LoopEndState) {
  4899. this.checkCondition(state.transitions[1].target instanceof StarBlockStartState);
  4900. this.checkCondition(state.nonGreedy);
  4901. } else {
  4902. throw("IllegalState");
  4903. }
  4904. } else if (state instanceof StarLoopbackState) {
  4905. this.checkCondition(state.transitions.length === 1);
  4906. this.checkCondition(state.transitions[0].target instanceof StarLoopEntryState);
  4907. } else if (state instanceof LoopEndState) {
  4908. this.checkCondition(state.loopBackState !== null);
  4909. } else if (state instanceof RuleStartState) {
  4910. this.checkCondition(state.stopState !== null);
  4911. } else if (state instanceof BlockStartState) {
  4912. this.checkCondition(state.endState !== null);
  4913. } else if (state instanceof BlockEndState) {
  4914. this.checkCondition(state.startState !== null);
  4915. } else if (state instanceof DecisionState) {
  4916. this.checkCondition(state.transitions.length <= 1 || state.decision >= 0);
  4917. } else {
  4918. this.checkCondition(state.transitions.length <= 1 || (state instanceof RuleStopState));
  4919. }
  4920. }
  4921. };
  4922. ATNDeserializer.prototype.checkCondition = function(condition, message) {
  4923. if (!condition) {
  4924. if (message === undefined || message===null) {
  4925. message = "IllegalState";
  4926. }
  4927. throw (message);
  4928. }
  4929. };
  4930. ATNDeserializer.prototype.readInt = function() {
  4931. return this.data[this.pos++];
  4932. };
  4933. ATNDeserializer.prototype.readInt32 = function() {
  4934. var low = this.readInt();
  4935. var high = this.readInt();
  4936. return low | (high << 16);
  4937. };
  4938. ATNDeserializer.prototype.readLong = function() {
  4939. var low = this.readInt32();
  4940. var high = this.readInt32();
  4941. return (low & 0x00000000FFFFFFFF) | (high << 32);
  4942. };
  4943. function createByteToHex() {
  4944. var bth = [];
  4945. for (var i = 0; i < 256; i++) {
  4946. bth[i] = (i + 0x100).toString(16).substr(1).toUpperCase();
  4947. }
  4948. return bth;
  4949. }
  4950. var byteToHex = createByteToHex();
  4951. ATNDeserializer.prototype.readUUID = function() {
  4952. var bb = [];
  4953. for(var i=7;i>=0;i--) {
  4954. var int = this.readInt();
  4955. /* jshint bitwise: false */
  4956. bb[(2*i)+1] = int & 0xFF;
  4957. bb[2*i] = (int >> 8) & 0xFF;
  4958. }
  4959. return byteToHex[bb[0]] + byteToHex[bb[1]] +
  4960. byteToHex[bb[2]] + byteToHex[bb[3]] + '-' +
  4961. byteToHex[bb[4]] + byteToHex[bb[5]] + '-' +
  4962. byteToHex[bb[6]] + byteToHex[bb[7]] + '-' +
  4963. byteToHex[bb[8]] + byteToHex[bb[9]] + '-' +
  4964. byteToHex[bb[10]] + byteToHex[bb[11]] +
  4965. byteToHex[bb[12]] + byteToHex[bb[13]] +
  4966. byteToHex[bb[14]] + byteToHex[bb[15]];
  4967. };
  4968. ATNDeserializer.prototype.edgeFactory = function(atn, type, src, trg, arg1, arg2, arg3, sets) {
  4969. var target = atn.states[trg];
  4970. switch(type) {
  4971. case Transition.EPSILON:
  4972. return new EpsilonTransition(target);
  4973. case Transition.RANGE:
  4974. return arg3 !== 0 ? new RangeTransition(target, Token.EOF, arg2) : new RangeTransition(target, arg1, arg2);
  4975. case Transition.RULE:
  4976. return new RuleTransition(atn.states[arg1], arg2, arg3, target);
  4977. case Transition.PREDICATE:
  4978. return new PredicateTransition(target, arg1, arg2, arg3 !== 0);
  4979. case Transition.PRECEDENCE:
  4980. return new PrecedencePredicateTransition(target, arg1);
  4981. case Transition.ATOM:
  4982. return arg3 !== 0 ? new AtomTransition(target, Token.EOF) : new AtomTransition(target, arg1);
  4983. case Transition.ACTION:
  4984. return new ActionTransition(target, arg1, arg2, arg3 !== 0);
  4985. case Transition.SET:
  4986. return new SetTransition(target, sets[arg1]);
  4987. case Transition.NOT_SET:
  4988. return new NotSetTransition(target, sets[arg1]);
  4989. case Transition.WILDCARD:
  4990. return new WildcardTransition(target);
  4991. default:
  4992. throw "The specified transition type: " + type + " is not valid.";
  4993. }
  4994. };
  4995. ATNDeserializer.prototype.stateFactory = function(type, ruleIndex) {
  4996. if (this.stateFactories === null) {
  4997. var sf = [];
  4998. sf[ATNState.INVALID_TYPE] = null;
  4999. sf[ATNState.BASIC] = function() { return new BasicState(); };
  5000. sf[ATNState.RULE_START] = function() { return new RuleStartState(); };
  5001. sf[ATNState.BLOCK_START] = function() { return new BasicBlockStartState(); };
  5002. sf[ATNState.PLUS_BLOCK_START] = function() { return new PlusBlockStartState(); };
  5003. sf[ATNState.STAR_BLOCK_START] = function() { return new StarBlockStartState(); };
  5004. sf[ATNState.TOKEN_START] = function() { return new TokensStartState(); };
  5005. sf[ATNState.RULE_STOP] = function() { return new RuleStopState(); };
  5006. sf[ATNState.BLOCK_END] = function() { return new BlockEndState(); };
  5007. sf[ATNState.STAR_LOOP_BACK] = function() { return new StarLoopbackState(); };
  5008. sf[ATNState.STAR_LOOP_ENTRY] = function() { return new StarLoopEntryState(); };
  5009. sf[ATNState.PLUS_LOOP_BACK] = function() { return new PlusLoopbackState(); };
  5010. sf[ATNState.LOOP_END] = function() { return new LoopEndState(); };
  5011. this.stateFactories = sf;
  5012. }
  5013. if (type>this.stateFactories.length || this.stateFactories[type] === null) {
  5014. throw("The specified state type " + type + " is not valid.");
  5015. } else {
  5016. var s = this.stateFactories[type]();
  5017. if (s!==null) {
  5018. s.ruleIndex = ruleIndex;
  5019. return s;
  5020. }
  5021. }
  5022. };
  5023. ATNDeserializer.prototype.lexerActionFactory = function(type, data1, data2) {
  5024. if (this.actionFactories === null) {
  5025. var af = [];
  5026. af[LexerActionType.CHANNEL] = function(data1, data2) { return new LexerChannelAction(data1); };
  5027. af[LexerActionType.CUSTOM] = function(data1, data2) { return new LexerCustomAction(data1, data2); };
  5028. af[LexerActionType.MODE] = function(data1, data2) { return new LexerModeAction(data1); };
  5029. af[LexerActionType.MORE] = function(data1, data2) { return LexerMoreAction.INSTANCE; };
  5030. af[LexerActionType.POP_MODE] = function(data1, data2) { return LexerPopModeAction.INSTANCE; };
  5031. af[LexerActionType.PUSH_MODE] = function(data1, data2) { return new LexerPushModeAction(data1); };
  5032. af[LexerActionType.SKIP] = function(data1, data2) { return LexerSkipAction.INSTANCE; };
  5033. af[LexerActionType.TYPE] = function(data1, data2) { return new LexerTypeAction(data1); };
  5034. this.actionFactories = af;
  5035. }
  5036. if (type>this.actionFactories.length || this.actionFactories[type] === null) {
  5037. throw("The specified lexer action type " + type + " is not valid.");
  5038. } else {
  5039. return this.actionFactories[type](data1, data2);
  5040. }
  5041. };
  5042. exports.ATNDeserializer = ATNDeserializer;
  5043. /***/ }),
  5044. /***/ "./node_modules/antlr4/atn/ATNSimulator.js":
  5045. /*!*************************************************!*\
  5046. !*** ./node_modules/antlr4/atn/ATNSimulator.js ***!
  5047. \*************************************************/
  5048. /*! no static exports found */
  5049. /***/ (function(module, exports, __webpack_require__) {
  5050. //
  5051. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  5052. * Use of this file is governed by the BSD 3-clause license that
  5053. * can be found in the LICENSE.txt file in the project root.
  5054. */
  5055. ///
  5056. var DFAState = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
  5057. var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  5058. var getCachedPredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").getCachedPredictionContext;
  5059. function ATNSimulator(atn, sharedContextCache) {
  5060. // The context cache maps all PredictionContext objects that are ==
  5061. // to a single cached copy. This cache is shared across all contexts
  5062. // in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet
  5063. // to use only cached nodes/graphs in addDFAState(). We don't want to
  5064. // fill this during closure() since there are lots of contexts that
  5065. // pop up but are not used ever again. It also greatly slows down closure().
  5066. //
  5067. // <p>This cache makes a huge difference in memory and a little bit in speed.
  5068. // For the Java grammar on java.*, it dropped the memory requirements
  5069. // at the end from 25M to 16M. We don't store any of the full context
  5070. // graphs in the DFA because they are limited to local context only,
  5071. // but apparently there's a lot of repetition there as well. We optimize
  5072. // the config contexts before storing the config set in the DFA states
  5073. // by literally rebuilding them with cached subgraphs only.</p>
  5074. //
  5075. // <p>I tried a cache for use during closure operations, that was
  5076. // whacked after each adaptivePredict(). It cost a little bit
  5077. // more time I think and doesn't save on the overall footprint
  5078. // so it's not worth the complexity.</p>
  5079. ///
  5080. this.atn = atn;
  5081. this.sharedContextCache = sharedContextCache;
  5082. return this;
  5083. }
  5084. // Must distinguish between missing edge and edge we know leads nowhere///
  5085. ATNSimulator.ERROR = new DFAState(0x7FFFFFFF, new ATNConfigSet());
  5086. ATNSimulator.prototype.getCachedContext = function(context) {
  5087. if (this.sharedContextCache ===null) {
  5088. return context;
  5089. }
  5090. var visited = {};
  5091. return getCachedPredictionContext(context, this.sharedContextCache, visited);
  5092. };
  5093. exports.ATNSimulator = ATNSimulator;
  5094. /***/ }),
  5095. /***/ "./node_modules/antlr4/atn/ATNState.js":
  5096. /*!*********************************************!*\
  5097. !*** ./node_modules/antlr4/atn/ATNState.js ***!
  5098. \*********************************************/
  5099. /*! no static exports found */
  5100. /***/ (function(module, exports) {
  5101. //
  5102. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  5103. * Use of this file is governed by the BSD 3-clause license that
  5104. * can be found in the LICENSE.txt file in the project root.
  5105. */
  5106. //
  5107. // The following images show the relation of states and
  5108. // {@link ATNState//transitions} for various grammar constructs.
  5109. //
  5110. // <ul>
  5111. //
  5112. // <li>Solid edges marked with an &//0949; indicate a required
  5113. // {@link EpsilonTransition}.</li>
  5114. //
  5115. // <li>Dashed edges indicate locations where any transition derived from
  5116. // {@link Transition} might appear.</li>
  5117. //
  5118. // <li>Dashed nodes are place holders for either a sequence of linked
  5119. // {@link BasicState} states or the inclusion of a block representing a nested
  5120. // construct in one of the forms below.</li>
  5121. //
  5122. // <li>Nodes showing multiple outgoing alternatives with a {@code ...} support
  5123. // any number of alternatives (one or more). Nodes without the {@code ...} only
  5124. // support the exact number of alternatives shown in the diagram.</li>
  5125. //
  5126. // </ul>
  5127. //
  5128. // <h2>Basic Blocks</h2>
  5129. //
  5130. // <h3>Rule</h3>
  5131. //
  5132. // <embed src="images/Rule.svg" type="image/svg+xml"/>
  5133. //
  5134. // <h3>Block of 1 or more alternatives</h3>
  5135. //
  5136. // <embed src="images/Block.svg" type="image/svg+xml"/>
  5137. //
  5138. // <h2>Greedy Loops</h2>
  5139. //
  5140. // <h3>Greedy Closure: {@code (...)*}</h3>
  5141. //
  5142. // <embed src="images/ClosureGreedy.svg" type="image/svg+xml"/>
  5143. //
  5144. // <h3>Greedy Positive Closure: {@code (...)+}</h3>
  5145. //
  5146. // <embed src="images/PositiveClosureGreedy.svg" type="image/svg+xml"/>
  5147. //
  5148. // <h3>Greedy Optional: {@code (...)?}</h3>
  5149. //
  5150. // <embed src="images/OptionalGreedy.svg" type="image/svg+xml"/>
  5151. //
  5152. // <h2>Non-Greedy Loops</h2>
  5153. //
  5154. // <h3>Non-Greedy Closure: {@code (...)*?}</h3>
  5155. //
  5156. // <embed src="images/ClosureNonGreedy.svg" type="image/svg+xml"/>
  5157. //
  5158. // <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>
  5159. //
  5160. // <embed src="images/PositiveClosureNonGreedy.svg" type="image/svg+xml"/>
  5161. //
  5162. // <h3>Non-Greedy Optional: {@code (...)??}</h3>
  5163. //
  5164. // <embed src="images/OptionalNonGreedy.svg" type="image/svg+xml"/>
  5165. //
  5166. var INITIAL_NUM_TRANSITIONS = 4;
  5167. function ATNState() {
  5168. // Which ATN are we in?
  5169. this.atn = null;
  5170. this.stateNumber = ATNState.INVALID_STATE_NUMBER;
  5171. this.stateType = null;
  5172. this.ruleIndex = 0; // at runtime, we don't have Rule objects
  5173. this.epsilonOnlyTransitions = false;
  5174. // Track the transitions emanating from this ATN state.
  5175. this.transitions = [];
  5176. // Used to cache lookahead during parsing, not used during construction
  5177. this.nextTokenWithinRule = null;
  5178. return this;
  5179. }
  5180. // constants for serialization
  5181. ATNState.INVALID_TYPE = 0;
  5182. ATNState.BASIC = 1;
  5183. ATNState.RULE_START = 2;
  5184. ATNState.BLOCK_START = 3;
  5185. ATNState.PLUS_BLOCK_START = 4;
  5186. ATNState.STAR_BLOCK_START = 5;
  5187. ATNState.TOKEN_START = 6;
  5188. ATNState.RULE_STOP = 7;
  5189. ATNState.BLOCK_END = 8;
  5190. ATNState.STAR_LOOP_BACK = 9;
  5191. ATNState.STAR_LOOP_ENTRY = 10;
  5192. ATNState.PLUS_LOOP_BACK = 11;
  5193. ATNState.LOOP_END = 12;
  5194. ATNState.serializationNames = [
  5195. "INVALID",
  5196. "BASIC",
  5197. "RULE_START",
  5198. "BLOCK_START",
  5199. "PLUS_BLOCK_START",
  5200. "STAR_BLOCK_START",
  5201. "TOKEN_START",
  5202. "RULE_STOP",
  5203. "BLOCK_END",
  5204. "STAR_LOOP_BACK",
  5205. "STAR_LOOP_ENTRY",
  5206. "PLUS_LOOP_BACK",
  5207. "LOOP_END" ];
  5208. ATNState.INVALID_STATE_NUMBER = -1;
  5209. ATNState.prototype.toString = function() {
  5210. return this.stateNumber;
  5211. };
  5212. ATNState.prototype.equals = function(other) {
  5213. if (other instanceof ATNState) {
  5214. return this.stateNumber===other.stateNumber;
  5215. } else {
  5216. return false;
  5217. }
  5218. };
  5219. ATNState.prototype.isNonGreedyExitState = function() {
  5220. return false;
  5221. };
  5222. ATNState.prototype.addTransition = function(trans, index) {
  5223. if(index===undefined) {
  5224. index = -1;
  5225. }
  5226. if (this.transitions.length===0) {
  5227. this.epsilonOnlyTransitions = trans.isEpsilon;
  5228. } else if(this.epsilonOnlyTransitions !== trans.isEpsilon) {
  5229. this.epsilonOnlyTransitions = false;
  5230. }
  5231. if (index===-1) {
  5232. this.transitions.push(trans);
  5233. } else {
  5234. this.transitions.splice(index, 1, trans);
  5235. }
  5236. };
  5237. function BasicState() {
  5238. ATNState.call(this);
  5239. this.stateType = ATNState.BASIC;
  5240. return this;
  5241. }
  5242. BasicState.prototype = Object.create(ATNState.prototype);
  5243. BasicState.prototype.constructor = BasicState;
  5244. function DecisionState() {
  5245. ATNState.call(this);
  5246. this.decision = -1;
  5247. this.nonGreedy = false;
  5248. return this;
  5249. }
  5250. DecisionState.prototype = Object.create(ATNState.prototype);
  5251. DecisionState.prototype.constructor = DecisionState;
  5252. // The start of a regular {@code (...)} block.
  5253. function BlockStartState() {
  5254. DecisionState.call(this);
  5255. this.endState = null;
  5256. return this;
  5257. }
  5258. BlockStartState.prototype = Object.create(DecisionState.prototype);
  5259. BlockStartState.prototype.constructor = BlockStartState;
  5260. function BasicBlockStartState() {
  5261. BlockStartState.call(this);
  5262. this.stateType = ATNState.BLOCK_START;
  5263. return this;
  5264. }
  5265. BasicBlockStartState.prototype = Object.create(BlockStartState.prototype);
  5266. BasicBlockStartState.prototype.constructor = BasicBlockStartState;
  5267. // Terminal node of a simple {@code (a|b|c)} block.
  5268. function BlockEndState() {
  5269. ATNState.call(this);
  5270. this.stateType = ATNState.BLOCK_END;
  5271. this.startState = null;
  5272. return this;
  5273. }
  5274. BlockEndState.prototype = Object.create(ATNState.prototype);
  5275. BlockEndState.prototype.constructor = BlockEndState;
  5276. // The last node in the ATN for a rule, unless that rule is the start symbol.
  5277. // In that case, there is one transition to EOF. Later, we might encode
  5278. // references to all calls to this rule to compute FOLLOW sets for
  5279. // error handling.
  5280. //
  5281. function RuleStopState() {
  5282. ATNState.call(this);
  5283. this.stateType = ATNState.RULE_STOP;
  5284. return this;
  5285. }
  5286. RuleStopState.prototype = Object.create(ATNState.prototype);
  5287. RuleStopState.prototype.constructor = RuleStopState;
  5288. function RuleStartState() {
  5289. ATNState.call(this);
  5290. this.stateType = ATNState.RULE_START;
  5291. this.stopState = null;
  5292. this.isPrecedenceRule = false;
  5293. return this;
  5294. }
  5295. RuleStartState.prototype = Object.create(ATNState.prototype);
  5296. RuleStartState.prototype.constructor = RuleStartState;
  5297. // Decision state for {@code A+} and {@code (A|B)+}. It has two transitions:
  5298. // one to the loop back to start of the block and one to exit.
  5299. //
  5300. function PlusLoopbackState() {
  5301. DecisionState.call(this);
  5302. this.stateType = ATNState.PLUS_LOOP_BACK;
  5303. return this;
  5304. }
  5305. PlusLoopbackState.prototype = Object.create(DecisionState.prototype);
  5306. PlusLoopbackState.prototype.constructor = PlusLoopbackState;
  5307. // Start of {@code (A|B|...)+} loop. Technically a decision state, but
  5308. // we don't use for code generation; somebody might need it, so I'm defining
  5309. // it for completeness. In reality, the {@link PlusLoopbackState} node is the
  5310. // real decision-making note for {@code A+}.
  5311. //
  5312. function PlusBlockStartState() {
  5313. BlockStartState.call(this);
  5314. this.stateType = ATNState.PLUS_BLOCK_START;
  5315. this.loopBackState = null;
  5316. return this;
  5317. }
  5318. PlusBlockStartState.prototype = Object.create(BlockStartState.prototype);
  5319. PlusBlockStartState.prototype.constructor = PlusBlockStartState;
  5320. // The block that begins a closure loop.
  5321. function StarBlockStartState() {
  5322. BlockStartState.call(this);
  5323. this.stateType = ATNState.STAR_BLOCK_START;
  5324. return this;
  5325. }
  5326. StarBlockStartState.prototype = Object.create(BlockStartState.prototype);
  5327. StarBlockStartState.prototype.constructor = StarBlockStartState;
  5328. function StarLoopbackState() {
  5329. ATNState.call(this);
  5330. this.stateType = ATNState.STAR_LOOP_BACK;
  5331. return this;
  5332. }
  5333. StarLoopbackState.prototype = Object.create(ATNState.prototype);
  5334. StarLoopbackState.prototype.constructor = StarLoopbackState;
  5335. function StarLoopEntryState() {
  5336. DecisionState.call(this);
  5337. this.stateType = ATNState.STAR_LOOP_ENTRY;
  5338. this.loopBackState = null;
  5339. // Indicates whether this state can benefit from a precedence DFA during SLL decision making.
  5340. this.isPrecedenceDecision = null;
  5341. return this;
  5342. }
  5343. StarLoopEntryState.prototype = Object.create(DecisionState.prototype);
  5344. StarLoopEntryState.prototype.constructor = StarLoopEntryState;
  5345. // Mark the end of a * or + loop.
  5346. function LoopEndState() {
  5347. ATNState.call(this);
  5348. this.stateType = ATNState.LOOP_END;
  5349. this.loopBackState = null;
  5350. return this;
  5351. }
  5352. LoopEndState.prototype = Object.create(ATNState.prototype);
  5353. LoopEndState.prototype.constructor = LoopEndState;
  5354. // The Tokens rule start state linking to each lexer rule start state */
  5355. function TokensStartState() {
  5356. DecisionState.call(this);
  5357. this.stateType = ATNState.TOKEN_START;
  5358. return this;
  5359. }
  5360. TokensStartState.prototype = Object.create(DecisionState.prototype);
  5361. TokensStartState.prototype.constructor = TokensStartState;
  5362. exports.ATNState = ATNState;
  5363. exports.BasicState = BasicState;
  5364. exports.DecisionState = DecisionState;
  5365. exports.BlockStartState = BlockStartState;
  5366. exports.BlockEndState = BlockEndState;
  5367. exports.LoopEndState = LoopEndState;
  5368. exports.RuleStartState = RuleStartState;
  5369. exports.RuleStopState = RuleStopState;
  5370. exports.TokensStartState = TokensStartState;
  5371. exports.PlusLoopbackState = PlusLoopbackState;
  5372. exports.StarLoopbackState = StarLoopbackState;
  5373. exports.StarLoopEntryState = StarLoopEntryState;
  5374. exports.PlusBlockStartState = PlusBlockStartState;
  5375. exports.StarBlockStartState = StarBlockStartState;
  5376. exports.BasicBlockStartState = BasicBlockStartState;
  5377. /***/ }),
  5378. /***/ "./node_modules/antlr4/atn/ATNType.js":
  5379. /*!********************************************!*\
  5380. !*** ./node_modules/antlr4/atn/ATNType.js ***!
  5381. \********************************************/
  5382. /*! no static exports found */
  5383. /***/ (function(module, exports) {
  5384. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  5385. * Use of this file is governed by the BSD 3-clause license that
  5386. * can be found in the LICENSE.txt file in the project root.
  5387. */
  5388. ///
  5389. // Represents the type of recognizer an ATN applies to.
  5390. function ATNType() {
  5391. }
  5392. ATNType.LEXER = 0;
  5393. ATNType.PARSER = 1;
  5394. exports.ATNType = ATNType;
  5395. /***/ }),
  5396. /***/ "./node_modules/antlr4/atn/LexerATNSimulator.js":
  5397. /*!******************************************************!*\
  5398. !*** ./node_modules/antlr4/atn/LexerATNSimulator.js ***!
  5399. \******************************************************/
  5400. /*! no static exports found */
  5401. /***/ (function(module, exports, __webpack_require__) {
  5402. //
  5403. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  5404. * Use of this file is governed by the BSD 3-clause license that
  5405. * can be found in the LICENSE.txt file in the project root.
  5406. */
  5407. ///
  5408. // When we hit an accept state in either the DFA or the ATN, we
  5409. // have to notify the character stream to start buffering characters
  5410. // via {@link IntStream//mark} and record the current state. The current sim state
  5411. // includes the current index into the input, the current line,
  5412. // and current character position in that line. Note that the Lexer is
  5413. // tracking the starting line and characterization of the token. These
  5414. // variables track the "state" of the simulator when it hits an accept state.
  5415. //
  5416. // <p>We track these variables separately for the DFA and ATN simulation
  5417. // because the DFA simulation often has to fail over to the ATN
  5418. // simulation. If the ATN simulation fails, we need the DFA to fall
  5419. // back to its previously accepted state, if any. If the ATN succeeds,
  5420. // then the ATN does the accept and the DFA simulator that invoked it
  5421. // can simply return the predicted token type.</p>
  5422. ///
  5423. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  5424. var Lexer = __webpack_require__(/*! ./../Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
  5425. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  5426. var ATNSimulator = __webpack_require__(/*! ./ATNSimulator */ "./node_modules/antlr4/atn/ATNSimulator.js").ATNSimulator;
  5427. var DFAState = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
  5428. var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  5429. var OrderedATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").OrderedATNConfigSet;
  5430. var PredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").PredictionContext;
  5431. var SingletonPredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").SingletonPredictionContext;
  5432. var RuleStopState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
  5433. var LexerATNConfig = __webpack_require__(/*! ./ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").LexerATNConfig;
  5434. var Transition = __webpack_require__(/*! ./Transition */ "./node_modules/antlr4/atn/Transition.js").Transition;
  5435. var LexerActionExecutor = __webpack_require__(/*! ./LexerActionExecutor */ "./node_modules/antlr4/atn/LexerActionExecutor.js").LexerActionExecutor;
  5436. var LexerNoViableAltException = __webpack_require__(/*! ./../error/Errors */ "./node_modules/antlr4/error/Errors.js").LexerNoViableAltException;
  5437. function resetSimState(sim) {
  5438. sim.index = -1;
  5439. sim.line = 0;
  5440. sim.column = -1;
  5441. sim.dfaState = null;
  5442. }
  5443. function SimState() {
  5444. resetSimState(this);
  5445. return this;
  5446. }
  5447. SimState.prototype.reset = function() {
  5448. resetSimState(this);
  5449. };
  5450. function LexerATNSimulator(recog, atn, decisionToDFA, sharedContextCache) {
  5451. ATNSimulator.call(this, atn, sharedContextCache);
  5452. this.decisionToDFA = decisionToDFA;
  5453. this.recog = recog;
  5454. // The current token's starting index into the character stream.
  5455. // Shared across DFA to ATN simulation in case the ATN fails and the
  5456. // DFA did not have a previous accept state. In this case, we use the
  5457. // ATN-generated exception object.
  5458. this.startIndex = -1;
  5459. // line number 1..n within the input///
  5460. this.line = 1;
  5461. // The index of the character relative to the beginning of the line
  5462. // 0..n-1///
  5463. this.column = 0;
  5464. this.mode = Lexer.DEFAULT_MODE;
  5465. // Used during DFA/ATN exec to record the most recent accept configuration
  5466. // info
  5467. this.prevAccept = new SimState();
  5468. // done
  5469. return this;
  5470. }
  5471. LexerATNSimulator.prototype = Object.create(ATNSimulator.prototype);
  5472. LexerATNSimulator.prototype.constructor = LexerATNSimulator;
  5473. LexerATNSimulator.debug = false;
  5474. LexerATNSimulator.dfa_debug = false;
  5475. LexerATNSimulator.MIN_DFA_EDGE = 0;
  5476. LexerATNSimulator.MAX_DFA_EDGE = 127; // forces unicode to stay in ATN
  5477. LexerATNSimulator.match_calls = 0;
  5478. LexerATNSimulator.prototype.copyState = function(simulator) {
  5479. this.column = simulator.column;
  5480. this.line = simulator.line;
  5481. this.mode = simulator.mode;
  5482. this.startIndex = simulator.startIndex;
  5483. };
  5484. LexerATNSimulator.prototype.match = function(input, mode) {
  5485. this.match_calls += 1;
  5486. this.mode = mode;
  5487. var mark = input.mark();
  5488. try {
  5489. this.startIndex = input.index;
  5490. this.prevAccept.reset();
  5491. var dfa = this.decisionToDFA[mode];
  5492. if (dfa.s0 === null) {
  5493. return this.matchATN(input);
  5494. } else {
  5495. return this.execATN(input, dfa.s0);
  5496. }
  5497. } finally {
  5498. input.release(mark);
  5499. }
  5500. };
  5501. LexerATNSimulator.prototype.reset = function() {
  5502. this.prevAccept.reset();
  5503. this.startIndex = -1;
  5504. this.line = 1;
  5505. this.column = 0;
  5506. this.mode = Lexer.DEFAULT_MODE;
  5507. };
  5508. LexerATNSimulator.prototype.matchATN = function(input) {
  5509. var startState = this.atn.modeToStartState[this.mode];
  5510. if (LexerATNSimulator.debug) {
  5511. console.log("matchATN mode " + this.mode + " start: " + startState);
  5512. }
  5513. var old_mode = this.mode;
  5514. var s0_closure = this.computeStartState(input, startState);
  5515. var suppressEdge = s0_closure.hasSemanticContext;
  5516. s0_closure.hasSemanticContext = false;
  5517. var next = this.addDFAState(s0_closure);
  5518. if (!suppressEdge) {
  5519. this.decisionToDFA[this.mode].s0 = next;
  5520. }
  5521. var predict = this.execATN(input, next);
  5522. if (LexerATNSimulator.debug) {
  5523. console.log("DFA after matchATN: " + this.decisionToDFA[old_mode].toLexerString());
  5524. }
  5525. return predict;
  5526. };
  5527. LexerATNSimulator.prototype.execATN = function(input, ds0) {
  5528. if (LexerATNSimulator.debug) {
  5529. console.log("start state closure=" + ds0.configs);
  5530. }
  5531. if (ds0.isAcceptState) {
  5532. // allow zero-length tokens
  5533. this.captureSimState(this.prevAccept, input, ds0);
  5534. }
  5535. var t = input.LA(1);
  5536. var s = ds0; // s is current/from DFA state
  5537. while (true) { // while more work
  5538. if (LexerATNSimulator.debug) {
  5539. console.log("execATN loop starting closure: " + s.configs);
  5540. }
  5541. // As we move src->trg, src->trg, we keep track of the previous trg to
  5542. // avoid looking up the DFA state again, which is expensive.
  5543. // If the previous target was already part of the DFA, we might
  5544. // be able to avoid doing a reach operation upon t. If s!=null,
  5545. // it means that semantic predicates didn't prevent us from
  5546. // creating a DFA state. Once we know s!=null, we check to see if
  5547. // the DFA state has an edge already for t. If so, we can just reuse
  5548. // it's configuration set; there's no point in re-computing it.
  5549. // This is kind of like doing DFA simulation within the ATN
  5550. // simulation because DFA simulation is really just a way to avoid
  5551. // computing reach/closure sets. Technically, once we know that
  5552. // we have a previously added DFA state, we could jump over to
  5553. // the DFA simulator. But, that would mean popping back and forth
  5554. // a lot and making things more complicated algorithmically.
  5555. // This optimization makes a lot of sense for loops within DFA.
  5556. // A character will take us back to an existing DFA state
  5557. // that already has lots of edges out of it. e.g., .* in comments.
  5558. // print("Target for:" + str(s) + " and:" + str(t))
  5559. var target = this.getExistingTargetState(s, t);
  5560. // print("Existing:" + str(target))
  5561. if (target === null) {
  5562. target = this.computeTargetState(input, s, t);
  5563. // print("Computed:" + str(target))
  5564. }
  5565. if (target === ATNSimulator.ERROR) {
  5566. break;
  5567. }
  5568. // If this is a consumable input element, make sure to consume before
  5569. // capturing the accept state so the input index, line, and char
  5570. // position accurately reflect the state of the interpreter at the
  5571. // end of the token.
  5572. if (t !== Token.EOF) {
  5573. this.consume(input);
  5574. }
  5575. if (target.isAcceptState) {
  5576. this.captureSimState(this.prevAccept, input, target);
  5577. if (t === Token.EOF) {
  5578. break;
  5579. }
  5580. }
  5581. t = input.LA(1);
  5582. s = target; // flip; current DFA target becomes new src/from state
  5583. }
  5584. return this.failOrAccept(this.prevAccept, input, s.configs, t);
  5585. };
  5586. // Get an existing target state for an edge in the DFA. If the target state
  5587. // for the edge has not yet been computed or is otherwise not available,
  5588. // this method returns {@code null}.
  5589. //
  5590. // @param s The current DFA state
  5591. // @param t The next input symbol
  5592. // @return The existing target DFA state for the given input symbol
  5593. // {@code t}, or {@code null} if the target state for this edge is not
  5594. // already cached
  5595. LexerATNSimulator.prototype.getExistingTargetState = function(s, t) {
  5596. if (s.edges === null || t < LexerATNSimulator.MIN_DFA_EDGE || t > LexerATNSimulator.MAX_DFA_EDGE) {
  5597. return null;
  5598. }
  5599. var target = s.edges[t - LexerATNSimulator.MIN_DFA_EDGE];
  5600. if(target===undefined) {
  5601. target = null;
  5602. }
  5603. if (LexerATNSimulator.debug && target !== null) {
  5604. console.log("reuse state " + s.stateNumber + " edge to " + target.stateNumber);
  5605. }
  5606. return target;
  5607. };
  5608. // Compute a target state for an edge in the DFA, and attempt to add the
  5609. // computed state and corresponding edge to the DFA.
  5610. //
  5611. // @param input The input stream
  5612. // @param s The current DFA state
  5613. // @param t The next input symbol
  5614. //
  5615. // @return The computed target DFA state for the given input symbol
  5616. // {@code t}. If {@code t} does not lead to a valid DFA state, this method
  5617. // returns {@link //ERROR}.
  5618. LexerATNSimulator.prototype.computeTargetState = function(input, s, t) {
  5619. var reach = new OrderedATNConfigSet();
  5620. // if we don't find an existing DFA state
  5621. // Fill reach starting from closure, following t transitions
  5622. this.getReachableConfigSet(input, s.configs, reach, t);
  5623. if (reach.items.length === 0) { // we got nowhere on t from s
  5624. if (!reach.hasSemanticContext) {
  5625. // we got nowhere on t, don't throw out this knowledge; it'd
  5626. // cause a failover from DFA later.
  5627. this.addDFAEdge(s, t, ATNSimulator.ERROR);
  5628. }
  5629. // stop when we can't match any more char
  5630. return ATNSimulator.ERROR;
  5631. }
  5632. // Add an edge from s to target DFA found/created for reach
  5633. return this.addDFAEdge(s, t, null, reach);
  5634. };
  5635. LexerATNSimulator.prototype.failOrAccept = function(prevAccept, input, reach, t) {
  5636. if (this.prevAccept.dfaState !== null) {
  5637. var lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor;
  5638. this.accept(input, lexerActionExecutor, this.startIndex,
  5639. prevAccept.index, prevAccept.line, prevAccept.column);
  5640. return prevAccept.dfaState.prediction;
  5641. } else {
  5642. // if no accept and EOF is first char, return EOF
  5643. if (t === Token.EOF && input.index === this.startIndex) {
  5644. return Token.EOF;
  5645. }
  5646. throw new LexerNoViableAltException(this.recog, input, this.startIndex, reach);
  5647. }
  5648. };
  5649. // Given a starting configuration set, figure out all ATN configurations
  5650. // we can reach upon input {@code t}. Parameter {@code reach} is a return
  5651. // parameter.
  5652. LexerATNSimulator.prototype.getReachableConfigSet = function(input, closure,
  5653. reach, t) {
  5654. // this is used to skip processing for configs which have a lower priority
  5655. // than a config that already reached an accept state for the same rule
  5656. var skipAlt = ATN.INVALID_ALT_NUMBER;
  5657. for (var i = 0; i < closure.items.length; i++) {
  5658. var cfg = closure.items[i];
  5659. var currentAltReachedAcceptState = (cfg.alt === skipAlt);
  5660. if (currentAltReachedAcceptState && cfg.passedThroughNonGreedyDecision) {
  5661. continue;
  5662. }
  5663. if (LexerATNSimulator.debug) {
  5664. console.log("testing %s at %s\n", this.getTokenName(t), cfg
  5665. .toString(this.recog, true));
  5666. }
  5667. for (var j = 0; j < cfg.state.transitions.length; j++) {
  5668. var trans = cfg.state.transitions[j]; // for each transition
  5669. var target = this.getReachableTarget(trans, t);
  5670. if (target !== null) {
  5671. var lexerActionExecutor = cfg.lexerActionExecutor;
  5672. if (lexerActionExecutor !== null) {
  5673. lexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.index - this.startIndex);
  5674. }
  5675. var treatEofAsEpsilon = (t === Token.EOF);
  5676. var config = new LexerATNConfig({state:target, lexerActionExecutor:lexerActionExecutor}, cfg);
  5677. if (this.closure(input, config, reach,
  5678. currentAltReachedAcceptState, true, treatEofAsEpsilon)) {
  5679. // any remaining configs for this alt have a lower priority
  5680. // than the one that just reached an accept state.
  5681. skipAlt = cfg.alt;
  5682. }
  5683. }
  5684. }
  5685. }
  5686. };
  5687. LexerATNSimulator.prototype.accept = function(input, lexerActionExecutor,
  5688. startIndex, index, line, charPos) {
  5689. if (LexerATNSimulator.debug) {
  5690. console.log("ACTION %s\n", lexerActionExecutor);
  5691. }
  5692. // seek to after last char in token
  5693. input.seek(index);
  5694. this.line = line;
  5695. this.column = charPos;
  5696. if (lexerActionExecutor !== null && this.recog !== null) {
  5697. lexerActionExecutor.execute(this.recog, input, startIndex);
  5698. }
  5699. };
  5700. LexerATNSimulator.prototype.getReachableTarget = function(trans, t) {
  5701. if (trans.matches(t, 0, Lexer.MAX_CHAR_VALUE)) {
  5702. return trans.target;
  5703. } else {
  5704. return null;
  5705. }
  5706. };
  5707. LexerATNSimulator.prototype.computeStartState = function(input, p) {
  5708. var initialContext = PredictionContext.EMPTY;
  5709. var configs = new OrderedATNConfigSet();
  5710. for (var i = 0; i < p.transitions.length; i++) {
  5711. var target = p.transitions[i].target;
  5712. var cfg = new LexerATNConfig({state:target, alt:i+1, context:initialContext}, null);
  5713. this.closure(input, cfg, configs, false, false, false);
  5714. }
  5715. return configs;
  5716. };
  5717. // Since the alternatives within any lexer decision are ordered by
  5718. // preference, this method stops pursuing the closure as soon as an accept
  5719. // state is reached. After the first accept state is reached by depth-first
  5720. // search from {@code config}, all other (potentially reachable) states for
  5721. // this rule would have a lower priority.
  5722. //
  5723. // @return {@code true} if an accept state is reached, otherwise
  5724. // {@code false}.
  5725. LexerATNSimulator.prototype.closure = function(input, config, configs,
  5726. currentAltReachedAcceptState, speculative, treatEofAsEpsilon) {
  5727. var cfg = null;
  5728. if (LexerATNSimulator.debug) {
  5729. console.log("closure(" + config.toString(this.recog, true) + ")");
  5730. }
  5731. if (config.state instanceof RuleStopState) {
  5732. if (LexerATNSimulator.debug) {
  5733. if (this.recog !== null) {
  5734. console.log("closure at %s rule stop %s\n", this.recog.ruleNames[config.state.ruleIndex], config);
  5735. } else {
  5736. console.log("closure at rule stop %s\n", config);
  5737. }
  5738. }
  5739. if (config.context === null || config.context.hasEmptyPath()) {
  5740. if (config.context === null || config.context.isEmpty()) {
  5741. configs.add(config);
  5742. return true;
  5743. } else {
  5744. configs.add(new LexerATNConfig({ state:config.state, context:PredictionContext.EMPTY}, config));
  5745. currentAltReachedAcceptState = true;
  5746. }
  5747. }
  5748. if (config.context !== null && !config.context.isEmpty()) {
  5749. for (var i = 0; i < config.context.length; i++) {
  5750. if (config.context.getReturnState(i) !== PredictionContext.EMPTY_RETURN_STATE) {
  5751. var newContext = config.context.getParent(i); // "pop" return state
  5752. var returnState = this.atn.states[config.context.getReturnState(i)];
  5753. cfg = new LexerATNConfig({ state:returnState, context:newContext }, config);
  5754. currentAltReachedAcceptState = this.closure(input, cfg,
  5755. configs, currentAltReachedAcceptState, speculative,
  5756. treatEofAsEpsilon);
  5757. }
  5758. }
  5759. }
  5760. return currentAltReachedAcceptState;
  5761. }
  5762. // optimization
  5763. if (!config.state.epsilonOnlyTransitions) {
  5764. if (!currentAltReachedAcceptState || !config.passedThroughNonGreedyDecision) {
  5765. configs.add(config);
  5766. }
  5767. }
  5768. for (var j = 0; j < config.state.transitions.length; j++) {
  5769. var trans = config.state.transitions[j];
  5770. cfg = this.getEpsilonTarget(input, config, trans, configs, speculative, treatEofAsEpsilon);
  5771. if (cfg !== null) {
  5772. currentAltReachedAcceptState = this.closure(input, cfg, configs,
  5773. currentAltReachedAcceptState, speculative, treatEofAsEpsilon);
  5774. }
  5775. }
  5776. return currentAltReachedAcceptState;
  5777. };
  5778. // side-effect: can alter configs.hasSemanticContext
  5779. LexerATNSimulator.prototype.getEpsilonTarget = function(input, config, trans,
  5780. configs, speculative, treatEofAsEpsilon) {
  5781. var cfg = null;
  5782. if (trans.serializationType === Transition.RULE) {
  5783. var newContext = SingletonPredictionContext.create(config.context, trans.followState.stateNumber);
  5784. cfg = new LexerATNConfig( { state:trans.target, context:newContext}, config);
  5785. } else if (trans.serializationType === Transition.PRECEDENCE) {
  5786. throw "Precedence predicates are not supported in lexers.";
  5787. } else if (trans.serializationType === Transition.PREDICATE) {
  5788. // Track traversing semantic predicates. If we traverse,
  5789. // we cannot add a DFA state for this "reach" computation
  5790. // because the DFA would not test the predicate again in the
  5791. // future. Rather than creating collections of semantic predicates
  5792. // like v3 and testing them on prediction, v4 will test them on the
  5793. // fly all the time using the ATN not the DFA. This is slower but
  5794. // semantically it's not used that often. One of the key elements to
  5795. // this predicate mechanism is not adding DFA states that see
  5796. // predicates immediately afterwards in the ATN. For example,
  5797. // a : ID {p1}? | ID {p2}? ;
  5798. // should create the start state for rule 'a' (to save start state
  5799. // competition), but should not create target of ID state. The
  5800. // collection of ATN states the following ID references includes
  5801. // states reached by traversing predicates. Since this is when we
  5802. // test them, we cannot cash the DFA state target of ID.
  5803. if (LexerATNSimulator.debug) {
  5804. console.log("EVAL rule " + trans.ruleIndex + ":" + trans.predIndex);
  5805. }
  5806. configs.hasSemanticContext = true;
  5807. if (this.evaluatePredicate(input, trans.ruleIndex, trans.predIndex, speculative)) {
  5808. cfg = new LexerATNConfig({ state:trans.target}, config);
  5809. }
  5810. } else if (trans.serializationType === Transition.ACTION) {
  5811. if (config.context === null || config.context.hasEmptyPath()) {
  5812. // execute actions anywhere in the start rule for a token.
  5813. //
  5814. // TODO: if the entry rule is invoked recursively, some
  5815. // actions may be executed during the recursive call. The
  5816. // problem can appear when hasEmptyPath() is true but
  5817. // isEmpty() is false. In this case, the config needs to be
  5818. // split into two contexts - one with just the empty path
  5819. // and another with everything but the empty path.
  5820. // Unfortunately, the current algorithm does not allow
  5821. // getEpsilonTarget to return two configurations, so
  5822. // additional modifications are needed before we can support
  5823. // the split operation.
  5824. var lexerActionExecutor = LexerActionExecutor.append(config.lexerActionExecutor,
  5825. this.atn.lexerActions[trans.actionIndex]);
  5826. cfg = new LexerATNConfig({ state:trans.target, lexerActionExecutor:lexerActionExecutor }, config);
  5827. } else {
  5828. // ignore actions in referenced rules
  5829. cfg = new LexerATNConfig( { state:trans.target}, config);
  5830. }
  5831. } else if (trans.serializationType === Transition.EPSILON) {
  5832. cfg = new LexerATNConfig({ state:trans.target}, config);
  5833. } else if (trans.serializationType === Transition.ATOM ||
  5834. trans.serializationType === Transition.RANGE ||
  5835. trans.serializationType === Transition.SET) {
  5836. if (treatEofAsEpsilon) {
  5837. if (trans.matches(Token.EOF, 0, Lexer.MAX_CHAR_VALUE)) {
  5838. cfg = new LexerATNConfig( { state:trans.target }, config);
  5839. }
  5840. }
  5841. }
  5842. return cfg;
  5843. };
  5844. // Evaluate a predicate specified in the lexer.
  5845. //
  5846. // <p>If {@code speculative} is {@code true}, this method was called before
  5847. // {@link //consume} for the matched character. This method should call
  5848. // {@link //consume} before evaluating the predicate to ensure position
  5849. // sensitive values, including {@link Lexer//getText}, {@link Lexer//getLine},
  5850. // and {@link Lexer//getcolumn}, properly reflect the current
  5851. // lexer state. This method should restore {@code input} and the simulator
  5852. // to the original state before returning (i.e. undo the actions made by the
  5853. // call to {@link //consume}.</p>
  5854. //
  5855. // @param input The input stream.
  5856. // @param ruleIndex The rule containing the predicate.
  5857. // @param predIndex The index of the predicate within the rule.
  5858. // @param speculative {@code true} if the current index in {@code input} is
  5859. // one character before the predicate's location.
  5860. //
  5861. // @return {@code true} if the specified predicate evaluates to
  5862. // {@code true}.
  5863. // /
  5864. LexerATNSimulator.prototype.evaluatePredicate = function(input, ruleIndex,
  5865. predIndex, speculative) {
  5866. // assume true if no recognizer was provided
  5867. if (this.recog === null) {
  5868. return true;
  5869. }
  5870. if (!speculative) {
  5871. return this.recog.sempred(null, ruleIndex, predIndex);
  5872. }
  5873. var savedcolumn = this.column;
  5874. var savedLine = this.line;
  5875. var index = input.index;
  5876. var marker = input.mark();
  5877. try {
  5878. this.consume(input);
  5879. return this.recog.sempred(null, ruleIndex, predIndex);
  5880. } finally {
  5881. this.column = savedcolumn;
  5882. this.line = savedLine;
  5883. input.seek(index);
  5884. input.release(marker);
  5885. }
  5886. };
  5887. LexerATNSimulator.prototype.captureSimState = function(settings, input, dfaState) {
  5888. settings.index = input.index;
  5889. settings.line = this.line;
  5890. settings.column = this.column;
  5891. settings.dfaState = dfaState;
  5892. };
  5893. LexerATNSimulator.prototype.addDFAEdge = function(from_, tk, to, cfgs) {
  5894. if (to === undefined) {
  5895. to = null;
  5896. }
  5897. if (cfgs === undefined) {
  5898. cfgs = null;
  5899. }
  5900. if (to === null && cfgs !== null) {
  5901. // leading to this call, ATNConfigSet.hasSemanticContext is used as a
  5902. // marker indicating dynamic predicate evaluation makes this edge
  5903. // dependent on the specific input sequence, so the static edge in the
  5904. // DFA should be omitted. The target DFAState is still created since
  5905. // execATN has the ability to resynchronize with the DFA state cache
  5906. // following the predicate evaluation step.
  5907. //
  5908. // TJP notes: next time through the DFA, we see a pred again and eval.
  5909. // If that gets us to a previously created (but dangling) DFA
  5910. // state, we can continue in pure DFA mode from there.
  5911. // /
  5912. var suppressEdge = cfgs.hasSemanticContext;
  5913. cfgs.hasSemanticContext = false;
  5914. to = this.addDFAState(cfgs);
  5915. if (suppressEdge) {
  5916. return to;
  5917. }
  5918. }
  5919. // add the edge
  5920. if (tk < LexerATNSimulator.MIN_DFA_EDGE || tk > LexerATNSimulator.MAX_DFA_EDGE) {
  5921. // Only track edges within the DFA bounds
  5922. return to;
  5923. }
  5924. if (LexerATNSimulator.debug) {
  5925. console.log("EDGE " + from_ + " -> " + to + " upon " + tk);
  5926. }
  5927. if (from_.edges === null) {
  5928. // make room for tokens 1..n and -1 masquerading as index 0
  5929. from_.edges = [];
  5930. }
  5931. from_.edges[tk - LexerATNSimulator.MIN_DFA_EDGE] = to; // connect
  5932. return to;
  5933. };
  5934. // Add a new DFA state if there isn't one with this set of
  5935. // configurations already. This method also detects the first
  5936. // configuration containing an ATN rule stop state. Later, when
  5937. // traversing the DFA, we will know which rule to accept.
  5938. LexerATNSimulator.prototype.addDFAState = function(configs) {
  5939. var proposed = new DFAState(null, configs);
  5940. var firstConfigWithRuleStopState = null;
  5941. for (var i = 0; i < configs.items.length; i++) {
  5942. var cfg = configs.items[i];
  5943. if (cfg.state instanceof RuleStopState) {
  5944. firstConfigWithRuleStopState = cfg;
  5945. break;
  5946. }
  5947. }
  5948. if (firstConfigWithRuleStopState !== null) {
  5949. proposed.isAcceptState = true;
  5950. proposed.lexerActionExecutor = firstConfigWithRuleStopState.lexerActionExecutor;
  5951. proposed.prediction = this.atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex];
  5952. }
  5953. var dfa = this.decisionToDFA[this.mode];
  5954. var existing = dfa.states.get(proposed);
  5955. if (existing!==null) {
  5956. return existing;
  5957. }
  5958. var newState = proposed;
  5959. newState.stateNumber = dfa.states.length;
  5960. configs.setReadonly(true);
  5961. newState.configs = configs;
  5962. dfa.states.add(newState);
  5963. return newState;
  5964. };
  5965. LexerATNSimulator.prototype.getDFA = function(mode) {
  5966. return this.decisionToDFA[mode];
  5967. };
  5968. // Get the text matched so far for the current token.
  5969. LexerATNSimulator.prototype.getText = function(input) {
  5970. // index is first lookahead char, don't include.
  5971. return input.getText(this.startIndex, input.index - 1);
  5972. };
  5973. LexerATNSimulator.prototype.consume = function(input) {
  5974. var curChar = input.LA(1);
  5975. if (curChar === "\n".charCodeAt(0)) {
  5976. this.line += 1;
  5977. this.column = 0;
  5978. } else {
  5979. this.column += 1;
  5980. }
  5981. input.consume();
  5982. };
  5983. LexerATNSimulator.prototype.getTokenName = function(tt) {
  5984. if (tt === -1) {
  5985. return "EOF";
  5986. } else {
  5987. return "'" + String.fromCharCode(tt) + "'";
  5988. }
  5989. };
  5990. exports.LexerATNSimulator = LexerATNSimulator;
  5991. /***/ }),
  5992. /***/ "./node_modules/antlr4/atn/LexerAction.js":
  5993. /*!************************************************!*\
  5994. !*** ./node_modules/antlr4/atn/LexerAction.js ***!
  5995. \************************************************/
  5996. /*! no static exports found */
  5997. /***/ (function(module, exports) {
  5998. //
  5999. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  6000. * Use of this file is governed by the BSD 3-clause license that
  6001. * can be found in the LICENSE.txt file in the project root.
  6002. */
  6003. //
  6004. function LexerActionType() {
  6005. }
  6006. LexerActionType.CHANNEL = 0; //The type of a {@link LexerChannelAction} action.
  6007. LexerActionType.CUSTOM = 1; //The type of a {@link LexerCustomAction} action.
  6008. LexerActionType.MODE = 2; //The type of a {@link LexerModeAction} action.
  6009. LexerActionType.MORE = 3; //The type of a {@link LexerMoreAction} action.
  6010. LexerActionType.POP_MODE = 4; //The type of a {@link LexerPopModeAction} action.
  6011. LexerActionType.PUSH_MODE = 5; //The type of a {@link LexerPushModeAction} action.
  6012. LexerActionType.SKIP = 6; //The type of a {@link LexerSkipAction} action.
  6013. LexerActionType.TYPE = 7; //The type of a {@link LexerTypeAction} action.
  6014. function LexerAction(action) {
  6015. this.actionType = action;
  6016. this.isPositionDependent = false;
  6017. return this;
  6018. }
  6019. LexerAction.prototype.hashCode = function() {
  6020. var hash = new Hash();
  6021. this.updateHashCode(hash);
  6022. return hash.finish()
  6023. };
  6024. LexerAction.prototype.updateHashCode = function(hash) {
  6025. hash.update(this.actionType);
  6026. };
  6027. LexerAction.prototype.equals = function(other) {
  6028. return this === other;
  6029. };
  6030. //
  6031. // Implements the {@code skip} lexer action by calling {@link Lexer//skip}.
  6032. //
  6033. // <p>The {@code skip} command does not have any parameters, so this action is
  6034. // implemented as a singleton instance exposed by {@link //INSTANCE}.</p>
  6035. function LexerSkipAction() {
  6036. LexerAction.call(this, LexerActionType.SKIP);
  6037. return this;
  6038. }
  6039. LexerSkipAction.prototype = Object.create(LexerAction.prototype);
  6040. LexerSkipAction.prototype.constructor = LexerSkipAction;
  6041. // Provides a singleton instance of this parameterless lexer action.
  6042. LexerSkipAction.INSTANCE = new LexerSkipAction();
  6043. LexerSkipAction.prototype.execute = function(lexer) {
  6044. lexer.skip();
  6045. };
  6046. LexerSkipAction.prototype.toString = function() {
  6047. return "skip";
  6048. };
  6049. // Implements the {@code type} lexer action by calling {@link Lexer//setType}
  6050. // with the assigned type.
  6051. function LexerTypeAction(type) {
  6052. LexerAction.call(this, LexerActionType.TYPE);
  6053. this.type = type;
  6054. return this;
  6055. }
  6056. LexerTypeAction.prototype = Object.create(LexerAction.prototype);
  6057. LexerTypeAction.prototype.constructor = LexerTypeAction;
  6058. LexerTypeAction.prototype.execute = function(lexer) {
  6059. lexer.type = this.type;
  6060. };
  6061. LexerTypeAction.prototype.updateHashCode = function(hash) {
  6062. hash.update(this.actionType, this.type);
  6063. };
  6064. LexerTypeAction.prototype.equals = function(other) {
  6065. if(this === other) {
  6066. return true;
  6067. } else if (! (other instanceof LexerTypeAction)) {
  6068. return false;
  6069. } else {
  6070. return this.type === other.type;
  6071. }
  6072. };
  6073. LexerTypeAction.prototype.toString = function() {
  6074. return "type(" + this.type + ")";
  6075. };
  6076. // Implements the {@code pushMode} lexer action by calling
  6077. // {@link Lexer//pushMode} with the assigned mode.
  6078. function LexerPushModeAction(mode) {
  6079. LexerAction.call(this, LexerActionType.PUSH_MODE);
  6080. this.mode = mode;
  6081. return this;
  6082. }
  6083. LexerPushModeAction.prototype = Object.create(LexerAction.prototype);
  6084. LexerPushModeAction.prototype.constructor = LexerPushModeAction;
  6085. // <p>This action is implemented by calling {@link Lexer//pushMode} with the
  6086. // value provided by {@link //getMode}.</p>
  6087. LexerPushModeAction.prototype.execute = function(lexer) {
  6088. lexer.pushMode(this.mode);
  6089. };
  6090. LexerPushModeAction.prototype.updateHashCode = function(hash) {
  6091. hash.update(this.actionType, this.mode);
  6092. };
  6093. LexerPushModeAction.prototype.equals = function(other) {
  6094. if (this === other) {
  6095. return true;
  6096. } else if (! (other instanceof LexerPushModeAction)) {
  6097. return false;
  6098. } else {
  6099. return this.mode === other.mode;
  6100. }
  6101. };
  6102. LexerPushModeAction.prototype.toString = function() {
  6103. return "pushMode(" + this.mode + ")";
  6104. };
  6105. // Implements the {@code popMode} lexer action by calling {@link Lexer//popMode}.
  6106. //
  6107. // <p>The {@code popMode} command does not have any parameters, so this action is
  6108. // implemented as a singleton instance exposed by {@link //INSTANCE}.</p>
  6109. function LexerPopModeAction() {
  6110. LexerAction.call(this,LexerActionType.POP_MODE);
  6111. return this;
  6112. }
  6113. LexerPopModeAction.prototype = Object.create(LexerAction.prototype);
  6114. LexerPopModeAction.prototype.constructor = LexerPopModeAction;
  6115. LexerPopModeAction.INSTANCE = new LexerPopModeAction();
  6116. // <p>This action is implemented by calling {@link Lexer//popMode}.</p>
  6117. LexerPopModeAction.prototype.execute = function(lexer) {
  6118. lexer.popMode();
  6119. };
  6120. LexerPopModeAction.prototype.toString = function() {
  6121. return "popMode";
  6122. };
  6123. // Implements the {@code more} lexer action by calling {@link Lexer//more}.
  6124. //
  6125. // <p>The {@code more} command does not have any parameters, so this action is
  6126. // implemented as a singleton instance exposed by {@link //INSTANCE}.</p>
  6127. function LexerMoreAction() {
  6128. LexerAction.call(this, LexerActionType.MORE);
  6129. return this;
  6130. }
  6131. LexerMoreAction.prototype = Object.create(LexerAction.prototype);
  6132. LexerMoreAction.prototype.constructor = LexerMoreAction;
  6133. LexerMoreAction.INSTANCE = new LexerMoreAction();
  6134. // <p>This action is implemented by calling {@link Lexer//popMode}.</p>
  6135. LexerMoreAction.prototype.execute = function(lexer) {
  6136. lexer.more();
  6137. };
  6138. LexerMoreAction.prototype.toString = function() {
  6139. return "more";
  6140. };
  6141. // Implements the {@code mode} lexer action by calling {@link Lexer//mode} with
  6142. // the assigned mode.
  6143. function LexerModeAction(mode) {
  6144. LexerAction.call(this, LexerActionType.MODE);
  6145. this.mode = mode;
  6146. return this;
  6147. }
  6148. LexerModeAction.prototype = Object.create(LexerAction.prototype);
  6149. LexerModeAction.prototype.constructor = LexerModeAction;
  6150. // <p>This action is implemented by calling {@link Lexer//mode} with the
  6151. // value provided by {@link //getMode}.</p>
  6152. LexerModeAction.prototype.execute = function(lexer) {
  6153. lexer.mode(this.mode);
  6154. };
  6155. LexerModeAction.prototype.updateHashCode = function(hash) {
  6156. hash.update(this.actionType, this.mode);
  6157. };
  6158. LexerModeAction.prototype.equals = function(other) {
  6159. if (this === other) {
  6160. return true;
  6161. } else if (! (other instanceof LexerModeAction)) {
  6162. return false;
  6163. } else {
  6164. return this.mode === other.mode;
  6165. }
  6166. };
  6167. LexerModeAction.prototype.toString = function() {
  6168. return "mode(" + this.mode + ")";
  6169. };
  6170. // Executes a custom lexer action by calling {@link Recognizer//action} with the
  6171. // rule and action indexes assigned to the custom action. The implementation of
  6172. // a custom action is added to the generated code for the lexer in an override
  6173. // of {@link Recognizer//action} when the grammar is compiled.
  6174. //
  6175. // <p>This class may represent embedded actions created with the <code>{...}</code>
  6176. // syntax in ANTLR 4, as well as actions created for lexer commands where the
  6177. // command argument could not be evaluated when the grammar was compiled.</p>
  6178. // Constructs a custom lexer action with the specified rule and action
  6179. // indexes.
  6180. //
  6181. // @param ruleIndex The rule index to use for calls to
  6182. // {@link Recognizer//action}.
  6183. // @param actionIndex The action index to use for calls to
  6184. // {@link Recognizer//action}.
  6185. function LexerCustomAction(ruleIndex, actionIndex) {
  6186. LexerAction.call(this, LexerActionType.CUSTOM);
  6187. this.ruleIndex = ruleIndex;
  6188. this.actionIndex = actionIndex;
  6189. this.isPositionDependent = true;
  6190. return this;
  6191. }
  6192. LexerCustomAction.prototype = Object.create(LexerAction.prototype);
  6193. LexerCustomAction.prototype.constructor = LexerCustomAction;
  6194. // <p>Custom actions are implemented by calling {@link Lexer//action} with the
  6195. // appropriate rule and action indexes.</p>
  6196. LexerCustomAction.prototype.execute = function(lexer) {
  6197. lexer.action(null, this.ruleIndex, this.actionIndex);
  6198. };
  6199. LexerCustomAction.prototype.updateHashCode = function(hash) {
  6200. hash.update(this.actionType, this.ruleIndex, this.actionIndex);
  6201. };
  6202. LexerCustomAction.prototype.equals = function(other) {
  6203. if (this === other) {
  6204. return true;
  6205. } else if (! (other instanceof LexerCustomAction)) {
  6206. return false;
  6207. } else {
  6208. return this.ruleIndex === other.ruleIndex && this.actionIndex === other.actionIndex;
  6209. }
  6210. };
  6211. // Implements the {@code channel} lexer action by calling
  6212. // {@link Lexer//setChannel} with the assigned channel.
  6213. // Constructs a new {@code channel} action with the specified channel value.
  6214. // @param channel The channel value to pass to {@link Lexer//setChannel}.
  6215. function LexerChannelAction(channel) {
  6216. LexerAction.call(this, LexerActionType.CHANNEL);
  6217. this.channel = channel;
  6218. return this;
  6219. }
  6220. LexerChannelAction.prototype = Object.create(LexerAction.prototype);
  6221. LexerChannelAction.prototype.constructor = LexerChannelAction;
  6222. // <p>This action is implemented by calling {@link Lexer//setChannel} with the
  6223. // value provided by {@link //getChannel}.</p>
  6224. LexerChannelAction.prototype.execute = function(lexer) {
  6225. lexer._channel = this.channel;
  6226. };
  6227. LexerChannelAction.prototype.updateHashCode = function(hash) {
  6228. hash.update(this.actionType, this.channel);
  6229. };
  6230. LexerChannelAction.prototype.equals = function(other) {
  6231. if (this === other) {
  6232. return true;
  6233. } else if (! (other instanceof LexerChannelAction)) {
  6234. return false;
  6235. } else {
  6236. return this.channel === other.channel;
  6237. }
  6238. };
  6239. LexerChannelAction.prototype.toString = function() {
  6240. return "channel(" + this.channel + ")";
  6241. };
  6242. // This implementation of {@link LexerAction} is used for tracking input offsets
  6243. // for position-dependent actions within a {@link LexerActionExecutor}.
  6244. //
  6245. // <p>This action is not serialized as part of the ATN, and is only required for
  6246. // position-dependent lexer actions which appear at a location other than the
  6247. // end of a rule. For more information about DFA optimizations employed for
  6248. // lexer actions, see {@link LexerActionExecutor//append} and
  6249. // {@link LexerActionExecutor//fixOffsetBeforeMatch}.</p>
  6250. // Constructs a new indexed custom action by associating a character offset
  6251. // with a {@link LexerAction}.
  6252. //
  6253. // <p>Note: This class is only required for lexer actions for which
  6254. // {@link LexerAction//isPositionDependent} returns {@code true}.</p>
  6255. //
  6256. // @param offset The offset into the input {@link CharStream}, relative to
  6257. // the token start index, at which the specified lexer action should be
  6258. // executed.
  6259. // @param action The lexer action to execute at a particular offset in the
  6260. // input {@link CharStream}.
  6261. function LexerIndexedCustomAction(offset, action) {
  6262. LexerAction.call(this, action.actionType);
  6263. this.offset = offset;
  6264. this.action = action;
  6265. this.isPositionDependent = true;
  6266. return this;
  6267. }
  6268. LexerIndexedCustomAction.prototype = Object.create(LexerAction.prototype);
  6269. LexerIndexedCustomAction.prototype.constructor = LexerIndexedCustomAction;
  6270. // <p>This method calls {@link //execute} on the result of {@link //getAction}
  6271. // using the provided {@code lexer}.</p>
  6272. LexerIndexedCustomAction.prototype.execute = function(lexer) {
  6273. // assume the input stream position was properly set by the calling code
  6274. this.action.execute(lexer);
  6275. };
  6276. LexerIndexedCustomAction.prototype.updateHashCode = function(hash) {
  6277. hash.update(this.actionType, this.offset, this.action);
  6278. };
  6279. LexerIndexedCustomAction.prototype.equals = function(other) {
  6280. if (this === other) {
  6281. return true;
  6282. } else if (! (other instanceof LexerIndexedCustomAction)) {
  6283. return false;
  6284. } else {
  6285. return this.offset === other.offset && this.action === other.action;
  6286. }
  6287. };
  6288. exports.LexerActionType = LexerActionType;
  6289. exports.LexerSkipAction = LexerSkipAction;
  6290. exports.LexerChannelAction = LexerChannelAction;
  6291. exports.LexerCustomAction = LexerCustomAction;
  6292. exports.LexerIndexedCustomAction = LexerIndexedCustomAction;
  6293. exports.LexerMoreAction = LexerMoreAction;
  6294. exports.LexerTypeAction = LexerTypeAction;
  6295. exports.LexerPushModeAction = LexerPushModeAction;
  6296. exports.LexerPopModeAction = LexerPopModeAction;
  6297. exports.LexerModeAction = LexerModeAction;
  6298. /***/ }),
  6299. /***/ "./node_modules/antlr4/atn/LexerActionExecutor.js":
  6300. /*!********************************************************!*\
  6301. !*** ./node_modules/antlr4/atn/LexerActionExecutor.js ***!
  6302. \********************************************************/
  6303. /*! no static exports found */
  6304. /***/ (function(module, exports, __webpack_require__) {
  6305. //
  6306. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  6307. * Use of this file is governed by the BSD 3-clause license that
  6308. * can be found in the LICENSE.txt file in the project root.
  6309. */
  6310. ///
  6311. // Represents an executor for a sequence of lexer actions which traversed during
  6312. // the matching operation of a lexer rule (token).
  6313. //
  6314. // <p>The executor tracks position information for position-dependent lexer actions
  6315. // efficiently, ensuring that actions appearing only at the end of the rule do
  6316. // not cause bloating of the {@link DFA} created for the lexer.</p>
  6317. var hashStuff = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").hashStuff;
  6318. var LexerIndexedCustomAction = __webpack_require__(/*! ./LexerAction */ "./node_modules/antlr4/atn/LexerAction.js").LexerIndexedCustomAction;
  6319. function LexerActionExecutor(lexerActions) {
  6320. this.lexerActions = lexerActions === null ? [] : lexerActions;
  6321. // Caches the result of {@link //hashCode} since the hash code is an element
  6322. // of the performance-critical {@link LexerATNConfig//hashCode} operation.
  6323. this.cachedHashCode = hashStuff(lexerActions); // "".join([str(la) for la in
  6324. // lexerActions]))
  6325. return this;
  6326. }
  6327. // Creates a {@link LexerActionExecutor} which executes the actions for
  6328. // the input {@code lexerActionExecutor} followed by a specified
  6329. // {@code lexerAction}.
  6330. //
  6331. // @param lexerActionExecutor The executor for actions already traversed by
  6332. // the lexer while matching a token within a particular
  6333. // {@link LexerATNConfig}. If this is {@code null}, the method behaves as
  6334. // though it were an empty executor.
  6335. // @param lexerAction The lexer action to execute after the actions
  6336. // specified in {@code lexerActionExecutor}.
  6337. //
  6338. // @return A {@link LexerActionExecutor} for executing the combine actions
  6339. // of {@code lexerActionExecutor} and {@code lexerAction}.
  6340. LexerActionExecutor.append = function(lexerActionExecutor, lexerAction) {
  6341. if (lexerActionExecutor === null) {
  6342. return new LexerActionExecutor([ lexerAction ]);
  6343. }
  6344. var lexerActions = lexerActionExecutor.lexerActions.concat([ lexerAction ]);
  6345. return new LexerActionExecutor(lexerActions);
  6346. };
  6347. // Creates a {@link LexerActionExecutor} which encodes the current offset
  6348. // for position-dependent lexer actions.
  6349. //
  6350. // <p>Normally, when the executor encounters lexer actions where
  6351. // {@link LexerAction//isPositionDependent} returns {@code true}, it calls
  6352. // {@link IntStream//seek} on the input {@link CharStream} to set the input
  6353. // position to the <em>end</em> of the current token. This behavior provides
  6354. // for efficient DFA representation of lexer actions which appear at the end
  6355. // of a lexer rule, even when the lexer rule matches a variable number of
  6356. // characters.</p>
  6357. //
  6358. // <p>Prior to traversing a match transition in the ATN, the current offset
  6359. // from the token start index is assigned to all position-dependent lexer
  6360. // actions which have not already been assigned a fixed offset. By storing
  6361. // the offsets relative to the token start index, the DFA representation of
  6362. // lexer actions which appear in the middle of tokens remains efficient due
  6363. // to sharing among tokens of the same length, regardless of their absolute
  6364. // position in the input stream.</p>
  6365. //
  6366. // <p>If the current executor already has offsets assigned to all
  6367. // position-dependent lexer actions, the method returns {@code this}.</p>
  6368. //
  6369. // @param offset The current offset to assign to all position-dependent
  6370. // lexer actions which do not already have offsets assigned.
  6371. //
  6372. // @return A {@link LexerActionExecutor} which stores input stream offsets
  6373. // for all position-dependent lexer actions.
  6374. // /
  6375. LexerActionExecutor.prototype.fixOffsetBeforeMatch = function(offset) {
  6376. var updatedLexerActions = null;
  6377. for (var i = 0; i < this.lexerActions.length; i++) {
  6378. if (this.lexerActions[i].isPositionDependent &&
  6379. !(this.lexerActions[i] instanceof LexerIndexedCustomAction)) {
  6380. if (updatedLexerActions === null) {
  6381. updatedLexerActions = this.lexerActions.concat([]);
  6382. }
  6383. updatedLexerActions[i] = new LexerIndexedCustomAction(offset,
  6384. this.lexerActions[i]);
  6385. }
  6386. }
  6387. if (updatedLexerActions === null) {
  6388. return this;
  6389. } else {
  6390. return new LexerActionExecutor(updatedLexerActions);
  6391. }
  6392. };
  6393. // Execute the actions encapsulated by this executor within the context of a
  6394. // particular {@link Lexer}.
  6395. //
  6396. // <p>This method calls {@link IntStream//seek} to set the position of the
  6397. // {@code input} {@link CharStream} prior to calling
  6398. // {@link LexerAction//execute} on a position-dependent action. Before the
  6399. // method returns, the input position will be restored to the same position
  6400. // it was in when the method was invoked.</p>
  6401. //
  6402. // @param lexer The lexer instance.
  6403. // @param input The input stream which is the source for the current token.
  6404. // When this method is called, the current {@link IntStream//index} for
  6405. // {@code input} should be the start of the following token, i.e. 1
  6406. // character past the end of the current token.
  6407. // @param startIndex The token start index. This value may be passed to
  6408. // {@link IntStream//seek} to set the {@code input} position to the beginning
  6409. // of the token.
  6410. // /
  6411. LexerActionExecutor.prototype.execute = function(lexer, input, startIndex) {
  6412. var requiresSeek = false;
  6413. var stopIndex = input.index;
  6414. try {
  6415. for (var i = 0; i < this.lexerActions.length; i++) {
  6416. var lexerAction = this.lexerActions[i];
  6417. if (lexerAction instanceof LexerIndexedCustomAction) {
  6418. var offset = lexerAction.offset;
  6419. input.seek(startIndex + offset);
  6420. lexerAction = lexerAction.action;
  6421. requiresSeek = (startIndex + offset) !== stopIndex;
  6422. } else if (lexerAction.isPositionDependent) {
  6423. input.seek(stopIndex);
  6424. requiresSeek = false;
  6425. }
  6426. lexerAction.execute(lexer);
  6427. }
  6428. } finally {
  6429. if (requiresSeek) {
  6430. input.seek(stopIndex);
  6431. }
  6432. }
  6433. };
  6434. LexerActionExecutor.prototype.hashCode = function() {
  6435. return this.cachedHashCode;
  6436. };
  6437. LexerActionExecutor.prototype.updateHashCode = function(hash) {
  6438. hash.update(this.cachedHashCode);
  6439. };
  6440. LexerActionExecutor.prototype.equals = function(other) {
  6441. if (this === other) {
  6442. return true;
  6443. } else if (!(other instanceof LexerActionExecutor)) {
  6444. return false;
  6445. } else if (this.cachedHashCode != other.cachedHashCode) {
  6446. return false;
  6447. } else if (this.lexerActions.length != other.lexerActions.length) {
  6448. return false;
  6449. } else {
  6450. var numActions = this.lexerActions.length
  6451. for (var idx = 0; idx < numActions; ++idx) {
  6452. if (!this.lexerActions[idx].equals(other.lexerActions[idx])) {
  6453. return false;
  6454. }
  6455. }
  6456. return true;
  6457. }
  6458. };
  6459. exports.LexerActionExecutor = LexerActionExecutor;
  6460. /***/ }),
  6461. /***/ "./node_modules/antlr4/atn/ParserATNSimulator.js":
  6462. /*!*******************************************************!*\
  6463. !*** ./node_modules/antlr4/atn/ParserATNSimulator.js ***!
  6464. \*******************************************************/
  6465. /*! no static exports found */
  6466. /***/ (function(module, exports, __webpack_require__) {
  6467. //
  6468. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  6469. * Use of this file is governed by the BSD 3-clause license that
  6470. * can be found in the LICENSE.txt file in the project root.
  6471. */
  6472. //
  6473. //
  6474. // The embodiment of the adaptive LL(*), ALL(*), parsing strategy.
  6475. //
  6476. // <p>
  6477. // The basic complexity of the adaptive strategy makes it harder to understand.
  6478. // We begin with ATN simulation to build paths in a DFA. Subsequent prediction
  6479. // requests go through the DFA first. If they reach a state without an edge for
  6480. // the current symbol, the algorithm fails over to the ATN simulation to
  6481. // complete the DFA path for the current input (until it finds a conflict state
  6482. // or uniquely predicting state).</p>
  6483. //
  6484. // <p>
  6485. // All of that is done without using the outer context because we want to create
  6486. // a DFA that is not dependent upon the rule invocation stack when we do a
  6487. // prediction. One DFA works in all contexts. We avoid using context not
  6488. // necessarily because it's slower, although it can be, but because of the DFA
  6489. // caching problem. The closure routine only considers the rule invocation stack
  6490. // created during prediction beginning in the decision rule. For example, if
  6491. // prediction occurs without invoking another rule's ATN, there are no context
  6492. // stacks in the configurations. When lack of context leads to a conflict, we
  6493. // don't know if it's an ambiguity or a weakness in the strong LL(*) parsing
  6494. // strategy (versus full LL(*)).</p>
  6495. //
  6496. // <p>
  6497. // When SLL yields a configuration set with conflict, we rewind the input and
  6498. // retry the ATN simulation, this time using full outer context without adding
  6499. // to the DFA. Configuration context stacks will be the full invocation stacks
  6500. // from the start rule. If we get a conflict using full context, then we can
  6501. // definitively say we have a true ambiguity for that input sequence. If we
  6502. // don't get a conflict, it implies that the decision is sensitive to the outer
  6503. // context. (It is not context-sensitive in the sense of context-sensitive
  6504. // grammars.)</p>
  6505. //
  6506. // <p>
  6507. // The next time we reach this DFA state with an SLL conflict, through DFA
  6508. // simulation, we will again retry the ATN simulation using full context mode.
  6509. // This is slow because we can't save the results and have to "interpret" the
  6510. // ATN each time we get that input.</p>
  6511. //
  6512. // <p>
  6513. // <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>
  6514. //
  6515. // <p>
  6516. // We could cache results from full context to predicted alternative easily and
  6517. // that saves a lot of time but doesn't work in presence of predicates. The set
  6518. // of visible predicates from the ATN start state changes depending on the
  6519. // context, because closure can fall off the end of a rule. I tried to cache
  6520. // tuples (stack context, semantic context, predicted alt) but it was slower
  6521. // than interpreting and much more complicated. Also required a huge amount of
  6522. // memory. The goal is not to create the world's fastest parser anyway. I'd like
  6523. // to keep this algorithm simple. By launching multiple threads, we can improve
  6524. // the speed of parsing across a large number of files.</p>
  6525. //
  6526. // <p>
  6527. // There is no strict ordering between the amount of input used by SLL vs LL,
  6528. // which makes it really hard to build a cache for full context. Let's say that
  6529. // we have input A B C that leads to an SLL conflict with full context X. That
  6530. // implies that using X we might only use A B but we could also use A B C D to
  6531. // resolve conflict. Input A B C D could predict alternative 1 in one position
  6532. // in the input and A B C E could predict alternative 2 in another position in
  6533. // input. The conflicting SLL configurations could still be non-unique in the
  6534. // full context prediction, which would lead us to requiring more input than the
  6535. // original A B C. To make a prediction cache work, we have to track the exact
  6536. // input used during the previous prediction. That amounts to a cache that maps
  6537. // X to a specific DFA for that context.</p>
  6538. //
  6539. // <p>
  6540. // Something should be done for left-recursive expression predictions. They are
  6541. // likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry
  6542. // with full LL thing Sam does.</p>
  6543. //
  6544. // <p>
  6545. // <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>
  6546. //
  6547. // <p>
  6548. // We avoid doing full context retry when the outer context is empty, we did not
  6549. // dip into the outer context by falling off the end of the decision state rule,
  6550. // or when we force SLL mode.</p>
  6551. //
  6552. // <p>
  6553. // As an example of the not dip into outer context case, consider as super
  6554. // constructor calls versus function calls. One grammar might look like
  6555. // this:</p>
  6556. //
  6557. // <pre>
  6558. // ctorBody
  6559. // : '{' superCall? stat* '}'
  6560. // ;
  6561. // </pre>
  6562. //
  6563. // <p>
  6564. // Or, you might see something like</p>
  6565. //
  6566. // <pre>
  6567. // stat
  6568. // : superCall ';'
  6569. // | expression ';'
  6570. // | ...
  6571. // ;
  6572. // </pre>
  6573. //
  6574. // <p>
  6575. // In both cases I believe that no closure operations will dip into the outer
  6576. // context. In the first case ctorBody in the worst case will stop at the '}'.
  6577. // In the 2nd case it should stop at the ';'. Both cases should stay within the
  6578. // entry rule and not dip into the outer context.</p>
  6579. //
  6580. // <p>
  6581. // <strong>PREDICATES</strong></p>
  6582. //
  6583. // <p>
  6584. // Predicates are always evaluated if present in either SLL or LL both. SLL and
  6585. // LL simulation deals with predicates differently. SLL collects predicates as
  6586. // it performs closure operations like ANTLR v3 did. It delays predicate
  6587. // evaluation until it reaches and accept state. This allows us to cache the SLL
  6588. // ATN simulation whereas, if we had evaluated predicates on-the-fly during
  6589. // closure, the DFA state configuration sets would be different and we couldn't
  6590. // build up a suitable DFA.</p>
  6591. //
  6592. // <p>
  6593. // When building a DFA accept state during ATN simulation, we evaluate any
  6594. // predicates and return the sole semantically valid alternative. If there is
  6595. // more than 1 alternative, we report an ambiguity. If there are 0 alternatives,
  6596. // we throw an exception. Alternatives without predicates act like they have
  6597. // true predicates. The simple way to think about it is to strip away all
  6598. // alternatives with false predicates and choose the minimum alternative that
  6599. // remains.</p>
  6600. //
  6601. // <p>
  6602. // When we start in the DFA and reach an accept state that's predicated, we test
  6603. // those and return the minimum semantically viable alternative. If no
  6604. // alternatives are viable, we throw an exception.</p>
  6605. //
  6606. // <p>
  6607. // During full LL ATN simulation, closure always evaluates predicates and
  6608. // on-the-fly. This is crucial to reducing the configuration set size during
  6609. // closure. It hits a landmine when parsing with the Java grammar, for example,
  6610. // without this on-the-fly evaluation.</p>
  6611. //
  6612. // <p>
  6613. // <strong>SHARING DFA</strong></p>
  6614. //
  6615. // <p>
  6616. // All instances of the same parser share the same decision DFAs through a
  6617. // static field. Each instance gets its own ATN simulator but they share the
  6618. // same {@link //decisionToDFA} field. They also share a
  6619. // {@link PredictionContextCache} object that makes sure that all
  6620. // {@link PredictionContext} objects are shared among the DFA states. This makes
  6621. // a big size difference.</p>
  6622. //
  6623. // <p>
  6624. // <strong>THREAD SAFETY</strong></p>
  6625. //
  6626. // <p>
  6627. // The {@link ParserATNSimulator} locks on the {@link //decisionToDFA} field when
  6628. // it adds a new DFA object to that array. {@link //addDFAEdge}
  6629. // locks on the DFA for the current decision when setting the
  6630. // {@link DFAState//edges} field. {@link //addDFAState} locks on
  6631. // the DFA for the current decision when looking up a DFA state to see if it
  6632. // already exists. We must make sure that all requests to add DFA states that
  6633. // are equivalent result in the same shared DFA object. This is because lots of
  6634. // threads will be trying to update the DFA at once. The
  6635. // {@link //addDFAState} method also locks inside the DFA lock
  6636. // but this time on the shared context cache when it rebuilds the
  6637. // configurations' {@link PredictionContext} objects using cached
  6638. // subgraphs/nodes. No other locking occurs, even during DFA simulation. This is
  6639. // safe as long as we can guarantee that all threads referencing
  6640. // {@code s.edge[t]} get the same physical target {@link DFAState}, or
  6641. // {@code null}. Once into the DFA, the DFA simulation does not reference the
  6642. // {@link DFA//states} map. It follows the {@link DFAState//edges} field to new
  6643. // targets. The DFA simulator will either find {@link DFAState//edges} to be
  6644. // {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or
  6645. // {@code dfa.edges[t]} to be non-null. The
  6646. // {@link //addDFAEdge} method could be racing to set the field
  6647. // but in either case the DFA simulator works; if {@code null}, and requests ATN
  6648. // simulation. It could also race trying to get {@code dfa.edges[t]}, but either
  6649. // way it will work because it's not doing a test and set operation.</p>
  6650. //
  6651. // <p>
  6652. // <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage
  6653. // Parsing)</strong></p>
  6654. //
  6655. // <p>
  6656. // Sam pointed out that if SLL does not give a syntax error, then there is no
  6657. // point in doing full LL, which is slower. We only have to try LL if we get a
  6658. // syntax error. For maximum speed, Sam starts the parser set to pure SLL
  6659. // mode with the {@link BailErrorStrategy}:</p>
  6660. //
  6661. // <pre>
  6662. // parser.{@link Parser//getInterpreter() getInterpreter()}.{@link //setPredictionMode setPredictionMode}{@code (}{@link PredictionMode//SLL}{@code )};
  6663. // parser.{@link Parser//setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());
  6664. // </pre>
  6665. //
  6666. // <p>
  6667. // If it does not get a syntax error, then we're done. If it does get a syntax
  6668. // error, we need to retry with the combined SLL/LL strategy.</p>
  6669. //
  6670. // <p>
  6671. // The reason this works is as follows. If there are no SLL conflicts, then the
  6672. // grammar is SLL (at least for that input set). If there is an SLL conflict,
  6673. // the full LL analysis must yield a set of viable alternatives which is a
  6674. // subset of the alternatives reported by SLL. If the LL set is a singleton,
  6675. // then the grammar is LL but not SLL. If the LL set is the same size as the SLL
  6676. // set, the decision is SLL. If the LL set has size &gt; 1, then that decision
  6677. // is truly ambiguous on the current input. If the LL set is smaller, then the
  6678. // SLL conflict resolution might choose an alternative that the full LL would
  6679. // rule out as a possibility based upon better context information. If that's
  6680. // the case, then the SLL parse will definitely get an error because the full LL
  6681. // analysis says it's not viable. If SLL conflict resolution chooses an
  6682. // alternative within the LL set, them both SLL and LL would choose the same
  6683. // alternative because they both choose the minimum of multiple conflicting
  6684. // alternatives.</p>
  6685. //
  6686. // <p>
  6687. // Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and
  6688. // a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL
  6689. // parsing will get an error because SLL will pursue alternative 1. If
  6690. // <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will
  6691. // choose the same alternative because alternative one is the minimum of either
  6692. // set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax
  6693. // error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>
  6694. //
  6695. // <p>
  6696. // Of course, if the input is invalid, then we will get an error for sure in
  6697. // both SLL and LL parsing. Erroneous input will therefore require 2 passes over
  6698. // the input.</p>
  6699. //
  6700. var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
  6701. var Set = Utils.Set;
  6702. var BitSet = Utils.BitSet;
  6703. var DoubleDict = Utils.DoubleDict;
  6704. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  6705. var ATNState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").ATNState;
  6706. var ATNConfig = __webpack_require__(/*! ./ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").ATNConfig;
  6707. var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  6708. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  6709. var DFAState = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
  6710. var PredPrediction = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").PredPrediction;
  6711. var ATNSimulator = __webpack_require__(/*! ./ATNSimulator */ "./node_modules/antlr4/atn/ATNSimulator.js").ATNSimulator;
  6712. var PredictionMode = __webpack_require__(/*! ./PredictionMode */ "./node_modules/antlr4/atn/PredictionMode.js").PredictionMode;
  6713. var RuleContext = __webpack_require__(/*! ./../RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
  6714. var ParserRuleContext = __webpack_require__(/*! ./../ParserRuleContext */ "./node_modules/antlr4/ParserRuleContext.js").ParserRuleContext;
  6715. var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
  6716. var StarLoopEntryState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").StarLoopEntryState;
  6717. var RuleStopState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
  6718. var PredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").PredictionContext;
  6719. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  6720. var Transitions = __webpack_require__(/*! ./Transition */ "./node_modules/antlr4/atn/Transition.js");
  6721. var Transition = Transitions.Transition;
  6722. var SetTransition = Transitions.SetTransition;
  6723. var NotSetTransition = Transitions.NotSetTransition;
  6724. var RuleTransition = Transitions.RuleTransition;
  6725. var ActionTransition = Transitions.ActionTransition;
  6726. var NoViableAltException = __webpack_require__(/*! ./../error/Errors */ "./node_modules/antlr4/error/Errors.js").NoViableAltException;
  6727. var SingletonPredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").SingletonPredictionContext;
  6728. var predictionContextFromRuleContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").predictionContextFromRuleContext;
  6729. function ParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache) {
  6730. ATNSimulator.call(this, atn, sharedContextCache);
  6731. this.parser = parser;
  6732. this.decisionToDFA = decisionToDFA;
  6733. // SLL, LL, or LL + exact ambig detection?//
  6734. this.predictionMode = PredictionMode.LL;
  6735. // LAME globals to avoid parameters!!!!! I need these down deep in predTransition
  6736. this._input = null;
  6737. this._startIndex = 0;
  6738. this._outerContext = null;
  6739. this._dfa = null;
  6740. // Each prediction operation uses a cache for merge of prediction contexts.
  6741. // Don't keep around as it wastes huge amounts of memory. DoubleKeyMap
  6742. // isn't synchronized but we're ok since two threads shouldn't reuse same
  6743. // parser/atnsim object because it can only handle one input at a time.
  6744. // This maps graphs a and b to merged result c. (a,b)&rarr;c. We can avoid
  6745. // the merge if we ever see a and b again. Note that (b,a)&rarr;c should
  6746. // also be examined during cache lookup.
  6747. //
  6748. this.mergeCache = null;
  6749. return this;
  6750. }
  6751. ParserATNSimulator.prototype = Object.create(ATNSimulator.prototype);
  6752. ParserATNSimulator.prototype.constructor = ParserATNSimulator;
  6753. ParserATNSimulator.prototype.debug = false;
  6754. ParserATNSimulator.prototype.debug_closure = false;
  6755. ParserATNSimulator.prototype.debug_add = false;
  6756. ParserATNSimulator.prototype.debug_list_atn_decisions = false;
  6757. ParserATNSimulator.prototype.dfa_debug = false;
  6758. ParserATNSimulator.prototype.retry_debug = false;
  6759. ParserATNSimulator.prototype.reset = function() {
  6760. };
  6761. ParserATNSimulator.prototype.adaptivePredict = function(input, decision, outerContext) {
  6762. if (this.debug || this.debug_list_atn_decisions) {
  6763. console.log("adaptivePredict decision " + decision +
  6764. " exec LA(1)==" + this.getLookaheadName(input) +
  6765. " line " + input.LT(1).line + ":" +
  6766. input.LT(1).column);
  6767. }
  6768. this._input = input;
  6769. this._startIndex = input.index;
  6770. this._outerContext = outerContext;
  6771. var dfa = this.decisionToDFA[decision];
  6772. this._dfa = dfa;
  6773. var m = input.mark();
  6774. var index = input.index;
  6775. // Now we are certain to have a specific decision's DFA
  6776. // But, do we still need an initial state?
  6777. try {
  6778. var s0;
  6779. if (dfa.precedenceDfa) {
  6780. // the start state for a precedence DFA depends on the current
  6781. // parser precedence, and is provided by a DFA method.
  6782. s0 = dfa.getPrecedenceStartState(this.parser.getPrecedence());
  6783. } else {
  6784. // the start state for a "regular" DFA is just s0
  6785. s0 = dfa.s0;
  6786. }
  6787. if (s0===null) {
  6788. if (outerContext===null) {
  6789. outerContext = RuleContext.EMPTY;
  6790. }
  6791. if (this.debug || this.debug_list_atn_decisions) {
  6792. console.log("predictATN decision " + dfa.decision +
  6793. " exec LA(1)==" + this.getLookaheadName(input) +
  6794. ", outerContext=" + outerContext.toString(this.parser.ruleNames));
  6795. }
  6796. var fullCtx = false;
  6797. var s0_closure = this.computeStartState(dfa.atnStartState, RuleContext.EMPTY, fullCtx);
  6798. if( dfa.precedenceDfa) {
  6799. // If this is a precedence DFA, we use applyPrecedenceFilter
  6800. // to convert the computed start state to a precedence start
  6801. // state. We then use DFA.setPrecedenceStartState to set the
  6802. // appropriate start state for the precedence level rather
  6803. // than simply setting DFA.s0.
  6804. //
  6805. dfa.s0.configs = s0_closure; // not used for prediction but useful to know start configs anyway
  6806. s0_closure = this.applyPrecedenceFilter(s0_closure);
  6807. s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
  6808. dfa.setPrecedenceStartState(this.parser.getPrecedence(), s0);
  6809. } else {
  6810. s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
  6811. dfa.s0 = s0;
  6812. }
  6813. }
  6814. var alt = this.execATN(dfa, s0, input, index, outerContext);
  6815. if (this.debug) {
  6816. console.log("DFA after predictATN: " + dfa.toString(this.parser.literalNames));
  6817. }
  6818. return alt;
  6819. } finally {
  6820. this._dfa = null;
  6821. this.mergeCache = null; // wack cache after each prediction
  6822. input.seek(index);
  6823. input.release(m);
  6824. }
  6825. };
  6826. // Performs ATN simulation to compute a predicted alternative based
  6827. // upon the remaining input, but also updates the DFA cache to avoid
  6828. // having to traverse the ATN again for the same input sequence.
  6829. // There are some key conditions we're looking for after computing a new
  6830. // set of ATN configs (proposed DFA state):
  6831. // if the set is empty, there is no viable alternative for current symbol
  6832. // does the state uniquely predict an alternative?
  6833. // does the state have a conflict that would prevent us from
  6834. // putting it on the work list?
  6835. // We also have some key operations to do:
  6836. // add an edge from previous DFA state to potentially new DFA state, D,
  6837. // upon current symbol but only if adding to work list, which means in all
  6838. // cases except no viable alternative (and possibly non-greedy decisions?)
  6839. // collecting predicates and adding semantic context to DFA accept states
  6840. // adding rule context to context-sensitive DFA accept states
  6841. // consuming an input symbol
  6842. // reporting a conflict
  6843. // reporting an ambiguity
  6844. // reporting a context sensitivity
  6845. // reporting insufficient predicates
  6846. // cover these cases:
  6847. // dead end
  6848. // single alt
  6849. // single alt + preds
  6850. // conflict
  6851. // conflict + preds
  6852. //
  6853. ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, outerContext ) {
  6854. if (this.debug || this.debug_list_atn_decisions) {
  6855. console.log("execATN decision " + dfa.decision +
  6856. " exec LA(1)==" + this.getLookaheadName(input) +
  6857. " line " + input.LT(1).line + ":" + input.LT(1).column);
  6858. }
  6859. var alt;
  6860. var previousD = s0;
  6861. if (this.debug) {
  6862. console.log("s0 = " + s0);
  6863. }
  6864. var t = input.LA(1);
  6865. while(true) { // while more work
  6866. var D = this.getExistingTargetState(previousD, t);
  6867. if(D===null) {
  6868. D = this.computeTargetState(dfa, previousD, t);
  6869. }
  6870. if(D===ATNSimulator.ERROR) {
  6871. // if any configs in previous dipped into outer context, that
  6872. // means that input up to t actually finished entry rule
  6873. // at least for SLL decision. Full LL doesn't dip into outer
  6874. // so don't need special case.
  6875. // We will get an error no matter what so delay until after
  6876. // decision; better error message. Also, no reachable target
  6877. // ATN states in SLL implies LL will also get nowhere.
  6878. // If conflict in states that dip out, choose min since we
  6879. // will get error no matter what.
  6880. var e = this.noViableAlt(input, outerContext, previousD.configs, startIndex);
  6881. input.seek(startIndex);
  6882. alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext);
  6883. if(alt!==ATN.INVALID_ALT_NUMBER) {
  6884. return alt;
  6885. } else {
  6886. throw e;
  6887. }
  6888. }
  6889. if(D.requiresFullContext && this.predictionMode !== PredictionMode.SLL) {
  6890. // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)
  6891. var conflictingAlts = null;
  6892. if (D.predicates!==null) {
  6893. if (this.debug) {
  6894. console.log("DFA state has preds in DFA sim LL failover");
  6895. }
  6896. var conflictIndex = input.index;
  6897. if(conflictIndex !== startIndex) {
  6898. input.seek(startIndex);
  6899. }
  6900. conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true);
  6901. if (conflictingAlts.length===1) {
  6902. if(this.debug) {
  6903. console.log("Full LL avoided");
  6904. }
  6905. return conflictingAlts.minValue();
  6906. }
  6907. if (conflictIndex !== startIndex) {
  6908. // restore the index so reporting the fallback to full
  6909. // context occurs with the index at the correct spot
  6910. input.seek(conflictIndex);
  6911. }
  6912. }
  6913. if (this.dfa_debug) {
  6914. console.log("ctx sensitive state " + outerContext +" in " + D);
  6915. }
  6916. var fullCtx = true;
  6917. var s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx);
  6918. this.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index);
  6919. alt = this.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext);
  6920. return alt;
  6921. }
  6922. if (D.isAcceptState) {
  6923. if (D.predicates===null) {
  6924. return D.prediction;
  6925. }
  6926. var stopIndex = input.index;
  6927. input.seek(startIndex);
  6928. var alts = this.evalSemanticContext(D.predicates, outerContext, true);
  6929. if (alts.length===0) {
  6930. throw this.noViableAlt(input, outerContext, D.configs, startIndex);
  6931. } else if (alts.length===1) {
  6932. return alts.minValue();
  6933. } else {
  6934. // report ambiguity after predicate evaluation to make sure the correct set of ambig alts is reported.
  6935. this.reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs);
  6936. return alts.minValue();
  6937. }
  6938. }
  6939. previousD = D;
  6940. if (t !== Token.EOF) {
  6941. input.consume();
  6942. t = input.LA(1);
  6943. }
  6944. }
  6945. };
  6946. //
  6947. // Get an existing target state for an edge in the DFA. If the target state
  6948. // for the edge has not yet been computed or is otherwise not available,
  6949. // this method returns {@code null}.
  6950. //
  6951. // @param previousD The current DFA state
  6952. // @param t The next input symbol
  6953. // @return The existing target DFA state for the given input symbol
  6954. // {@code t}, or {@code null} if the target state for this edge is not
  6955. // already cached
  6956. //
  6957. ParserATNSimulator.prototype.getExistingTargetState = function(previousD, t) {
  6958. var edges = previousD.edges;
  6959. if (edges===null) {
  6960. return null;
  6961. } else {
  6962. return edges[t + 1] || null;
  6963. }
  6964. };
  6965. //
  6966. // Compute a target state for an edge in the DFA, and attempt to add the
  6967. // computed state and corresponding edge to the DFA.
  6968. //
  6969. // @param dfa The DFA
  6970. // @param previousD The current DFA state
  6971. // @param t The next input symbol
  6972. //
  6973. // @return The computed target DFA state for the given input symbol
  6974. // {@code t}. If {@code t} does not lead to a valid DFA state, this method
  6975. // returns {@link //ERROR}.
  6976. //
  6977. ParserATNSimulator.prototype.computeTargetState = function(dfa, previousD, t) {
  6978. var reach = this.computeReachSet(previousD.configs, t, false);
  6979. if(reach===null) {
  6980. this.addDFAEdge(dfa, previousD, t, ATNSimulator.ERROR);
  6981. return ATNSimulator.ERROR;
  6982. }
  6983. // create new target state; we'll add to DFA after it's complete
  6984. var D = new DFAState(null, reach);
  6985. var predictedAlt = this.getUniqueAlt(reach);
  6986. if (this.debug) {
  6987. var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
  6988. console.log("SLL altSubSets=" + Utils.arrayToString(altSubSets) +
  6989. ", previous=" + previousD.configs +
  6990. ", configs=" + reach +
  6991. ", predict=" + predictedAlt +
  6992. ", allSubsetsConflict=" +
  6993. PredictionMode.allSubsetsConflict(altSubSets) + ", conflictingAlts=" +
  6994. this.getConflictingAlts(reach));
  6995. }
  6996. if (predictedAlt!==ATN.INVALID_ALT_NUMBER) {
  6997. // NO CONFLICT, UNIQUELY PREDICTED ALT
  6998. D.isAcceptState = true;
  6999. D.configs.uniqueAlt = predictedAlt;
  7000. D.prediction = predictedAlt;
  7001. } else if (PredictionMode.hasSLLConflictTerminatingPrediction(this.predictionMode, reach)) {
  7002. // MORE THAN ONE VIABLE ALTERNATIVE
  7003. D.configs.conflictingAlts = this.getConflictingAlts(reach);
  7004. D.requiresFullContext = true;
  7005. // in SLL-only mode, we will stop at this state and return the minimum alt
  7006. D.isAcceptState = true;
  7007. D.prediction = D.configs.conflictingAlts.minValue();
  7008. }
  7009. if (D.isAcceptState && D.configs.hasSemanticContext) {
  7010. this.predicateDFAState(D, this.atn.getDecisionState(dfa.decision));
  7011. if( D.predicates!==null) {
  7012. D.prediction = ATN.INVALID_ALT_NUMBER;
  7013. }
  7014. }
  7015. // all adds to dfa are done after we've created full D state
  7016. D = this.addDFAEdge(dfa, previousD, t, D);
  7017. return D;
  7018. };
  7019. ParserATNSimulator.prototype.predicateDFAState = function(dfaState, decisionState) {
  7020. // We need to test all predicates, even in DFA states that
  7021. // uniquely predict alternative.
  7022. var nalts = decisionState.transitions.length;
  7023. // Update DFA so reach becomes accept state with (predicate,alt)
  7024. // pairs if preds found for conflicting alts
  7025. var altsToCollectPredsFrom = this.getConflictingAltsOrUniqueAlt(dfaState.configs);
  7026. var altToPred = this.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts);
  7027. if (altToPred!==null) {
  7028. dfaState.predicates = this.getPredicatePredictions(altsToCollectPredsFrom, altToPred);
  7029. dfaState.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds
  7030. } else {
  7031. // There are preds in configs but they might go away
  7032. // when OR'd together like {p}? || NONE == NONE. If neither
  7033. // alt has preds, resolve to min alt
  7034. dfaState.prediction = altsToCollectPredsFrom.minValue();
  7035. }
  7036. };
  7037. // comes back with reach.uniqueAlt set to a valid alt
  7038. ParserATNSimulator.prototype.execATNWithFullContext = function(dfa, D, // how far we got before failing over
  7039. s0,
  7040. input,
  7041. startIndex,
  7042. outerContext) {
  7043. if (this.debug || this.debug_list_atn_decisions) {
  7044. console.log("execATNWithFullContext "+s0);
  7045. }
  7046. var fullCtx = true;
  7047. var foundExactAmbig = false;
  7048. var reach = null;
  7049. var previous = s0;
  7050. input.seek(startIndex);
  7051. var t = input.LA(1);
  7052. var predictedAlt = -1;
  7053. while (true) { // while more work
  7054. reach = this.computeReachSet(previous, t, fullCtx);
  7055. if (reach===null) {
  7056. // if any configs in previous dipped into outer context, that
  7057. // means that input up to t actually finished entry rule
  7058. // at least for LL decision. Full LL doesn't dip into outer
  7059. // so don't need special case.
  7060. // We will get an error no matter what so delay until after
  7061. // decision; better error message. Also, no reachable target
  7062. // ATN states in SLL implies LL will also get nowhere.
  7063. // If conflict in states that dip out, choose min since we
  7064. // will get error no matter what.
  7065. var e = this.noViableAlt(input, outerContext, previous, startIndex);
  7066. input.seek(startIndex);
  7067. var alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext);
  7068. if(alt!==ATN.INVALID_ALT_NUMBER) {
  7069. return alt;
  7070. } else {
  7071. throw e;
  7072. }
  7073. }
  7074. var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
  7075. if(this.debug) {
  7076. console.log("LL altSubSets=" + altSubSets + ", predict=" +
  7077. PredictionMode.getUniqueAlt(altSubSets) + ", resolvesToJustOneViableAlt=" +
  7078. PredictionMode.resolvesToJustOneViableAlt(altSubSets));
  7079. }
  7080. reach.uniqueAlt = this.getUniqueAlt(reach);
  7081. // unique prediction?
  7082. if(reach.uniqueAlt!==ATN.INVALID_ALT_NUMBER) {
  7083. predictedAlt = reach.uniqueAlt;
  7084. break;
  7085. } else if (this.predictionMode !== PredictionMode.LL_EXACT_AMBIG_DETECTION) {
  7086. predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets);
  7087. if(predictedAlt !== ATN.INVALID_ALT_NUMBER) {
  7088. break;
  7089. }
  7090. } else {
  7091. // In exact ambiguity mode, we never try to terminate early.
  7092. // Just keeps scarfing until we know what the conflict is
  7093. if (PredictionMode.allSubsetsConflict(altSubSets) && PredictionMode.allSubsetsEqual(altSubSets)) {
  7094. foundExactAmbig = true;
  7095. predictedAlt = PredictionMode.getSingleViableAlt(altSubSets);
  7096. break;
  7097. }
  7098. // else there are multiple non-conflicting subsets or
  7099. // we're not sure what the ambiguity is yet.
  7100. // So, keep going.
  7101. }
  7102. previous = reach;
  7103. if( t !== Token.EOF) {
  7104. input.consume();
  7105. t = input.LA(1);
  7106. }
  7107. }
  7108. // If the configuration set uniquely predicts an alternative,
  7109. // without conflict, then we know that it's a full LL decision
  7110. // not SLL.
  7111. if (reach.uniqueAlt !== ATN.INVALID_ALT_NUMBER ) {
  7112. this.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index);
  7113. return predictedAlt;
  7114. }
  7115. // We do not check predicates here because we have checked them
  7116. // on-the-fly when doing full context prediction.
  7117. //
  7118. // In non-exact ambiguity detection mode, we might actually be able to
  7119. // detect an exact ambiguity, but I'm not going to spend the cycles
  7120. // needed to check. We only emit ambiguity warnings in exact ambiguity
  7121. // mode.
  7122. //
  7123. // For example, we might know that we have conflicting configurations.
  7124. // But, that does not mean that there is no way forward without a
  7125. // conflict. It's possible to have nonconflicting alt subsets as in:
  7126. // altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]
  7127. // from
  7128. //
  7129. // [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),
  7130. // (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]
  7131. //
  7132. // In this case, (17,1,[5 $]) indicates there is some next sequence that
  7133. // would resolve this without conflict to alternative 1. Any other viable
  7134. // next sequence, however, is associated with a conflict. We stop
  7135. // looking for input because no amount of further lookahead will alter
  7136. // the fact that we should predict alternative 1. We just can't say for
  7137. // sure that there is an ambiguity without looking further.
  7138. this.reportAmbiguity(dfa, D, startIndex, input.index, foundExactAmbig, null, reach);
  7139. return predictedAlt;
  7140. };
  7141. ParserATNSimulator.prototype.computeReachSet = function(closure, t, fullCtx) {
  7142. if (this.debug) {
  7143. console.log("in computeReachSet, starting closure: " + closure);
  7144. }
  7145. if( this.mergeCache===null) {
  7146. this.mergeCache = new DoubleDict();
  7147. }
  7148. var intermediate = new ATNConfigSet(fullCtx);
  7149. // Configurations already in a rule stop state indicate reaching the end
  7150. // of the decision rule (local context) or end of the start rule (full
  7151. // context). Once reached, these configurations are never updated by a
  7152. // closure operation, so they are handled separately for the performance
  7153. // advantage of having a smaller intermediate set when calling closure.
  7154. //
  7155. // For full-context reach operations, separate handling is required to
  7156. // ensure that the alternative matching the longest overall sequence is
  7157. // chosen when multiple such configurations can match the input.
  7158. var skippedStopStates = null;
  7159. // First figure out where we can reach on input t
  7160. for (var i=0; i<closure.items.length;i++) {
  7161. var c = closure.items[i];
  7162. if(this.debug_add) {
  7163. console.log("testing " + this.getTokenName(t) + " at " + c);
  7164. }
  7165. if (c.state instanceof RuleStopState) {
  7166. if (fullCtx || t === Token.EOF) {
  7167. if (skippedStopStates===null) {
  7168. skippedStopStates = [];
  7169. }
  7170. skippedStopStates.push(c);
  7171. if(this.debug_add) {
  7172. console.log("added " + c + " to skippedStopStates");
  7173. }
  7174. }
  7175. continue;
  7176. }
  7177. for(var j=0;j<c.state.transitions.length;j++) {
  7178. var trans = c.state.transitions[j];
  7179. var target = this.getReachableTarget(trans, t);
  7180. if (target!==null) {
  7181. var cfg = new ATNConfig({state:target}, c);
  7182. intermediate.add(cfg, this.mergeCache);
  7183. if(this.debug_add) {
  7184. console.log("added " + cfg + " to intermediate");
  7185. }
  7186. }
  7187. }
  7188. }
  7189. // Now figure out where the reach operation can take us...
  7190. var reach = null;
  7191. // This block optimizes the reach operation for intermediate sets which
  7192. // trivially indicate a termination state for the overall
  7193. // adaptivePredict operation.
  7194. //
  7195. // The conditions assume that intermediate
  7196. // contains all configurations relevant to the reach set, but this
  7197. // condition is not true when one or more configurations have been
  7198. // withheld in skippedStopStates, or when the current symbol is EOF.
  7199. //
  7200. if (skippedStopStates===null && t!==Token.EOF) {
  7201. if (intermediate.items.length===1) {
  7202. // Don't pursue the closure if there is just one state.
  7203. // It can only have one alternative; just add to result
  7204. // Also don't pursue the closure if there is unique alternative
  7205. // among the configurations.
  7206. reach = intermediate;
  7207. } else if (this.getUniqueAlt(intermediate)!==ATN.INVALID_ALT_NUMBER) {
  7208. // Also don't pursue the closure if there is unique alternative
  7209. // among the configurations.
  7210. reach = intermediate;
  7211. }
  7212. }
  7213. // If the reach set could not be trivially determined, perform a closure
  7214. // operation on the intermediate set to compute its initial value.
  7215. //
  7216. if (reach===null) {
  7217. reach = new ATNConfigSet(fullCtx);
  7218. var closureBusy = new Set();
  7219. var treatEofAsEpsilon = t === Token.EOF;
  7220. for (var k=0; k<intermediate.items.length;k++) {
  7221. this.closure(intermediate.items[k], reach, closureBusy, false, fullCtx, treatEofAsEpsilon);
  7222. }
  7223. }
  7224. if (t === Token.EOF) {
  7225. // After consuming EOF no additional input is possible, so we are
  7226. // only interested in configurations which reached the end of the
  7227. // decision rule (local context) or end of the start rule (full
  7228. // context). Update reach to contain only these configurations. This
  7229. // handles both explicit EOF transitions in the grammar and implicit
  7230. // EOF transitions following the end of the decision or start rule.
  7231. //
  7232. // When reach==intermediate, no closure operation was performed. In
  7233. // this case, removeAllConfigsNotInRuleStopState needs to check for
  7234. // reachable rule stop states as well as configurations already in
  7235. // a rule stop state.
  7236. //
  7237. // This is handled before the configurations in skippedStopStates,
  7238. // because any configurations potentially added from that list are
  7239. // already guaranteed to meet this condition whether or not it's
  7240. // required.
  7241. //
  7242. reach = this.removeAllConfigsNotInRuleStopState(reach, reach === intermediate);
  7243. }
  7244. // If skippedStopStates!==null, then it contains at least one
  7245. // configuration. For full-context reach operations, these
  7246. // configurations reached the end of the start rule, in which case we
  7247. // only add them back to reach if no configuration during the current
  7248. // closure operation reached such a state. This ensures adaptivePredict
  7249. // chooses an alternative matching the longest overall sequence when
  7250. // multiple alternatives are viable.
  7251. //
  7252. if (skippedStopStates!==null && ( (! fullCtx) || (! PredictionMode.hasConfigInRuleStopState(reach)))) {
  7253. for (var l=0; l<skippedStopStates.length;l++) {
  7254. reach.add(skippedStopStates[l], this.mergeCache);
  7255. }
  7256. }
  7257. if (reach.items.length===0) {
  7258. return null;
  7259. } else {
  7260. return reach;
  7261. }
  7262. };
  7263. //
  7264. // Return a configuration set containing only the configurations from
  7265. // {@code configs} which are in a {@link RuleStopState}. If all
  7266. // configurations in {@code configs} are already in a rule stop state, this
  7267. // method simply returns {@code configs}.
  7268. //
  7269. // <p>When {@code lookToEndOfRule} is true, this method uses
  7270. // {@link ATN//nextTokens} for each configuration in {@code configs} which is
  7271. // not already in a rule stop state to see if a rule stop state is reachable
  7272. // from the configuration via epsilon-only transitions.</p>
  7273. //
  7274. // @param configs the configuration set to update
  7275. // @param lookToEndOfRule when true, this method checks for rule stop states
  7276. // reachable by epsilon-only transitions from each configuration in
  7277. // {@code configs}.
  7278. //
  7279. // @return {@code configs} if all configurations in {@code configs} are in a
  7280. // rule stop state, otherwise return a new configuration set containing only
  7281. // the configurations from {@code configs} which are in a rule stop state
  7282. //
  7283. ParserATNSimulator.prototype.removeAllConfigsNotInRuleStopState = function(configs, lookToEndOfRule) {
  7284. if (PredictionMode.allConfigsInRuleStopStates(configs)) {
  7285. return configs;
  7286. }
  7287. var result = new ATNConfigSet(configs.fullCtx);
  7288. for(var i=0; i<configs.items.length;i++) {
  7289. var config = configs.items[i];
  7290. if (config.state instanceof RuleStopState) {
  7291. result.add(config, this.mergeCache);
  7292. continue;
  7293. }
  7294. if (lookToEndOfRule && config.state.epsilonOnlyTransitions) {
  7295. var nextTokens = this.atn.nextTokens(config.state);
  7296. if (nextTokens.contains(Token.EPSILON)) {
  7297. var endOfRuleState = this.atn.ruleToStopState[config.state.ruleIndex];
  7298. result.add(new ATNConfig({state:endOfRuleState}, config), this.mergeCache);
  7299. }
  7300. }
  7301. }
  7302. return result;
  7303. };
  7304. ParserATNSimulator.prototype.computeStartState = function(p, ctx, fullCtx) {
  7305. // always at least the implicit call to start rule
  7306. var initialContext = predictionContextFromRuleContext(this.atn, ctx);
  7307. var configs = new ATNConfigSet(fullCtx);
  7308. for(var i=0;i<p.transitions.length;i++) {
  7309. var target = p.transitions[i].target;
  7310. var c = new ATNConfig({ state:target, alt:i+1, context:initialContext }, null);
  7311. var closureBusy = new Set();
  7312. this.closure(c, configs, closureBusy, true, fullCtx, false);
  7313. }
  7314. return configs;
  7315. };
  7316. //
  7317. // This method transforms the start state computed by
  7318. // {@link //computeStartState} to the special start state used by a
  7319. // precedence DFA for a particular precedence value. The transformation
  7320. // process applies the following changes to the start state's configuration
  7321. // set.
  7322. //
  7323. // <ol>
  7324. // <li>Evaluate the precedence predicates for each configuration using
  7325. // {@link SemanticContext//evalPrecedence}.</li>
  7326. // <li>Remove all configurations which predict an alternative greater than
  7327. // 1, for which another configuration that predicts alternative 1 is in the
  7328. // same ATN state with the same prediction context. This transformation is
  7329. // valid for the following reasons:
  7330. // <ul>
  7331. // <li>The closure block cannot contain any epsilon transitions which bypass
  7332. // the body of the closure, so all states reachable via alternative 1 are
  7333. // part of the precedence alternatives of the transformed left-recursive
  7334. // rule.</li>
  7335. // <li>The "primary" portion of a left recursive rule cannot contain an
  7336. // epsilon transition, so the only way an alternative other than 1 can exist
  7337. // in a state that is also reachable via alternative 1 is by nesting calls
  7338. // to the left-recursive rule, with the outer calls not being at the
  7339. // preferred precedence level.</li>
  7340. // </ul>
  7341. // </li>
  7342. // </ol>
  7343. //
  7344. // <p>
  7345. // The prediction context must be considered by this filter to address
  7346. // situations like the following.
  7347. // </p>
  7348. // <code>
  7349. // <pre>
  7350. // grammar TA;
  7351. // prog: statement* EOF;
  7352. // statement: letterA | statement letterA 'b' ;
  7353. // letterA: 'a';
  7354. // </pre>
  7355. // </code>
  7356. // <p>
  7357. // If the above grammar, the ATN state immediately before the token
  7358. // reference {@code 'a'} in {@code letterA} is reachable from the left edge
  7359. // of both the primary and closure blocks of the left-recursive rule
  7360. // {@code statement}. The prediction context associated with each of these
  7361. // configurations distinguishes between them, and prevents the alternative
  7362. // which stepped out to {@code prog} (and then back in to {@code statement}
  7363. // from being eliminated by the filter.
  7364. // </p>
  7365. //
  7366. // @param configs The configuration set computed by
  7367. // {@link //computeStartState} as the start state for the DFA.
  7368. // @return The transformed configuration set representing the start state
  7369. // for a precedence DFA at a particular precedence level (determined by
  7370. // calling {@link Parser//getPrecedence}).
  7371. //
  7372. ParserATNSimulator.prototype.applyPrecedenceFilter = function(configs) {
  7373. var config;
  7374. var statesFromAlt1 = [];
  7375. var configSet = new ATNConfigSet(configs.fullCtx);
  7376. for(var i=0; i<configs.items.length; i++) {
  7377. config = configs.items[i];
  7378. // handle alt 1 first
  7379. if (config.alt !== 1) {
  7380. continue;
  7381. }
  7382. var updatedContext = config.semanticContext.evalPrecedence(this.parser, this._outerContext);
  7383. if (updatedContext===null) {
  7384. // the configuration was eliminated
  7385. continue;
  7386. }
  7387. statesFromAlt1[config.state.stateNumber] = config.context;
  7388. if (updatedContext !== config.semanticContext) {
  7389. configSet.add(new ATNConfig({semanticContext:updatedContext}, config), this.mergeCache);
  7390. } else {
  7391. configSet.add(config, this.mergeCache);
  7392. }
  7393. }
  7394. for(i=0; i<configs.items.length; i++) {
  7395. config = configs.items[i];
  7396. if (config.alt === 1) {
  7397. // already handled
  7398. continue;
  7399. }
  7400. // In the future, this elimination step could be updated to also
  7401. // filter the prediction context for alternatives predicting alt>1
  7402. // (basically a graph subtraction algorithm).
  7403. if (!config.precedenceFilterSuppressed) {
  7404. var context = statesFromAlt1[config.state.stateNumber] || null;
  7405. if (context!==null && context.equals(config.context)) {
  7406. // eliminated
  7407. continue;
  7408. }
  7409. }
  7410. configSet.add(config, this.mergeCache);
  7411. }
  7412. return configSet;
  7413. };
  7414. ParserATNSimulator.prototype.getReachableTarget = function(trans, ttype) {
  7415. if (trans.matches(ttype, 0, this.atn.maxTokenType)) {
  7416. return trans.target;
  7417. } else {
  7418. return null;
  7419. }
  7420. };
  7421. ParserATNSimulator.prototype.getPredsForAmbigAlts = function(ambigAlts, configs, nalts) {
  7422. // REACH=[1|1|[]|0:0, 1|2|[]|0:1]
  7423. // altToPred starts as an array of all null contexts. The entry at index i
  7424. // corresponds to alternative i. altToPred[i] may have one of three values:
  7425. // 1. null: no ATNConfig c is found such that c.alt==i
  7426. // 2. SemanticContext.NONE: At least one ATNConfig c exists such that
  7427. // c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,
  7428. // alt i has at least one unpredicated config.
  7429. // 3. Non-NONE Semantic Context: There exists at least one, and for all
  7430. // ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.
  7431. //
  7432. // From this, it is clear that NONE||anything==NONE.
  7433. //
  7434. var altToPred = [];
  7435. for(var i=0;i<configs.items.length;i++) {
  7436. var c = configs.items[i];
  7437. if(ambigAlts.contains( c.alt )) {
  7438. altToPred[c.alt] = SemanticContext.orContext(altToPred[c.alt] || null, c.semanticContext);
  7439. }
  7440. }
  7441. var nPredAlts = 0;
  7442. for (i =1;i< nalts+1;i++) {
  7443. var pred = altToPred[i] || null;
  7444. if (pred===null) {
  7445. altToPred[i] = SemanticContext.NONE;
  7446. } else if (pred !== SemanticContext.NONE) {
  7447. nPredAlts += 1;
  7448. }
  7449. }
  7450. // nonambig alts are null in altToPred
  7451. if (nPredAlts===0) {
  7452. altToPred = null;
  7453. }
  7454. if (this.debug) {
  7455. console.log("getPredsForAmbigAlts result " + Utils.arrayToString(altToPred));
  7456. }
  7457. return altToPred;
  7458. };
  7459. ParserATNSimulator.prototype.getPredicatePredictions = function(ambigAlts, altToPred) {
  7460. var pairs = [];
  7461. var containsPredicate = false;
  7462. for (var i=1; i<altToPred.length;i++) {
  7463. var pred = altToPred[i];
  7464. // unpredicated is indicated by SemanticContext.NONE
  7465. if( ambigAlts!==null && ambigAlts.contains( i )) {
  7466. pairs.push(new PredPrediction(pred, i));
  7467. }
  7468. if (pred !== SemanticContext.NONE) {
  7469. containsPredicate = true;
  7470. }
  7471. }
  7472. if (! containsPredicate) {
  7473. return null;
  7474. }
  7475. return pairs;
  7476. };
  7477. //
  7478. // This method is used to improve the localization of error messages by
  7479. // choosing an alternative rather than throwing a
  7480. // {@link NoViableAltException} in particular prediction scenarios where the
  7481. // {@link //ERROR} state was reached during ATN simulation.
  7482. //
  7483. // <p>
  7484. // The default implementation of this method uses the following
  7485. // algorithm to identify an ATN configuration which successfully parsed the
  7486. // decision entry rule. Choosing such an alternative ensures that the
  7487. // {@link ParserRuleContext} returned by the calling rule will be complete
  7488. // and valid, and the syntax error will be reported later at a more
  7489. // localized location.</p>
  7490. //
  7491. // <ul>
  7492. // <li>If a syntactically valid path or paths reach the end of the decision rule and
  7493. // they are semantically valid if predicated, return the min associated alt.</li>
  7494. // <li>Else, if a semantically invalid but syntactically valid path exist
  7495. // or paths exist, return the minimum associated alt.
  7496. // </li>
  7497. // <li>Otherwise, return {@link ATN//INVALID_ALT_NUMBER}.</li>
  7498. // </ul>
  7499. //
  7500. // <p>
  7501. // In some scenarios, the algorithm described above could predict an
  7502. // alternative which will result in a {@link FailedPredicateException} in
  7503. // the parser. Specifically, this could occur if the <em>only</em> configuration
  7504. // capable of successfully parsing to the end of the decision rule is
  7505. // blocked by a semantic predicate. By choosing this alternative within
  7506. // {@link //adaptivePredict} instead of throwing a
  7507. // {@link NoViableAltException}, the resulting
  7508. // {@link FailedPredicateException} in the parser will identify the specific
  7509. // predicate which is preventing the parser from successfully parsing the
  7510. // decision rule, which helps developers identify and correct logic errors
  7511. // in semantic predicates.
  7512. // </p>
  7513. //
  7514. // @param configs The ATN configurations which were valid immediately before
  7515. // the {@link //ERROR} state was reached
  7516. // @param outerContext The is the \gamma_0 initial parser context from the paper
  7517. // or the parser stack at the instant before prediction commences.
  7518. //
  7519. // @return The value to return from {@link //adaptivePredict}, or
  7520. // {@link ATN//INVALID_ALT_NUMBER} if a suitable alternative was not
  7521. // identified and {@link //adaptivePredict} should report an error instead.
  7522. //
  7523. ParserATNSimulator.prototype.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule = function(configs, outerContext) {
  7524. var cfgs = this.splitAccordingToSemanticValidity(configs, outerContext);
  7525. var semValidConfigs = cfgs[0];
  7526. var semInvalidConfigs = cfgs[1];
  7527. var alt = this.getAltThatFinishedDecisionEntryRule(semValidConfigs);
  7528. if (alt!==ATN.INVALID_ALT_NUMBER) { // semantically/syntactically viable path exists
  7529. return alt;
  7530. }
  7531. // Is there a syntactically valid path with a failed pred?
  7532. if (semInvalidConfigs.items.length>0) {
  7533. alt = this.getAltThatFinishedDecisionEntryRule(semInvalidConfigs);
  7534. if (alt!==ATN.INVALID_ALT_NUMBER) { // syntactically viable path exists
  7535. return alt;
  7536. }
  7537. }
  7538. return ATN.INVALID_ALT_NUMBER;
  7539. };
  7540. ParserATNSimulator.prototype.getAltThatFinishedDecisionEntryRule = function(configs) {
  7541. var alts = [];
  7542. for(var i=0;i<configs.items.length; i++) {
  7543. var c = configs.items[i];
  7544. if (c.reachesIntoOuterContext>0 || ((c.state instanceof RuleStopState) && c.context.hasEmptyPath())) {
  7545. if(alts.indexOf(c.alt)<0) {
  7546. alts.push(c.alt);
  7547. }
  7548. }
  7549. }
  7550. if (alts.length===0) {
  7551. return ATN.INVALID_ALT_NUMBER;
  7552. } else {
  7553. return Math.min.apply(null, alts);
  7554. }
  7555. };
  7556. // Walk the list of configurations and split them according to
  7557. // those that have preds evaluating to true/false. If no pred, assume
  7558. // true pred and include in succeeded set. Returns Pair of sets.
  7559. //
  7560. // Create a new set so as not to alter the incoming parameter.
  7561. //
  7562. // Assumption: the input stream has been restored to the starting point
  7563. // prediction, which is where predicates need to evaluate.
  7564. //
  7565. ParserATNSimulator.prototype.splitAccordingToSemanticValidity = function( configs, outerContext) {
  7566. var succeeded = new ATNConfigSet(configs.fullCtx);
  7567. var failed = new ATNConfigSet(configs.fullCtx);
  7568. for(var i=0;i<configs.items.length; i++) {
  7569. var c = configs.items[i];
  7570. if (c.semanticContext !== SemanticContext.NONE) {
  7571. var predicateEvaluationResult = c.semanticContext.evaluate(this.parser, outerContext);
  7572. if (predicateEvaluationResult) {
  7573. succeeded.add(c);
  7574. } else {
  7575. failed.add(c);
  7576. }
  7577. } else {
  7578. succeeded.add(c);
  7579. }
  7580. }
  7581. return [succeeded, failed];
  7582. };
  7583. // Look through a list of predicate/alt pairs, returning alts for the
  7584. // pairs that win. A {@code NONE} predicate indicates an alt containing an
  7585. // unpredicated config which behaves as "always true." If !complete
  7586. // then we stop at the first predicate that evaluates to true. This
  7587. // includes pairs with null predicates.
  7588. //
  7589. ParserATNSimulator.prototype.evalSemanticContext = function(predPredictions, outerContext, complete) {
  7590. var predictions = new BitSet();
  7591. for(var i=0;i<predPredictions.length;i++) {
  7592. var pair = predPredictions[i];
  7593. if (pair.pred === SemanticContext.NONE) {
  7594. predictions.add(pair.alt);
  7595. if (! complete) {
  7596. break;
  7597. }
  7598. continue;
  7599. }
  7600. var predicateEvaluationResult = pair.pred.evaluate(this.parser, outerContext);
  7601. if (this.debug || this.dfa_debug) {
  7602. console.log("eval pred " + pair + "=" + predicateEvaluationResult);
  7603. }
  7604. if (predicateEvaluationResult) {
  7605. if (this.debug || this.dfa_debug) {
  7606. console.log("PREDICT " + pair.alt);
  7607. }
  7608. predictions.add(pair.alt);
  7609. if (! complete) {
  7610. break;
  7611. }
  7612. }
  7613. }
  7614. return predictions;
  7615. };
  7616. // TODO: If we are doing predicates, there is no point in pursuing
  7617. // closure operations if we reach a DFA state that uniquely predicts
  7618. // alternative. We will not be caching that DFA state and it is a
  7619. // waste to pursue the closure. Might have to advance when we do
  7620. // ambig detection thought :(
  7621. //
  7622. ParserATNSimulator.prototype.closure = function(config, configs, closureBusy, collectPredicates, fullCtx, treatEofAsEpsilon) {
  7623. var initialDepth = 0;
  7624. this.closureCheckingStopState(config, configs, closureBusy, collectPredicates,
  7625. fullCtx, initialDepth, treatEofAsEpsilon);
  7626. };
  7627. ParserATNSimulator.prototype.closureCheckingStopState = function(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
  7628. if (this.debug || this.debug_closure) {
  7629. console.log("closure(" + config.toString(this.parser,true) + ")");
  7630. // console.log("configs(" + configs.toString() + ")");
  7631. if(config.reachesIntoOuterContext>50) {
  7632. throw "problem";
  7633. }
  7634. }
  7635. if (config.state instanceof RuleStopState) {
  7636. // We hit rule end. If we have context info, use it
  7637. // run thru all possible stack tops in ctx
  7638. if (! config.context.isEmpty()) {
  7639. for ( var i =0; i<config.context.length; i++) {
  7640. if (config.context.getReturnState(i) === PredictionContext.EMPTY_RETURN_STATE) {
  7641. if (fullCtx) {
  7642. configs.add(new ATNConfig({state:config.state, context:PredictionContext.EMPTY}, config), this.mergeCache);
  7643. continue;
  7644. } else {
  7645. // we have no context info, just chase follow links (if greedy)
  7646. if (this.debug) {
  7647. console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
  7648. }
  7649. this.closure_(config, configs, closureBusy, collectPredicates,
  7650. fullCtx, depth, treatEofAsEpsilon);
  7651. }
  7652. continue;
  7653. }
  7654. var returnState = this.atn.states[config.context.getReturnState(i)];
  7655. var newContext = config.context.getParent(i); // "pop" return state
  7656. var parms = {state:returnState, alt:config.alt, context:newContext, semanticContext:config.semanticContext};
  7657. var c = new ATNConfig(parms, null);
  7658. // While we have context to pop back from, we may have
  7659. // gotten that context AFTER having falling off a rule.
  7660. // Make sure we track that we are now out of context.
  7661. c.reachesIntoOuterContext = config.reachesIntoOuterContext;
  7662. this.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1, treatEofAsEpsilon);
  7663. }
  7664. return;
  7665. } else if( fullCtx) {
  7666. // reached end of start rule
  7667. configs.add(config, this.mergeCache);
  7668. return;
  7669. } else {
  7670. // else if we have no context info, just chase follow links (if greedy)
  7671. if (this.debug) {
  7672. console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
  7673. }
  7674. }
  7675. }
  7676. this.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon);
  7677. };
  7678. // Do the actual work of walking epsilon edges//
  7679. ParserATNSimulator.prototype.closure_ = function(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
  7680. var p = config.state;
  7681. // optimization
  7682. if (! p.epsilonOnlyTransitions) {
  7683. configs.add(config, this.mergeCache);
  7684. // make sure to not return here, because EOF transitions can act as
  7685. // both epsilon transitions and non-epsilon transitions.
  7686. }
  7687. for(var i = 0;i<p.transitions.length; i++) {
  7688. if(i==0 && this.canDropLoopEntryEdgeInLeftRecursiveRule(config))
  7689. continue;
  7690. var t = p.transitions[i];
  7691. var continueCollecting = collectPredicates && !(t instanceof ActionTransition);
  7692. var c = this.getEpsilonTarget(config, t, continueCollecting, depth === 0, fullCtx, treatEofAsEpsilon);
  7693. if (c!==null) {
  7694. var newDepth = depth;
  7695. if ( config.state instanceof RuleStopState) {
  7696. // target fell off end of rule; mark resulting c as having dipped into outer context
  7697. // We can't get here if incoming config was rule stop and we had context
  7698. // track how far we dip into outer context. Might
  7699. // come in handy and we avoid evaluating context dependent
  7700. // preds if this is > 0.
  7701. if (this._dfa !== null && this._dfa.precedenceDfa) {
  7702. if (t.outermostPrecedenceReturn === this._dfa.atnStartState.ruleIndex) {
  7703. c.precedenceFilterSuppressed = true;
  7704. }
  7705. }
  7706. c.reachesIntoOuterContext += 1;
  7707. if (closureBusy.add(c)!==c) {
  7708. // avoid infinite recursion for right-recursive rules
  7709. continue;
  7710. }
  7711. configs.dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method
  7712. newDepth -= 1;
  7713. if (this.debug) {
  7714. console.log("dips into outer ctx: " + c);
  7715. }
  7716. } else {
  7717. if (!t.isEpsilon && closureBusy.add(c)!==c){
  7718. // avoid infinite recursion for EOF* and EOF+
  7719. continue;
  7720. }
  7721. if (t instanceof RuleTransition) {
  7722. // latch when newDepth goes negative - once we step out of the entry context we can't return
  7723. if (newDepth >= 0) {
  7724. newDepth += 1;
  7725. }
  7726. }
  7727. }
  7728. this.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEofAsEpsilon);
  7729. }
  7730. }
  7731. };
  7732. ParserATNSimulator.prototype.canDropLoopEntryEdgeInLeftRecursiveRule = function(config) {
  7733. // return False
  7734. var p = config.state;
  7735. // First check to see if we are in StarLoopEntryState generated during
  7736. // left-recursion elimination. For efficiency, also check if
  7737. // the context has an empty stack case. If so, it would mean
  7738. // global FOLLOW so we can't perform optimization
  7739. // Are we the special loop entry/exit state? or SLL wildcard
  7740. if(p.stateType != ATNState.STAR_LOOP_ENTRY)
  7741. return false;
  7742. if(p.stateType != ATNState.STAR_LOOP_ENTRY || !p.isPrecedenceDecision ||
  7743. config.context.isEmpty() || config.context.hasEmptyPath())
  7744. return false;
  7745. // Require all return states to return back to the same rule that p is in.
  7746. var numCtxs = config.context.length;
  7747. for(var i=0; i<numCtxs; i++) { // for each stack context
  7748. var returnState = this.atn.states[config.context.getReturnState(i)];
  7749. if (returnState.ruleIndex != p.ruleIndex)
  7750. return false;
  7751. }
  7752. var decisionStartState = p.transitions[0].target;
  7753. var blockEndStateNum = decisionStartState.endState.stateNumber;
  7754. var blockEndState = this.atn.states[blockEndStateNum];
  7755. // Verify that the top of each stack context leads to loop entry/exit
  7756. // state through epsilon edges and w/o leaving rule.
  7757. for(var i=0; i<numCtxs; i++) { // for each stack context
  7758. var returnStateNumber = config.context.getReturnState(i);
  7759. var returnState = this.atn.states[returnStateNumber];
  7760. // all states must have single outgoing epsilon edge
  7761. if (returnState.transitions.length != 1 || !returnState.transitions[0].isEpsilon)
  7762. return false;
  7763. // Look for prefix op case like 'not expr', (' type ')' expr
  7764. var returnStateTarget = returnState.transitions[0].target;
  7765. if ( returnState.stateType == ATNState.BLOCK_END && returnStateTarget == p )
  7766. continue;
  7767. // Look for 'expr op expr' or case where expr's return state is block end
  7768. // of (...)* internal block; the block end points to loop back
  7769. // which points to p but we don't need to check that
  7770. if ( returnState == blockEndState )
  7771. continue;
  7772. // Look for ternary expr ? expr : expr. The return state points at block end,
  7773. // which points at loop entry state
  7774. if ( returnStateTarget == blockEndState )
  7775. continue;
  7776. // Look for complex prefix 'between expr and expr' case where 2nd expr's
  7777. // return state points at block end state of (...)* internal block
  7778. if (returnStateTarget.stateType == ATNState.BLOCK_END && returnStateTarget.transitions.length == 1
  7779. && returnStateTarget.transitions[0].isEpsilon && returnStateTarget.transitions[0].target == p)
  7780. continue;
  7781. // anything else ain't conforming
  7782. return false;
  7783. }
  7784. return true;
  7785. };
  7786. ParserATNSimulator.prototype.getRuleName = function( index) {
  7787. if (this.parser!==null && index>=0) {
  7788. return this.parser.ruleNames[index];
  7789. } else {
  7790. return "<rule " + index + ">";
  7791. }
  7792. };
  7793. ParserATNSimulator.prototype.getEpsilonTarget = function(config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon) {
  7794. switch(t.serializationType) {
  7795. case Transition.RULE:
  7796. return this.ruleTransition(config, t);
  7797. case Transition.PRECEDENCE:
  7798. return this.precedenceTransition(config, t, collectPredicates, inContext, fullCtx);
  7799. case Transition.PREDICATE:
  7800. return this.predTransition(config, t, collectPredicates, inContext, fullCtx);
  7801. case Transition.ACTION:
  7802. return this.actionTransition(config, t);
  7803. case Transition.EPSILON:
  7804. return new ATNConfig({state:t.target}, config);
  7805. case Transition.ATOM:
  7806. case Transition.RANGE:
  7807. case Transition.SET:
  7808. // EOF transitions act like epsilon transitions after the first EOF
  7809. // transition is traversed
  7810. if (treatEofAsEpsilon) {
  7811. if (t.matches(Token.EOF, 0, 1)) {
  7812. return new ATNConfig({state: t.target}, config);
  7813. }
  7814. }
  7815. return null;
  7816. default:
  7817. return null;
  7818. }
  7819. };
  7820. ParserATNSimulator.prototype.actionTransition = function(config, t) {
  7821. if (this.debug) {
  7822. var index = t.actionIndex==-1 ? 65535 : t.actionIndex;
  7823. console.log("ACTION edge " + t.ruleIndex + ":" + index);
  7824. }
  7825. return new ATNConfig({state:t.target}, config);
  7826. };
  7827. ParserATNSimulator.prototype.precedenceTransition = function(config, pt, collectPredicates, inContext, fullCtx) {
  7828. if (this.debug) {
  7829. console.log("PRED (collectPredicates=" + collectPredicates + ") " +
  7830. pt.precedence + ">=_p, ctx dependent=true");
  7831. if (this.parser!==null) {
  7832. console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
  7833. }
  7834. }
  7835. var c = null;
  7836. if (collectPredicates && inContext) {
  7837. if (fullCtx) {
  7838. // In full context mode, we can evaluate predicates on-the-fly
  7839. // during closure, which dramatically reduces the size of
  7840. // the config sets. It also obviates the need to test predicates
  7841. // later during conflict resolution.
  7842. var currentPosition = this._input.index;
  7843. this._input.seek(this._startIndex);
  7844. var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
  7845. this._input.seek(currentPosition);
  7846. if (predSucceeds) {
  7847. c = new ATNConfig({state:pt.target}, config); // no pred context
  7848. }
  7849. } else {
  7850. var newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
  7851. c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);
  7852. }
  7853. } else {
  7854. c = new ATNConfig({state:pt.target}, config);
  7855. }
  7856. if (this.debug) {
  7857. console.log("config from pred transition=" + c);
  7858. }
  7859. return c;
  7860. };
  7861. ParserATNSimulator.prototype.predTransition = function(config, pt, collectPredicates, inContext, fullCtx) {
  7862. if (this.debug) {
  7863. console.log("PRED (collectPredicates=" + collectPredicates + ") " + pt.ruleIndex +
  7864. ":" + pt.predIndex + ", ctx dependent=" + pt.isCtxDependent);
  7865. if (this.parser!==null) {
  7866. console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
  7867. }
  7868. }
  7869. var c = null;
  7870. if (collectPredicates && ((pt.isCtxDependent && inContext) || ! pt.isCtxDependent)) {
  7871. if (fullCtx) {
  7872. // In full context mode, we can evaluate predicates on-the-fly
  7873. // during closure, which dramatically reduces the size of
  7874. // the config sets. It also obviates the need to test predicates
  7875. // later during conflict resolution.
  7876. var currentPosition = this._input.index;
  7877. this._input.seek(this._startIndex);
  7878. var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
  7879. this._input.seek(currentPosition);
  7880. if (predSucceeds) {
  7881. c = new ATNConfig({state:pt.target}, config); // no pred context
  7882. }
  7883. } else {
  7884. var newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
  7885. c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);
  7886. }
  7887. } else {
  7888. c = new ATNConfig({state:pt.target}, config);
  7889. }
  7890. if (this.debug) {
  7891. console.log("config from pred transition=" + c);
  7892. }
  7893. return c;
  7894. };
  7895. ParserATNSimulator.prototype.ruleTransition = function(config, t) {
  7896. if (this.debug) {
  7897. console.log("CALL rule " + this.getRuleName(t.target.ruleIndex) + ", ctx=" + config.context);
  7898. }
  7899. var returnState = t.followState;
  7900. var newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber);
  7901. return new ATNConfig({state:t.target, context:newContext}, config );
  7902. };
  7903. ParserATNSimulator.prototype.getConflictingAlts = function(configs) {
  7904. var altsets = PredictionMode.getConflictingAltSubsets(configs);
  7905. return PredictionMode.getAlts(altsets);
  7906. };
  7907. // Sam pointed out a problem with the previous definition, v3, of
  7908. // ambiguous states. If we have another state associated with conflicting
  7909. // alternatives, we should keep going. For example, the following grammar
  7910. //
  7911. // s : (ID | ID ID?) ';' ;
  7912. //
  7913. // When the ATN simulation reaches the state before ';', it has a DFA
  7914. // state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally
  7915. // 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node
  7916. // because alternative to has another way to continue, via [6|2|[]].
  7917. // The key is that we have a single state that has config's only associated
  7918. // with a single alternative, 2, and crucially the state transitions
  7919. // among the configurations are all non-epsilon transitions. That means
  7920. // we don't consider any conflicts that include alternative 2. So, we
  7921. // ignore the conflict between alts 1 and 2. We ignore a set of
  7922. // conflicting alts when there is an intersection with an alternative
  7923. // associated with a single alt state in the state&rarr;config-list map.
  7924. //
  7925. // It's also the case that we might have two conflicting configurations but
  7926. // also a 3rd nonconflicting configuration for a different alternative:
  7927. // [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:
  7928. //
  7929. // a : A | A | A B ;
  7930. //
  7931. // After matching input A, we reach the stop state for rule A, state 1.
  7932. // State 8 is the state right before B. Clearly alternatives 1 and 2
  7933. // conflict and no amount of further lookahead will separate the two.
  7934. // However, alternative 3 will be able to continue and so we do not
  7935. // stop working on this state. In the previous example, we're concerned
  7936. // with states associated with the conflicting alternatives. Here alt
  7937. // 3 is not associated with the conflicting configs, but since we can continue
  7938. // looking for input reasonably, I don't declare the state done. We
  7939. // ignore a set of conflicting alts when we have an alternative
  7940. // that we still need to pursue.
  7941. //
  7942. ParserATNSimulator.prototype.getConflictingAltsOrUniqueAlt = function(configs) {
  7943. var conflictingAlts = null;
  7944. if (configs.uniqueAlt!== ATN.INVALID_ALT_NUMBER) {
  7945. conflictingAlts = new BitSet();
  7946. conflictingAlts.add(configs.uniqueAlt);
  7947. } else {
  7948. conflictingAlts = configs.conflictingAlts;
  7949. }
  7950. return conflictingAlts;
  7951. };
  7952. ParserATNSimulator.prototype.getTokenName = function( t) {
  7953. if (t===Token.EOF) {
  7954. return "EOF";
  7955. }
  7956. if( this.parser!==null && this.parser.literalNames!==null) {
  7957. if (t >= this.parser.literalNames.length && t >= this.parser.symbolicNames.length) {
  7958. console.log("" + t + " ttype out of range: " + this.parser.literalNames);
  7959. console.log("" + this.parser.getInputStream().getTokens());
  7960. } else {
  7961. var name = this.parser.literalNames[t] || this.parser.symbolicNames[t];
  7962. return name + "<" + t + ">";
  7963. }
  7964. }
  7965. return "" + t;
  7966. };
  7967. ParserATNSimulator.prototype.getLookaheadName = function(input) {
  7968. return this.getTokenName(input.LA(1));
  7969. };
  7970. // Used for debugging in adaptivePredict around execATN but I cut
  7971. // it out for clarity now that alg. works well. We can leave this
  7972. // "dead" code for a bit.
  7973. //
  7974. ParserATNSimulator.prototype.dumpDeadEndConfigs = function(nvae) {
  7975. console.log("dead end configs: ");
  7976. var decs = nvae.getDeadEndConfigs();
  7977. for(var i=0; i<decs.length; i++) {
  7978. var c = decs[i];
  7979. var trans = "no edges";
  7980. if (c.state.transitions.length>0) {
  7981. var t = c.state.transitions[0];
  7982. if (t instanceof AtomTransition) {
  7983. trans = "Atom "+ this.getTokenName(t.label);
  7984. } else if (t instanceof SetTransition) {
  7985. var neg = (t instanceof NotSetTransition);
  7986. trans = (neg ? "~" : "") + "Set " + t.set;
  7987. }
  7988. }
  7989. console.error(c.toString(this.parser, true) + ":" + trans);
  7990. }
  7991. };
  7992. ParserATNSimulator.prototype.noViableAlt = function(input, outerContext, configs, startIndex) {
  7993. return new NoViableAltException(this.parser, input, input.get(startIndex), input.LT(1), configs, outerContext);
  7994. };
  7995. ParserATNSimulator.prototype.getUniqueAlt = function(configs) {
  7996. var alt = ATN.INVALID_ALT_NUMBER;
  7997. for(var i=0;i<configs.items.length;i++) {
  7998. var c = configs.items[i];
  7999. if (alt === ATN.INVALID_ALT_NUMBER) {
  8000. alt = c.alt // found first alt
  8001. } else if( c.alt!==alt) {
  8002. return ATN.INVALID_ALT_NUMBER;
  8003. }
  8004. }
  8005. return alt;
  8006. };
  8007. //
  8008. // Add an edge to the DFA, if possible. This method calls
  8009. // {@link //addDFAState} to ensure the {@code to} state is present in the
  8010. // DFA. If {@code from} is {@code null}, or if {@code t} is outside the
  8011. // range of edges that can be represented in the DFA tables, this method
  8012. // returns without adding the edge to the DFA.
  8013. //
  8014. // <p>If {@code to} is {@code null}, this method returns {@code null}.
  8015. // Otherwise, this method returns the {@link DFAState} returned by calling
  8016. // {@link //addDFAState} for the {@code to} state.</p>
  8017. //
  8018. // @param dfa The DFA
  8019. // @param from The source state for the edge
  8020. // @param t The input symbol
  8021. // @param to The target state for the edge
  8022. //
  8023. // @return If {@code to} is {@code null}, this method returns {@code null};
  8024. // otherwise this method returns the result of calling {@link //addDFAState}
  8025. // on {@code to}
  8026. //
  8027. ParserATNSimulator.prototype.addDFAEdge = function(dfa, from_, t, to) {
  8028. if( this.debug) {
  8029. console.log("EDGE " + from_ + " -> " + to + " upon " + this.getTokenName(t));
  8030. }
  8031. if (to===null) {
  8032. return null;
  8033. }
  8034. to = this.addDFAState(dfa, to); // used existing if possible not incoming
  8035. if (from_===null || t < -1 || t > this.atn.maxTokenType) {
  8036. return to;
  8037. }
  8038. if (from_.edges===null) {
  8039. from_.edges = [];
  8040. }
  8041. from_.edges[t+1] = to; // connect
  8042. if (this.debug) {
  8043. var literalNames = this.parser===null ? null : this.parser.literalNames;
  8044. var symbolicNames = this.parser===null ? null : this.parser.symbolicNames;
  8045. console.log("DFA=\n" + dfa.toString(literalNames, symbolicNames));
  8046. }
  8047. return to;
  8048. };
  8049. //
  8050. // Add state {@code D} to the DFA if it is not already present, and return
  8051. // the actual instance stored in the DFA. If a state equivalent to {@code D}
  8052. // is already in the DFA, the existing state is returned. Otherwise this
  8053. // method returns {@code D} after adding it to the DFA.
  8054. //
  8055. // <p>If {@code D} is {@link //ERROR}, this method returns {@link //ERROR} and
  8056. // does not change the DFA.</p>
  8057. //
  8058. // @param dfa The dfa
  8059. // @param D The DFA state to add
  8060. // @return The state stored in the DFA. This will be either the existing
  8061. // state if {@code D} is already in the DFA, or {@code D} itself if the
  8062. // state was not already present.
  8063. //
  8064. ParserATNSimulator.prototype.addDFAState = function(dfa, D) {
  8065. if (D == ATNSimulator.ERROR) {
  8066. return D;
  8067. }
  8068. var existing = dfa.states.get(D);
  8069. if(existing!==null) {
  8070. return existing;
  8071. }
  8072. D.stateNumber = dfa.states.length;
  8073. if (! D.configs.readOnly) {
  8074. D.configs.optimizeConfigs(this);
  8075. D.configs.setReadonly(true);
  8076. }
  8077. dfa.states.add(D);
  8078. if (this.debug) {
  8079. console.log("adding new DFA state: " + D);
  8080. }
  8081. return D;
  8082. };
  8083. ParserATNSimulator.prototype.reportAttemptingFullContext = function(dfa, conflictingAlts, configs, startIndex, stopIndex) {
  8084. if (this.debug || this.retry_debug) {
  8085. var interval = new Interval(startIndex, stopIndex + 1);
  8086. console.log("reportAttemptingFullContext decision=" + dfa.decision + ":" + configs +
  8087. ", input=" + this.parser.getTokenStream().getText(interval));
  8088. }
  8089. if (this.parser!==null) {
  8090. this.parser.getErrorListenerDispatch().reportAttemptingFullContext(this.parser, dfa, startIndex, stopIndex, conflictingAlts, configs);
  8091. }
  8092. };
  8093. ParserATNSimulator.prototype.reportContextSensitivity = function(dfa, prediction, configs, startIndex, stopIndex) {
  8094. if (this.debug || this.retry_debug) {
  8095. var interval = new Interval(startIndex, stopIndex + 1);
  8096. console.log("reportContextSensitivity decision=" + dfa.decision + ":" + configs +
  8097. ", input=" + this.parser.getTokenStream().getText(interval));
  8098. }
  8099. if (this.parser!==null) {
  8100. this.parser.getErrorListenerDispatch().reportContextSensitivity(this.parser, dfa, startIndex, stopIndex, prediction, configs);
  8101. }
  8102. };
  8103. // If context sensitive parsing, we know it's ambiguity not conflict//
  8104. ParserATNSimulator.prototype.reportAmbiguity = function(dfa, D, startIndex, stopIndex,
  8105. exact, ambigAlts, configs ) {
  8106. if (this.debug || this.retry_debug) {
  8107. var interval = new Interval(startIndex, stopIndex + 1);
  8108. console.log("reportAmbiguity " + ambigAlts + ":" + configs +
  8109. ", input=" + this.parser.getTokenStream().getText(interval));
  8110. }
  8111. if (this.parser!==null) {
  8112. this.parser.getErrorListenerDispatch().reportAmbiguity(this.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs);
  8113. }
  8114. };
  8115. exports.ParserATNSimulator = ParserATNSimulator;
  8116. /***/ }),
  8117. /***/ "./node_modules/antlr4/atn/PredictionMode.js":
  8118. /*!***************************************************!*\
  8119. !*** ./node_modules/antlr4/atn/PredictionMode.js ***!
  8120. \***************************************************/
  8121. /*! no static exports found */
  8122. /***/ (function(module, exports, __webpack_require__) {
  8123. //
  8124. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  8125. * Use of this file is governed by the BSD 3-clause license that
  8126. * can be found in the LICENSE.txt file in the project root.
  8127. */
  8128. //
  8129. //
  8130. // This enumeration defines the prediction modes available in ANTLR 4 along with
  8131. // utility methods for analyzing configuration sets for conflicts and/or
  8132. // ambiguities.
  8133. var Set = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Set;
  8134. var Map = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Map;
  8135. var BitSet = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").BitSet;
  8136. var AltDict = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").AltDict;
  8137. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  8138. var RuleStopState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
  8139. var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  8140. var ATNConfig = __webpack_require__(/*! ./ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").ATNConfig;
  8141. var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
  8142. var Hash = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").Hash;
  8143. var hashStuff = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").hashStuff;
  8144. var equalArrays = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").equalArrays;
  8145. function PredictionMode() {
  8146. return this;
  8147. }
  8148. //
  8149. // The SLL(*) prediction mode. This prediction mode ignores the current
  8150. // parser context when making predictions. This is the fastest prediction
  8151. // mode, and provides correct results for many grammars. This prediction
  8152. // mode is more powerful than the prediction mode provided by ANTLR 3, but
  8153. // may result in syntax errors for grammar and input combinations which are
  8154. // not SLL.
  8155. //
  8156. // <p>
  8157. // When using this prediction mode, the parser will either return a correct
  8158. // parse tree (i.e. the same parse tree that would be returned with the
  8159. // {@link //LL} prediction mode), or it will report a syntax error. If a
  8160. // syntax error is encountered when using the {@link //SLL} prediction mode,
  8161. // it may be due to either an actual syntax error in the input or indicate
  8162. // that the particular combination of grammar and input requires the more
  8163. // powerful {@link //LL} prediction abilities to complete successfully.</p>
  8164. //
  8165. // <p>
  8166. // This prediction mode does not provide any guarantees for prediction
  8167. // behavior for syntactically-incorrect inputs.</p>
  8168. //
  8169. PredictionMode.SLL = 0;
  8170. //
  8171. // The LL(*) prediction mode. This prediction mode allows the current parser
  8172. // context to be used for resolving SLL conflicts that occur during
  8173. // prediction. This is the fastest prediction mode that guarantees correct
  8174. // parse results for all combinations of grammars with syntactically correct
  8175. // inputs.
  8176. //
  8177. // <p>
  8178. // When using this prediction mode, the parser will make correct decisions
  8179. // for all syntactically-correct grammar and input combinations. However, in
  8180. // cases where the grammar is truly ambiguous this prediction mode might not
  8181. // report a precise answer for <em>exactly which</em> alternatives are
  8182. // ambiguous.</p>
  8183. //
  8184. // <p>
  8185. // This prediction mode does not provide any guarantees for prediction
  8186. // behavior for syntactically-incorrect inputs.</p>
  8187. //
  8188. PredictionMode.LL = 1;
  8189. //
  8190. // The LL(*) prediction mode with exact ambiguity detection. In addition to
  8191. // the correctness guarantees provided by the {@link //LL} prediction mode,
  8192. // this prediction mode instructs the prediction algorithm to determine the
  8193. // complete and exact set of ambiguous alternatives for every ambiguous
  8194. // decision encountered while parsing.
  8195. //
  8196. // <p>
  8197. // This prediction mode may be used for diagnosing ambiguities during
  8198. // grammar development. Due to the performance overhead of calculating sets
  8199. // of ambiguous alternatives, this prediction mode should be avoided when
  8200. // the exact results are not necessary.</p>
  8201. //
  8202. // <p>
  8203. // This prediction mode does not provide any guarantees for prediction
  8204. // behavior for syntactically-incorrect inputs.</p>
  8205. //
  8206. PredictionMode.LL_EXACT_AMBIG_DETECTION = 2;
  8207. //
  8208. // Computes the SLL prediction termination condition.
  8209. //
  8210. // <p>
  8211. // This method computes the SLL prediction termination condition for both of
  8212. // the following cases.</p>
  8213. //
  8214. // <ul>
  8215. // <li>The usual SLL+LL fallback upon SLL conflict</li>
  8216. // <li>Pure SLL without LL fallback</li>
  8217. // </ul>
  8218. //
  8219. // <p><strong>COMBINED SLL+LL PARSING</strong></p>
  8220. //
  8221. // <p>When LL-fallback is enabled upon SLL conflict, correct predictions are
  8222. // ensured regardless of how the termination condition is computed by this
  8223. // method. Due to the substantially higher cost of LL prediction, the
  8224. // prediction should only fall back to LL when the additional lookahead
  8225. // cannot lead to a unique SLL prediction.</p>
  8226. //
  8227. // <p>Assuming combined SLL+LL parsing, an SLL configuration set with only
  8228. // conflicting subsets should fall back to full LL, even if the
  8229. // configuration sets don't resolve to the same alternative (e.g.
  8230. // {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting
  8231. // configuration, SLL could continue with the hopes that more lookahead will
  8232. // resolve via one of those non-conflicting configurations.</p>
  8233. //
  8234. // <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)
  8235. // stops when it sees only conflicting configuration subsets. In contrast,
  8236. // full LL keeps going when there is uncertainty.</p>
  8237. //
  8238. // <p><strong>HEURISTIC</strong></p>
  8239. //
  8240. // <p>As a heuristic, we stop prediction when we see any conflicting subset
  8241. // unless we see a state that only has one alternative associated with it.
  8242. // The single-alt-state thing lets prediction continue upon rules like
  8243. // (otherwise, it would admit defeat too soon):</p>
  8244. //
  8245. // <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p>
  8246. //
  8247. // <p>When the ATN simulation reaches the state before {@code ';'}, it has a
  8248. // DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally
  8249. // {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop
  8250. // processing this node because alternative to has another way to continue,
  8251. // via {@code [6|2|[]]}.</p>
  8252. //
  8253. // <p>It also let's us continue for this rule:</p>
  8254. //
  8255. // <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p>
  8256. //
  8257. // <p>After matching input A, we reach the stop state for rule A, state 1.
  8258. // State 8 is the state right before B. Clearly alternatives 1 and 2
  8259. // conflict and no amount of further lookahead will separate the two.
  8260. // However, alternative 3 will be able to continue and so we do not stop
  8261. // working on this state. In the previous example, we're concerned with
  8262. // states associated with the conflicting alternatives. Here alt 3 is not
  8263. // associated with the conflicting configs, but since we can continue
  8264. // looking for input reasonably, don't declare the state done.</p>
  8265. //
  8266. // <p><strong>PURE SLL PARSING</strong></p>
  8267. //
  8268. // <p>To handle pure SLL parsing, all we have to do is make sure that we
  8269. // combine stack contexts for configurations that differ only by semantic
  8270. // predicate. From there, we can do the usual SLL termination heuristic.</p>
  8271. //
  8272. // <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>
  8273. //
  8274. // <p>SLL decisions don't evaluate predicates until after they reach DFA stop
  8275. // states because they need to create the DFA cache that works in all
  8276. // semantic situations. In contrast, full LL evaluates predicates collected
  8277. // during start state computation so it can ignore predicates thereafter.
  8278. // This means that SLL termination detection can totally ignore semantic
  8279. // predicates.</p>
  8280. //
  8281. // <p>Implementation-wise, {@link ATNConfigSet} combines stack contexts but not
  8282. // semantic predicate contexts so we might see two configurations like the
  8283. // following.</p>
  8284. //
  8285. // <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p>
  8286. //
  8287. // <p>Before testing these configurations against others, we have to merge
  8288. // {@code x} and {@code x'} (without modifying the existing configurations).
  8289. // For example, we test {@code (x+x')==x''} when looking for conflicts in
  8290. // the following configurations.</p>
  8291. //
  8292. // <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p>
  8293. //
  8294. // <p>If the configuration set has predicates (as indicated by
  8295. // {@link ATNConfigSet//hasSemanticContext}), this algorithm makes a copy of
  8296. // the configurations to strip out all of the predicates so that a standard
  8297. // {@link ATNConfigSet} will merge everything ignoring predicates.</p>
  8298. //
  8299. PredictionMode.hasSLLConflictTerminatingPrediction = function( mode, configs) {
  8300. // Configs in rule stop states indicate reaching the end of the decision
  8301. // rule (local context) or end of start rule (full context). If all
  8302. // configs meet this condition, then none of the configurations is able
  8303. // to match additional input so we terminate prediction.
  8304. //
  8305. if (PredictionMode.allConfigsInRuleStopStates(configs)) {
  8306. return true;
  8307. }
  8308. // pure SLL mode parsing
  8309. if (mode === PredictionMode.SLL) {
  8310. // Don't bother with combining configs from different semantic
  8311. // contexts if we can fail over to full LL; costs more time
  8312. // since we'll often fail over anyway.
  8313. if (configs.hasSemanticContext) {
  8314. // dup configs, tossing out semantic predicates
  8315. var dup = new ATNConfigSet();
  8316. for(var i=0;i<configs.items.length;i++) {
  8317. var c = configs.items[i];
  8318. c = new ATNConfig({semanticContext:SemanticContext.NONE}, c);
  8319. dup.add(c);
  8320. }
  8321. configs = dup;
  8322. }
  8323. // now we have combined contexts for configs with dissimilar preds
  8324. }
  8325. // pure SLL or combined SLL+LL mode parsing
  8326. var altsets = PredictionMode.getConflictingAltSubsets(configs);
  8327. return PredictionMode.hasConflictingAltSet(altsets) && !PredictionMode.hasStateAssociatedWithOneAlt(configs);
  8328. };
  8329. // Checks if any configuration in {@code configs} is in a
  8330. // {@link RuleStopState}. Configurations meeting this condition have reached
  8331. // the end of the decision rule (local context) or end of start rule (full
  8332. // context).
  8333. //
  8334. // @param configs the configuration set to test
  8335. // @return {@code true} if any configuration in {@code configs} is in a
  8336. // {@link RuleStopState}, otherwise {@code false}
  8337. PredictionMode.hasConfigInRuleStopState = function(configs) {
  8338. for(var i=0;i<configs.items.length;i++) {
  8339. var c = configs.items[i];
  8340. if (c.state instanceof RuleStopState) {
  8341. return true;
  8342. }
  8343. }
  8344. return false;
  8345. };
  8346. // Checks if all configurations in {@code configs} are in a
  8347. // {@link RuleStopState}. Configurations meeting this condition have reached
  8348. // the end of the decision rule (local context) or end of start rule (full
  8349. // context).
  8350. //
  8351. // @param configs the configuration set to test
  8352. // @return {@code true} if all configurations in {@code configs} are in a
  8353. // {@link RuleStopState}, otherwise {@code false}
  8354. PredictionMode.allConfigsInRuleStopStates = function(configs) {
  8355. for(var i=0;i<configs.items.length;i++) {
  8356. var c = configs.items[i];
  8357. if (!(c.state instanceof RuleStopState)) {
  8358. return false;
  8359. }
  8360. }
  8361. return true;
  8362. };
  8363. //
  8364. // Full LL prediction termination.
  8365. //
  8366. // <p>Can we stop looking ahead during ATN simulation or is there some
  8367. // uncertainty as to which alternative we will ultimately pick, after
  8368. // consuming more input? Even if there are partial conflicts, we might know
  8369. // that everything is going to resolve to the same minimum alternative. That
  8370. // means we can stop since no more lookahead will change that fact. On the
  8371. // other hand, there might be multiple conflicts that resolve to different
  8372. // minimums. That means we need more look ahead to decide which of those
  8373. // alternatives we should predict.</p>
  8374. //
  8375. // <p>The basic idea is to split the set of configurations {@code C}, into
  8376. // conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with
  8377. // non-conflicting configurations. Two configurations conflict if they have
  8378. // identical {@link ATNConfig//state} and {@link ATNConfig//context} values
  8379. // but different {@link ATNConfig//alt} value, e.g. {@code (s, i, ctx, _)}
  8380. // and {@code (s, j, ctx, _)} for {@code i!=j}.</p>
  8381. //
  8382. // <p>Reduce these configuration subsets to the set of possible alternatives.
  8383. // You can compute the alternative subsets in one pass as follows:</p>
  8384. //
  8385. // <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in
  8386. // {@code C} holding {@code s} and {@code ctx} fixed.</p>
  8387. //
  8388. // <p>Or in pseudo-code, for each configuration {@code c} in {@code C}:</p>
  8389. //
  8390. // <pre>
  8391. // map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not
  8392. // alt and not pred
  8393. // </pre>
  8394. //
  8395. // <p>The values in {@code map} are the set of {@code A_s,ctx} sets.</p>
  8396. //
  8397. // <p>If {@code |A_s,ctx|=1} then there is no conflict associated with
  8398. // {@code s} and {@code ctx}.</p>
  8399. //
  8400. // <p>Reduce the subsets to singletons by choosing a minimum of each subset. If
  8401. // the union of these alternative subsets is a singleton, then no amount of
  8402. // more lookahead will help us. We will always pick that alternative. If,
  8403. // however, there is more than one alternative, then we are uncertain which
  8404. // alternative to predict and must continue looking for resolution. We may
  8405. // or may not discover an ambiguity in the future, even if there are no
  8406. // conflicting subsets this round.</p>
  8407. //
  8408. // <p>The biggest sin is to terminate early because it means we've made a
  8409. // decision but were uncertain as to the eventual outcome. We haven't used
  8410. // enough lookahead. On the other hand, announcing a conflict too late is no
  8411. // big deal; you will still have the conflict. It's just inefficient. It
  8412. // might even look until the end of file.</p>
  8413. //
  8414. // <p>No special consideration for semantic predicates is required because
  8415. // predicates are evaluated on-the-fly for full LL prediction, ensuring that
  8416. // no configuration contains a semantic context during the termination
  8417. // check.</p>
  8418. //
  8419. // <p><strong>CONFLICTING CONFIGS</strong></p>
  8420. //
  8421. // <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict
  8422. // when {@code i!=j} but {@code x=x'}. Because we merge all
  8423. // {@code (s, i, _)} configurations together, that means that there are at
  8424. // most {@code n} configurations associated with state {@code s} for
  8425. // {@code n} possible alternatives in the decision. The merged stacks
  8426. // complicate the comparison of configuration contexts {@code x} and
  8427. // {@code x'}. Sam checks to see if one is a subset of the other by calling
  8428. // merge and checking to see if the merged result is either {@code x} or
  8429. // {@code x'}. If the {@code x} associated with lowest alternative {@code i}
  8430. // is the superset, then {@code i} is the only possible prediction since the
  8431. // others resolve to {@code min(i)} as well. However, if {@code x} is
  8432. // associated with {@code j>i} then at least one stack configuration for
  8433. // {@code j} is not in conflict with alternative {@code i}. The algorithm
  8434. // should keep going, looking for more lookahead due to the uncertainty.</p>
  8435. //
  8436. // <p>For simplicity, I'm doing a equality check between {@code x} and
  8437. // {@code x'} that lets the algorithm continue to consume lookahead longer
  8438. // than necessary. The reason I like the equality is of course the
  8439. // simplicity but also because that is the test you need to detect the
  8440. // alternatives that are actually in conflict.</p>
  8441. //
  8442. // <p><strong>CONTINUE/STOP RULE</strong></p>
  8443. //
  8444. // <p>Continue if union of resolved alternative sets from non-conflicting and
  8445. // conflicting alternative subsets has more than one alternative. We are
  8446. // uncertain about which alternative to predict.</p>
  8447. //
  8448. // <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which
  8449. // alternatives are still in the running for the amount of input we've
  8450. // consumed at this point. The conflicting sets let us to strip away
  8451. // configurations that won't lead to more states because we resolve
  8452. // conflicts to the configuration with a minimum alternate for the
  8453. // conflicting set.</p>
  8454. //
  8455. // <p><strong>CASES</strong></p>
  8456. //
  8457. // <ul>
  8458. //
  8459. // <li>no conflicts and more than 1 alternative in set =&gt; continue</li>
  8460. //
  8461. // <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},
  8462. // {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set
  8463. // {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
  8464. // {@code {1,3}} =&gt; continue
  8465. // </li>
  8466. //
  8467. // <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
  8468. // {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set
  8469. // {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
  8470. // {@code {1}} =&gt; stop and predict 1</li>
  8471. //
  8472. // <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
  8473. // {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U
  8474. // {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce
  8475. // ambiguity {@code {1,2}}</li>
  8476. //
  8477. // <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},
  8478. // {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U
  8479. // {@code {2}} = {@code {1,2}} =&gt; continue</li>
  8480. //
  8481. // <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},
  8482. // {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U
  8483. // {@code {3}} = {@code {1,3}} =&gt; continue</li>
  8484. //
  8485. // </ul>
  8486. //
  8487. // <p><strong>EXACT AMBIGUITY DETECTION</strong></p>
  8488. //
  8489. // <p>If all states report the same conflicting set of alternatives, then we
  8490. // know we have the exact ambiguity set.</p>
  8491. //
  8492. // <p><code>|A_<em>i</em>|&gt;1</code> and
  8493. // <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>
  8494. //
  8495. // <p>In other words, we continue examining lookahead until all {@code A_i}
  8496. // have more than one alternative and all {@code A_i} are the same. If
  8497. // {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate
  8498. // because the resolved set is {@code {1}}. To determine what the real
  8499. // ambiguity is, we have to know whether the ambiguity is between one and
  8500. // two or one and three so we keep going. We can only stop prediction when
  8501. // we need exact ambiguity detection when the sets look like
  8502. // {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>
  8503. //
  8504. PredictionMode.resolvesToJustOneViableAlt = function(altsets) {
  8505. return PredictionMode.getSingleViableAlt(altsets);
  8506. };
  8507. //
  8508. // Determines if every alternative subset in {@code altsets} contains more
  8509. // than one alternative.
  8510. //
  8511. // @param altsets a collection of alternative subsets
  8512. // @return {@code true} if every {@link BitSet} in {@code altsets} has
  8513. // {@link BitSet//cardinality cardinality} &gt; 1, otherwise {@code false}
  8514. //
  8515. PredictionMode.allSubsetsConflict = function(altsets) {
  8516. return ! PredictionMode.hasNonConflictingAltSet(altsets);
  8517. };
  8518. //
  8519. // Determines if any single alternative subset in {@code altsets} contains
  8520. // exactly one alternative.
  8521. //
  8522. // @param altsets a collection of alternative subsets
  8523. // @return {@code true} if {@code altsets} contains a {@link BitSet} with
  8524. // {@link BitSet//cardinality cardinality} 1, otherwise {@code false}
  8525. //
  8526. PredictionMode.hasNonConflictingAltSet = function(altsets) {
  8527. for(var i=0;i<altsets.length;i++) {
  8528. var alts = altsets[i];
  8529. if (alts.length===1) {
  8530. return true;
  8531. }
  8532. }
  8533. return false;
  8534. };
  8535. //
  8536. // Determines if any single alternative subset in {@code altsets} contains
  8537. // more than one alternative.
  8538. //
  8539. // @param altsets a collection of alternative subsets
  8540. // @return {@code true} if {@code altsets} contains a {@link BitSet} with
  8541. // {@link BitSet//cardinality cardinality} &gt; 1, otherwise {@code false}
  8542. //
  8543. PredictionMode.hasConflictingAltSet = function(altsets) {
  8544. for(var i=0;i<altsets.length;i++) {
  8545. var alts = altsets[i];
  8546. if (alts.length>1) {
  8547. return true;
  8548. }
  8549. }
  8550. return false;
  8551. };
  8552. //
  8553. // Determines if every alternative subset in {@code altsets} is equivalent.
  8554. //
  8555. // @param altsets a collection of alternative subsets
  8556. // @return {@code true} if every member of {@code altsets} is equal to the
  8557. // others, otherwise {@code false}
  8558. //
  8559. PredictionMode.allSubsetsEqual = function(altsets) {
  8560. var first = null;
  8561. for(var i=0;i<altsets.length;i++) {
  8562. var alts = altsets[i];
  8563. if (first === null) {
  8564. first = alts;
  8565. } else if (alts!==first) {
  8566. return false;
  8567. }
  8568. }
  8569. return true;
  8570. };
  8571. //
  8572. // Returns the unique alternative predicted by all alternative subsets in
  8573. // {@code altsets}. If no such alternative exists, this method returns
  8574. // {@link ATN//INVALID_ALT_NUMBER}.
  8575. //
  8576. // @param altsets a collection of alternative subsets
  8577. //
  8578. PredictionMode.getUniqueAlt = function(altsets) {
  8579. var all = PredictionMode.getAlts(altsets);
  8580. if (all.length===1) {
  8581. return all.minValue();
  8582. } else {
  8583. return ATN.INVALID_ALT_NUMBER;
  8584. }
  8585. };
  8586. // Gets the complete set of represented alternatives for a collection of
  8587. // alternative subsets. This method returns the union of each {@link BitSet}
  8588. // in {@code altsets}.
  8589. //
  8590. // @param altsets a collection of alternative subsets
  8591. // @return the set of represented alternatives in {@code altsets}
  8592. //
  8593. PredictionMode.getAlts = function(altsets) {
  8594. var all = new BitSet();
  8595. altsets.map( function(alts) { all.or(alts); });
  8596. return all;
  8597. };
  8598. //
  8599. // This function gets the conflicting alt subsets from a configuration set.
  8600. // For each configuration {@code c} in {@code configs}:
  8601. //
  8602. // <pre>
  8603. // map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not
  8604. // alt and not pred
  8605. // </pre>
  8606. PredictionMode.getConflictingAltSubsets = function(configs) {
  8607. var configToAlts = new Map();
  8608. configToAlts.hashFunction = function(cfg) { hashStuff(cfg.state.stateNumber, cfg.context); };
  8609. configToAlts.equalsFunction = function(c1, c2) { return c1.state.stateNumber==c2.state.stateNumber && c1.context.equals(c2.context);}
  8610. configs.items.map(function(cfg) {
  8611. var alts = configToAlts.get(cfg);
  8612. if (alts === null) {
  8613. alts = new BitSet();
  8614. configToAlts.put(cfg, alts);
  8615. }
  8616. alts.add(cfg.alt);
  8617. });
  8618. return configToAlts.getValues();
  8619. };
  8620. //
  8621. // Get a map from state to alt subset from a configuration set. For each
  8622. // configuration {@code c} in {@code configs}:
  8623. //
  8624. // <pre>
  8625. // map[c.{@link ATNConfig//state state}] U= c.{@link ATNConfig//alt alt}
  8626. // </pre>
  8627. //
  8628. PredictionMode.getStateToAltMap = function(configs) {
  8629. var m = new AltDict();
  8630. configs.items.map(function(c) {
  8631. var alts = m.get(c.state);
  8632. if (alts === null) {
  8633. alts = new BitSet();
  8634. m.put(c.state, alts);
  8635. }
  8636. alts.add(c.alt);
  8637. });
  8638. return m;
  8639. };
  8640. PredictionMode.hasStateAssociatedWithOneAlt = function(configs) {
  8641. var values = PredictionMode.getStateToAltMap(configs).values();
  8642. for(var i=0;i<values.length;i++) {
  8643. if (values[i].length===1) {
  8644. return true;
  8645. }
  8646. }
  8647. return false;
  8648. };
  8649. PredictionMode.getSingleViableAlt = function(altsets) {
  8650. var result = null;
  8651. for(var i=0;i<altsets.length;i++) {
  8652. var alts = altsets[i];
  8653. var minAlt = alts.minValue();
  8654. if(result===null) {
  8655. result = minAlt;
  8656. } else if(result!==minAlt) { // more than 1 viable alt
  8657. return ATN.INVALID_ALT_NUMBER;
  8658. }
  8659. }
  8660. return result;
  8661. };
  8662. exports.PredictionMode = PredictionMode;
  8663. /***/ }),
  8664. /***/ "./node_modules/antlr4/atn/SemanticContext.js":
  8665. /*!****************************************************!*\
  8666. !*** ./node_modules/antlr4/atn/SemanticContext.js ***!
  8667. \****************************************************/
  8668. /*! no static exports found */
  8669. /***/ (function(module, exports, __webpack_require__) {
  8670. //
  8671. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  8672. * Use of this file is governed by the BSD 3-clause license that
  8673. * can be found in the LICENSE.txt file in the project root.
  8674. */
  8675. //
  8676. // A tree structure used to record the semantic context in which
  8677. // an ATN configuration is valid. It's either a single predicate,
  8678. // a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.
  8679. //
  8680. // <p>I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of
  8681. // {@link SemanticContext} within the scope of this outer class.</p>
  8682. //
  8683. var Set = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Set;
  8684. var Hash = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Hash;
  8685. function SemanticContext() {
  8686. return this;
  8687. }
  8688. SemanticContext.prototype.hashCode = function() {
  8689. var hash = new Hash();
  8690. this.updateHashCode(hash);
  8691. return hash.finish();
  8692. };
  8693. // For context independent predicates, we evaluate them without a local
  8694. // context (i.e., null context). That way, we can evaluate them without
  8695. // having to create proper rule-specific context during prediction (as
  8696. // opposed to the parser, which creates them naturally). In a practical
  8697. // sense, this avoids a cast exception from RuleContext to myruleContext.
  8698. //
  8699. // <p>For context dependent predicates, we must pass in a local context so that
  8700. // references such as $arg evaluate properly as _localctx.arg. We only
  8701. // capture context dependent predicates in the context in which we begin
  8702. // prediction, so we passed in the outer context here in case of context
  8703. // dependent predicate evaluation.</p>
  8704. //
  8705. SemanticContext.prototype.evaluate = function(parser, outerContext) {
  8706. };
  8707. //
  8708. // Evaluate the precedence predicates for the context and reduce the result.
  8709. //
  8710. // @param parser The parser instance.
  8711. // @param outerContext The current parser context object.
  8712. // @return The simplified semantic context after precedence predicates are
  8713. // evaluated, which will be one of the following values.
  8714. // <ul>
  8715. // <li>{@link //NONE}: if the predicate simplifies to {@code true} after
  8716. // precedence predicates are evaluated.</li>
  8717. // <li>{@code null}: if the predicate simplifies to {@code false} after
  8718. // precedence predicates are evaluated.</li>
  8719. // <li>{@code this}: if the semantic context is not changed as a result of
  8720. // precedence predicate evaluation.</li>
  8721. // <li>A non-{@code null} {@link SemanticContext}: the new simplified
  8722. // semantic context after precedence predicates are evaluated.</li>
  8723. // </ul>
  8724. //
  8725. SemanticContext.prototype.evalPrecedence = function(parser, outerContext) {
  8726. return this;
  8727. };
  8728. SemanticContext.andContext = function(a, b) {
  8729. if (a === null || a === SemanticContext.NONE) {
  8730. return b;
  8731. }
  8732. if (b === null || b === SemanticContext.NONE) {
  8733. return a;
  8734. }
  8735. var result = new AND(a, b);
  8736. if (result.opnds.length === 1) {
  8737. return result.opnds[0];
  8738. } else {
  8739. return result;
  8740. }
  8741. };
  8742. SemanticContext.orContext = function(a, b) {
  8743. if (a === null) {
  8744. return b;
  8745. }
  8746. if (b === null) {
  8747. return a;
  8748. }
  8749. if (a === SemanticContext.NONE || b === SemanticContext.NONE) {
  8750. return SemanticContext.NONE;
  8751. }
  8752. var result = new OR(a, b);
  8753. if (result.opnds.length === 1) {
  8754. return result.opnds[0];
  8755. } else {
  8756. return result;
  8757. }
  8758. };
  8759. function Predicate(ruleIndex, predIndex, isCtxDependent) {
  8760. SemanticContext.call(this);
  8761. this.ruleIndex = ruleIndex === undefined ? -1 : ruleIndex;
  8762. this.predIndex = predIndex === undefined ? -1 : predIndex;
  8763. this.isCtxDependent = isCtxDependent === undefined ? false : isCtxDependent; // e.g., $i ref in pred
  8764. return this;
  8765. }
  8766. Predicate.prototype = Object.create(SemanticContext.prototype);
  8767. Predicate.prototype.constructor = Predicate;
  8768. //The default {@link SemanticContext}, which is semantically equivalent to
  8769. //a predicate of the form {@code {true}?}.
  8770. //
  8771. SemanticContext.NONE = new Predicate();
  8772. Predicate.prototype.evaluate = function(parser, outerContext) {
  8773. var localctx = this.isCtxDependent ? outerContext : null;
  8774. return parser.sempred(localctx, this.ruleIndex, this.predIndex);
  8775. };
  8776. Predicate.prototype.updateHashCode = function(hash) {
  8777. hash.update(this.ruleIndex, this.predIndex, this.isCtxDependent);
  8778. };
  8779. Predicate.prototype.equals = function(other) {
  8780. if (this === other) {
  8781. return true;
  8782. } else if (!(other instanceof Predicate)) {
  8783. return false;
  8784. } else {
  8785. return this.ruleIndex === other.ruleIndex &&
  8786. this.predIndex === other.predIndex &&
  8787. this.isCtxDependent === other.isCtxDependent;
  8788. }
  8789. };
  8790. Predicate.prototype.toString = function() {
  8791. return "{" + this.ruleIndex + ":" + this.predIndex + "}?";
  8792. };
  8793. function PrecedencePredicate(precedence) {
  8794. SemanticContext.call(this);
  8795. this.precedence = precedence === undefined ? 0 : precedence;
  8796. }
  8797. PrecedencePredicate.prototype = Object.create(SemanticContext.prototype);
  8798. PrecedencePredicate.prototype.constructor = PrecedencePredicate;
  8799. PrecedencePredicate.prototype.evaluate = function(parser, outerContext) {
  8800. return parser.precpred(outerContext, this.precedence);
  8801. };
  8802. PrecedencePredicate.prototype.evalPrecedence = function(parser, outerContext) {
  8803. if (parser.precpred(outerContext, this.precedence)) {
  8804. return SemanticContext.NONE;
  8805. } else {
  8806. return null;
  8807. }
  8808. };
  8809. PrecedencePredicate.prototype.compareTo = function(other) {
  8810. return this.precedence - other.precedence;
  8811. };
  8812. PrecedencePredicate.prototype.updateHashCode = function(hash) {
  8813. hash.update(31);
  8814. };
  8815. PrecedencePredicate.prototype.equals = function(other) {
  8816. if (this === other) {
  8817. return true;
  8818. } else if (!(other instanceof PrecedencePredicate)) {
  8819. return false;
  8820. } else {
  8821. return this.precedence === other.precedence;
  8822. }
  8823. };
  8824. PrecedencePredicate.prototype.toString = function() {
  8825. return "{"+this.precedence+">=prec}?";
  8826. };
  8827. PrecedencePredicate.filterPrecedencePredicates = function(set) {
  8828. var result = [];
  8829. set.values().map( function(context) {
  8830. if (context instanceof PrecedencePredicate) {
  8831. result.push(context);
  8832. }
  8833. });
  8834. return result;
  8835. };
  8836. // A semantic context which is true whenever none of the contained contexts
  8837. // is false.
  8838. //
  8839. function AND(a, b) {
  8840. SemanticContext.call(this);
  8841. var operands = new Set();
  8842. if (a instanceof AND) {
  8843. a.opnds.map(function(o) {
  8844. operands.add(o);
  8845. });
  8846. } else {
  8847. operands.add(a);
  8848. }
  8849. if (b instanceof AND) {
  8850. b.opnds.map(function(o) {
  8851. operands.add(o);
  8852. });
  8853. } else {
  8854. operands.add(b);
  8855. }
  8856. var precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
  8857. if (precedencePredicates.length > 0) {
  8858. // interested in the transition with the lowest precedence
  8859. var reduced = null;
  8860. precedencePredicates.map( function(p) {
  8861. if(reduced===null || p.precedence<reduced.precedence) {
  8862. reduced = p;
  8863. }
  8864. });
  8865. operands.add(reduced);
  8866. }
  8867. this.opnds = operands.values();
  8868. return this;
  8869. }
  8870. AND.prototype = Object.create(SemanticContext.prototype);
  8871. AND.prototype.constructor = AND;
  8872. AND.prototype.equals = function(other) {
  8873. if (this === other) {
  8874. return true;
  8875. } else if (!(other instanceof AND)) {
  8876. return false;
  8877. } else {
  8878. return this.opnds === other.opnds;
  8879. }
  8880. };
  8881. AND.prototype.updateHashCode = function(hash) {
  8882. hash.update(this.opnds, "AND");
  8883. };
  8884. //
  8885. // {@inheritDoc}
  8886. //
  8887. // <p>
  8888. // The evaluation of predicates by this context is short-circuiting, but
  8889. // unordered.</p>
  8890. //
  8891. AND.prototype.evaluate = function(parser, outerContext) {
  8892. for (var i = 0; i < this.opnds.length; i++) {
  8893. if (!this.opnds[i].evaluate(parser, outerContext)) {
  8894. return false;
  8895. }
  8896. }
  8897. return true;
  8898. };
  8899. AND.prototype.evalPrecedence = function(parser, outerContext) {
  8900. var differs = false;
  8901. var operands = [];
  8902. for (var i = 0; i < this.opnds.length; i++) {
  8903. var context = this.opnds[i];
  8904. var evaluated = context.evalPrecedence(parser, outerContext);
  8905. differs |= (evaluated !== context);
  8906. if (evaluated === null) {
  8907. // The AND context is false if any element is false
  8908. return null;
  8909. } else if (evaluated !== SemanticContext.NONE) {
  8910. // Reduce the result by skipping true elements
  8911. operands.push(evaluated);
  8912. }
  8913. }
  8914. if (!differs) {
  8915. return this;
  8916. }
  8917. if (operands.length === 0) {
  8918. // all elements were true, so the AND context is true
  8919. return SemanticContext.NONE;
  8920. }
  8921. var result = null;
  8922. operands.map(function(o) {
  8923. result = result === null ? o : SemanticContext.andContext(result, o);
  8924. });
  8925. return result;
  8926. };
  8927. AND.prototype.toString = function() {
  8928. var s = "";
  8929. this.opnds.map(function(o) {
  8930. s += "&& " + o.toString();
  8931. });
  8932. return s.length > 3 ? s.slice(3) : s;
  8933. };
  8934. //
  8935. // A semantic context which is true whenever at least one of the contained
  8936. // contexts is true.
  8937. //
  8938. function OR(a, b) {
  8939. SemanticContext.call(this);
  8940. var operands = new Set();
  8941. if (a instanceof OR) {
  8942. a.opnds.map(function(o) {
  8943. operands.add(o);
  8944. });
  8945. } else {
  8946. operands.add(a);
  8947. }
  8948. if (b instanceof OR) {
  8949. b.opnds.map(function(o) {
  8950. operands.add(o);
  8951. });
  8952. } else {
  8953. operands.add(b);
  8954. }
  8955. var precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
  8956. if (precedencePredicates.length > 0) {
  8957. // interested in the transition with the highest precedence
  8958. var s = precedencePredicates.sort(function(a, b) {
  8959. return a.compareTo(b);
  8960. });
  8961. var reduced = s[s.length-1];
  8962. operands.add(reduced);
  8963. }
  8964. this.opnds = operands.values();
  8965. return this;
  8966. }
  8967. OR.prototype = Object.create(SemanticContext.prototype);
  8968. OR.prototype.constructor = OR;
  8969. OR.prototype.constructor = function(other) {
  8970. if (this === other) {
  8971. return true;
  8972. } else if (!(other instanceof OR)) {
  8973. return false;
  8974. } else {
  8975. return this.opnds === other.opnds;
  8976. }
  8977. };
  8978. OR.prototype.updateHashCode = function(hash) {
  8979. hash.update(this.opnds, "OR");
  8980. };
  8981. // <p>
  8982. // The evaluation of predicates by this context is short-circuiting, but
  8983. // unordered.</p>
  8984. //
  8985. OR.prototype.evaluate = function(parser, outerContext) {
  8986. for (var i = 0; i < this.opnds.length; i++) {
  8987. if (this.opnds[i].evaluate(parser, outerContext)) {
  8988. return true;
  8989. }
  8990. }
  8991. return false;
  8992. };
  8993. OR.prototype.evalPrecedence = function(parser, outerContext) {
  8994. var differs = false;
  8995. var operands = [];
  8996. for (var i = 0; i < this.opnds.length; i++) {
  8997. var context = this.opnds[i];
  8998. var evaluated = context.evalPrecedence(parser, outerContext);
  8999. differs |= (evaluated !== context);
  9000. if (evaluated === SemanticContext.NONE) {
  9001. // The OR context is true if any element is true
  9002. return SemanticContext.NONE;
  9003. } else if (evaluated !== null) {
  9004. // Reduce the result by skipping false elements
  9005. operands.push(evaluated);
  9006. }
  9007. }
  9008. if (!differs) {
  9009. return this;
  9010. }
  9011. if (operands.length === 0) {
  9012. // all elements were false, so the OR context is false
  9013. return null;
  9014. }
  9015. var result = null;
  9016. operands.map(function(o) {
  9017. return result === null ? o : SemanticContext.orContext(result, o);
  9018. });
  9019. return result;
  9020. };
  9021. OR.prototype.toString = function() {
  9022. var s = "";
  9023. this.opnds.map(function(o) {
  9024. s += "|| " + o.toString();
  9025. });
  9026. return s.length > 3 ? s.slice(3) : s;
  9027. };
  9028. exports.SemanticContext = SemanticContext;
  9029. exports.PrecedencePredicate = PrecedencePredicate;
  9030. exports.Predicate = Predicate;
  9031. /***/ }),
  9032. /***/ "./node_modules/antlr4/atn/Transition.js":
  9033. /*!***********************************************!*\
  9034. !*** ./node_modules/antlr4/atn/Transition.js ***!
  9035. \***********************************************/
  9036. /*! no static exports found */
  9037. /***/ (function(module, exports, __webpack_require__) {
  9038. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9039. * Use of this file is governed by the BSD 3-clause license that
  9040. * can be found in the LICENSE.txt file in the project root.
  9041. */
  9042. //
  9043. // An ATN transition between any two ATN states. Subclasses define
  9044. // atom, set, epsilon, action, predicate, rule transitions.
  9045. //
  9046. // <p>This is a one way link. It emanates from a state (usually via a list of
  9047. // transitions) and has a target state.</p>
  9048. //
  9049. // <p>Since we never have to change the ATN transitions once we construct it,
  9050. // we can fix these transitions as specific classes. The DFA transitions
  9051. // on the other hand need to update the labels as it adds transitions to
  9052. // the states. We'll use the term Edge for the DFA to distinguish them from
  9053. // ATN transitions.</p>
  9054. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  9055. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  9056. var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  9057. var Predicate = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").Predicate;
  9058. var PrecedencePredicate = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").PrecedencePredicate;
  9059. function Transition (target) {
  9060. // The target of this transition.
  9061. if (target===undefined || target===null) {
  9062. throw "target cannot be null.";
  9063. }
  9064. this.target = target;
  9065. // Are we epsilon, action, sempred?
  9066. this.isEpsilon = false;
  9067. this.label = null;
  9068. return this;
  9069. }
  9070. // constants for serialization
  9071. Transition.EPSILON = 1;
  9072. Transition.RANGE = 2;
  9073. Transition.RULE = 3;
  9074. Transition.PREDICATE = 4; // e.g., {isType(input.LT(1))}?
  9075. Transition.ATOM = 5;
  9076. Transition.ACTION = 6;
  9077. Transition.SET = 7; // ~(A|B) or ~atom, wildcard, which convert to next 2
  9078. Transition.NOT_SET = 8;
  9079. Transition.WILDCARD = 9;
  9080. Transition.PRECEDENCE = 10;
  9081. Transition.serializationNames = [
  9082. "INVALID",
  9083. "EPSILON",
  9084. "RANGE",
  9085. "RULE",
  9086. "PREDICATE",
  9087. "ATOM",
  9088. "ACTION",
  9089. "SET",
  9090. "NOT_SET",
  9091. "WILDCARD",
  9092. "PRECEDENCE"
  9093. ];
  9094. Transition.serializationTypes = {
  9095. EpsilonTransition: Transition.EPSILON,
  9096. RangeTransition: Transition.RANGE,
  9097. RuleTransition: Transition.RULE,
  9098. PredicateTransition: Transition.PREDICATE,
  9099. AtomTransition: Transition.ATOM,
  9100. ActionTransition: Transition.ACTION,
  9101. SetTransition: Transition.SET,
  9102. NotSetTransition: Transition.NOT_SET,
  9103. WildcardTransition: Transition.WILDCARD,
  9104. PrecedencePredicateTransition: Transition.PRECEDENCE
  9105. };
  9106. // TODO: make all transitions sets? no, should remove set edges
  9107. function AtomTransition(target, label) {
  9108. Transition.call(this, target);
  9109. this.label_ = label; // The token type or character value; or, signifies special label.
  9110. this.label = this.makeLabel();
  9111. this.serializationType = Transition.ATOM;
  9112. return this;
  9113. }
  9114. AtomTransition.prototype = Object.create(Transition.prototype);
  9115. AtomTransition.prototype.constructor = AtomTransition;
  9116. AtomTransition.prototype.makeLabel = function() {
  9117. var s = new IntervalSet();
  9118. s.addOne(this.label_);
  9119. return s;
  9120. };
  9121. AtomTransition.prototype.matches = function( symbol, minVocabSymbol, maxVocabSymbol) {
  9122. return this.label_ === symbol;
  9123. };
  9124. AtomTransition.prototype.toString = function() {
  9125. return this.label_;
  9126. };
  9127. function RuleTransition(ruleStart, ruleIndex, precedence, followState) {
  9128. Transition.call(this, ruleStart);
  9129. this.ruleIndex = ruleIndex; // ptr to the rule definition object for this rule ref
  9130. this.precedence = precedence;
  9131. this.followState = followState; // what node to begin computations following ref to rule
  9132. this.serializationType = Transition.RULE;
  9133. this.isEpsilon = true;
  9134. return this;
  9135. }
  9136. RuleTransition.prototype = Object.create(Transition.prototype);
  9137. RuleTransition.prototype.constructor = RuleTransition;
  9138. RuleTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9139. return false;
  9140. };
  9141. function EpsilonTransition(target, outermostPrecedenceReturn) {
  9142. Transition.call(this, target);
  9143. this.serializationType = Transition.EPSILON;
  9144. this.isEpsilon = true;
  9145. this.outermostPrecedenceReturn = outermostPrecedenceReturn;
  9146. return this;
  9147. }
  9148. EpsilonTransition.prototype = Object.create(Transition.prototype);
  9149. EpsilonTransition.prototype.constructor = EpsilonTransition;
  9150. EpsilonTransition.prototype.matches = function( symbol, minVocabSymbol, maxVocabSymbol) {
  9151. return false;
  9152. };
  9153. EpsilonTransition.prototype.toString = function() {
  9154. return "epsilon";
  9155. };
  9156. function RangeTransition(target, start, stop) {
  9157. Transition.call(this, target);
  9158. this.serializationType = Transition.RANGE;
  9159. this.start = start;
  9160. this.stop = stop;
  9161. this.label = this.makeLabel();
  9162. return this;
  9163. }
  9164. RangeTransition.prototype = Object.create(Transition.prototype);
  9165. RangeTransition.prototype.constructor = RangeTransition;
  9166. RangeTransition.prototype.makeLabel = function() {
  9167. var s = new IntervalSet();
  9168. s.addRange(this.start, this.stop);
  9169. return s;
  9170. };
  9171. RangeTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9172. return symbol >= this.start && symbol <= this.stop;
  9173. };
  9174. RangeTransition.prototype.toString = function() {
  9175. return "'" + String.fromCharCode(this.start) + "'..'" + String.fromCharCode(this.stop) + "'";
  9176. };
  9177. function AbstractPredicateTransition(target) {
  9178. Transition.call(this, target);
  9179. return this;
  9180. }
  9181. AbstractPredicateTransition.prototype = Object.create(Transition.prototype);
  9182. AbstractPredicateTransition.prototype.constructor = AbstractPredicateTransition;
  9183. function PredicateTransition(target, ruleIndex, predIndex, isCtxDependent) {
  9184. AbstractPredicateTransition.call(this, target);
  9185. this.serializationType = Transition.PREDICATE;
  9186. this.ruleIndex = ruleIndex;
  9187. this.predIndex = predIndex;
  9188. this.isCtxDependent = isCtxDependent; // e.g., $i ref in pred
  9189. this.isEpsilon = true;
  9190. return this;
  9191. }
  9192. PredicateTransition.prototype = Object.create(AbstractPredicateTransition.prototype);
  9193. PredicateTransition.prototype.constructor = PredicateTransition;
  9194. PredicateTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9195. return false;
  9196. };
  9197. PredicateTransition.prototype.getPredicate = function() {
  9198. return new Predicate(this.ruleIndex, this.predIndex, this.isCtxDependent);
  9199. };
  9200. PredicateTransition.prototype.toString = function() {
  9201. return "pred_" + this.ruleIndex + ":" + this.predIndex;
  9202. };
  9203. function ActionTransition(target, ruleIndex, actionIndex, isCtxDependent) {
  9204. Transition.call(this, target);
  9205. this.serializationType = Transition.ACTION;
  9206. this.ruleIndex = ruleIndex;
  9207. this.actionIndex = actionIndex===undefined ? -1 : actionIndex;
  9208. this.isCtxDependent = isCtxDependent===undefined ? false : isCtxDependent; // e.g., $i ref in pred
  9209. this.isEpsilon = true;
  9210. return this;
  9211. }
  9212. ActionTransition.prototype = Object.create(Transition.prototype);
  9213. ActionTransition.prototype.constructor = ActionTransition;
  9214. ActionTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9215. return false;
  9216. };
  9217. ActionTransition.prototype.toString = function() {
  9218. return "action_" + this.ruleIndex + ":" + this.actionIndex;
  9219. };
  9220. // A transition containing a set of values.
  9221. function SetTransition(target, set) {
  9222. Transition.call(this, target);
  9223. this.serializationType = Transition.SET;
  9224. if (set !==undefined && set !==null) {
  9225. this.label = set;
  9226. } else {
  9227. this.label = new IntervalSet();
  9228. this.label.addOne(Token.INVALID_TYPE);
  9229. }
  9230. return this;
  9231. }
  9232. SetTransition.prototype = Object.create(Transition.prototype);
  9233. SetTransition.prototype.constructor = SetTransition;
  9234. SetTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9235. return this.label.contains(symbol);
  9236. };
  9237. SetTransition.prototype.toString = function() {
  9238. return this.label.toString();
  9239. };
  9240. function NotSetTransition(target, set) {
  9241. SetTransition.call(this, target, set);
  9242. this.serializationType = Transition.NOT_SET;
  9243. return this;
  9244. }
  9245. NotSetTransition.prototype = Object.create(SetTransition.prototype);
  9246. NotSetTransition.prototype.constructor = NotSetTransition;
  9247. NotSetTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9248. return symbol >= minVocabSymbol && symbol <= maxVocabSymbol &&
  9249. !SetTransition.prototype.matches.call(this, symbol, minVocabSymbol, maxVocabSymbol);
  9250. };
  9251. NotSetTransition.prototype.toString = function() {
  9252. return '~' + SetTransition.prototype.toString.call(this);
  9253. };
  9254. function WildcardTransition(target) {
  9255. Transition.call(this, target);
  9256. this.serializationType = Transition.WILDCARD;
  9257. return this;
  9258. }
  9259. WildcardTransition.prototype = Object.create(Transition.prototype);
  9260. WildcardTransition.prototype.constructor = WildcardTransition;
  9261. WildcardTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9262. return symbol >= minVocabSymbol && symbol <= maxVocabSymbol;
  9263. };
  9264. WildcardTransition.prototype.toString = function() {
  9265. return ".";
  9266. };
  9267. function PrecedencePredicateTransition(target, precedence) {
  9268. AbstractPredicateTransition.call(this, target);
  9269. this.serializationType = Transition.PRECEDENCE;
  9270. this.precedence = precedence;
  9271. this.isEpsilon = true;
  9272. return this;
  9273. }
  9274. PrecedencePredicateTransition.prototype = Object.create(AbstractPredicateTransition.prototype);
  9275. PrecedencePredicateTransition.prototype.constructor = PrecedencePredicateTransition;
  9276. PrecedencePredicateTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9277. return false;
  9278. };
  9279. PrecedencePredicateTransition.prototype.getPredicate = function() {
  9280. return new PrecedencePredicate(this.precedence);
  9281. };
  9282. PrecedencePredicateTransition.prototype.toString = function() {
  9283. return this.precedence + " >= _p";
  9284. };
  9285. exports.Transition = Transition;
  9286. exports.AtomTransition = AtomTransition;
  9287. exports.SetTransition = SetTransition;
  9288. exports.NotSetTransition = NotSetTransition;
  9289. exports.RuleTransition = RuleTransition;
  9290. exports.ActionTransition = ActionTransition;
  9291. exports.EpsilonTransition = EpsilonTransition;
  9292. exports.RangeTransition = RangeTransition;
  9293. exports.WildcardTransition = WildcardTransition;
  9294. exports.PredicateTransition = PredicateTransition;
  9295. exports.PrecedencePredicateTransition = PrecedencePredicateTransition;
  9296. exports.AbstractPredicateTransition = AbstractPredicateTransition;
  9297. /***/ }),
  9298. /***/ "./node_modules/antlr4/atn/index.js":
  9299. /*!******************************************!*\
  9300. !*** ./node_modules/antlr4/atn/index.js ***!
  9301. \******************************************/
  9302. /*! no static exports found */
  9303. /***/ (function(module, exports, __webpack_require__) {
  9304. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9305. * Use of this file is governed by the BSD 3-clause license that
  9306. * can be found in the LICENSE.txt file in the project root.
  9307. */
  9308. exports.ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  9309. exports.ATNDeserializer = __webpack_require__(/*! ./ATNDeserializer */ "./node_modules/antlr4/atn/ATNDeserializer.js").ATNDeserializer;
  9310. exports.LexerATNSimulator = __webpack_require__(/*! ./LexerATNSimulator */ "./node_modules/antlr4/atn/LexerATNSimulator.js").LexerATNSimulator;
  9311. exports.ParserATNSimulator = __webpack_require__(/*! ./ParserATNSimulator */ "./node_modules/antlr4/atn/ParserATNSimulator.js").ParserATNSimulator;
  9312. exports.PredictionMode = __webpack_require__(/*! ./PredictionMode */ "./node_modules/antlr4/atn/PredictionMode.js").PredictionMode;
  9313. /***/ }),
  9314. /***/ "./node_modules/antlr4/dfa/DFA.js":
  9315. /*!****************************************!*\
  9316. !*** ./node_modules/antlr4/dfa/DFA.js ***!
  9317. \****************************************/
  9318. /*! no static exports found */
  9319. /***/ (function(module, exports, __webpack_require__) {
  9320. //
  9321. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9322. * Use of this file is governed by the BSD 3-clause license that
  9323. * can be found in the LICENSE.txt file in the project root.
  9324. */
  9325. var Set = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").Set;
  9326. var DFAState = __webpack_require__(/*! ./DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
  9327. var StarLoopEntryState = __webpack_require__(/*! ../atn/ATNState */ "./node_modules/antlr4/atn/ATNState.js").StarLoopEntryState;
  9328. var ATNConfigSet = __webpack_require__(/*! ./../atn/ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  9329. var DFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").DFASerializer;
  9330. var LexerDFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").LexerDFASerializer;
  9331. function DFA(atnStartState, decision) {
  9332. if (decision === undefined) {
  9333. decision = 0;
  9334. }
  9335. // From which ATN state did we create this DFA?
  9336. this.atnStartState = atnStartState;
  9337. this.decision = decision;
  9338. // A set of all DFA states. Use {@link Map} so we can get old state back
  9339. // ({@link Set} only allows you to see if it's there).
  9340. this._states = new Set();
  9341. this.s0 = null;
  9342. // {@code true} if this DFA is for a precedence decision; otherwise,
  9343. // {@code false}. This is the backing field for {@link //isPrecedenceDfa},
  9344. // {@link //setPrecedenceDfa}.
  9345. this.precedenceDfa = false;
  9346. if (atnStartState instanceof StarLoopEntryState)
  9347. {
  9348. if (atnStartState.isPrecedenceDecision) {
  9349. this.precedenceDfa = true;
  9350. var precedenceState = new DFAState(null, new ATNConfigSet());
  9351. precedenceState.edges = [];
  9352. precedenceState.isAcceptState = false;
  9353. precedenceState.requiresFullContext = false;
  9354. this.s0 = precedenceState;
  9355. }
  9356. }
  9357. return this;
  9358. }
  9359. // Get the start state for a specific precedence value.
  9360. //
  9361. // @param precedence The current precedence.
  9362. // @return The start state corresponding to the specified precedence, or
  9363. // {@code null} if no start state exists for the specified precedence.
  9364. //
  9365. // @throws IllegalStateException if this is not a precedence DFA.
  9366. // @see //isPrecedenceDfa()
  9367. DFA.prototype.getPrecedenceStartState = function(precedence) {
  9368. if (!(this.precedenceDfa)) {
  9369. throw ("Only precedence DFAs may contain a precedence start state.");
  9370. }
  9371. // s0.edges is never null for a precedence DFA
  9372. if (precedence < 0 || precedence >= this.s0.edges.length) {
  9373. return null;
  9374. }
  9375. return this.s0.edges[precedence] || null;
  9376. };
  9377. // Set the start state for a specific precedence value.
  9378. //
  9379. // @param precedence The current precedence.
  9380. // @param startState The start state corresponding to the specified
  9381. // precedence.
  9382. //
  9383. // @throws IllegalStateException if this is not a precedence DFA.
  9384. // @see //isPrecedenceDfa()
  9385. //
  9386. DFA.prototype.setPrecedenceStartState = function(precedence, startState) {
  9387. if (!(this.precedenceDfa)) {
  9388. throw ("Only precedence DFAs may contain a precedence start state.");
  9389. }
  9390. if (precedence < 0) {
  9391. return;
  9392. }
  9393. // synchronization on s0 here is ok. when the DFA is turned into a
  9394. // precedence DFA, s0 will be initialized once and not updated again
  9395. // s0.edges is never null for a precedence DFA
  9396. this.s0.edges[precedence] = startState;
  9397. };
  9398. //
  9399. // Sets whether this is a precedence DFA. If the specified value differs
  9400. // from the current DFA configuration, the following actions are taken;
  9401. // otherwise no changes are made to the current DFA.
  9402. //
  9403. // <ul>
  9404. // <li>The {@link //states} map is cleared</li>
  9405. // <li>If {@code precedenceDfa} is {@code false}, the initial state
  9406. // {@link //s0} is set to {@code null}; otherwise, it is initialized to a new
  9407. // {@link DFAState} with an empty outgoing {@link DFAState//edges} array to
  9408. // store the start states for individual precedence values.</li>
  9409. // <li>The {@link //precedenceDfa} field is updated</li>
  9410. // </ul>
  9411. //
  9412. // @param precedenceDfa {@code true} if this is a precedence DFA; otherwise,
  9413. // {@code false}
  9414. DFA.prototype.setPrecedenceDfa = function(precedenceDfa) {
  9415. if (this.precedenceDfa!==precedenceDfa) {
  9416. this._states = new DFAStatesSet();
  9417. if (precedenceDfa) {
  9418. var precedenceState = new DFAState(null, new ATNConfigSet());
  9419. precedenceState.edges = [];
  9420. precedenceState.isAcceptState = false;
  9421. precedenceState.requiresFullContext = false;
  9422. this.s0 = precedenceState;
  9423. } else {
  9424. this.s0 = null;
  9425. }
  9426. this.precedenceDfa = precedenceDfa;
  9427. }
  9428. };
  9429. Object.defineProperty(DFA.prototype, "states", {
  9430. get : function() {
  9431. return this._states;
  9432. }
  9433. });
  9434. // Return a list of all states in this DFA, ordered by state number.
  9435. DFA.prototype.sortedStates = function() {
  9436. var list = this._states.values();
  9437. return list.sort(function(a, b) {
  9438. return a.stateNumber - b.stateNumber;
  9439. });
  9440. };
  9441. DFA.prototype.toString = function(literalNames, symbolicNames) {
  9442. literalNames = literalNames || null;
  9443. symbolicNames = symbolicNames || null;
  9444. if (this.s0 === null) {
  9445. return "";
  9446. }
  9447. var serializer = new DFASerializer(this, literalNames, symbolicNames);
  9448. return serializer.toString();
  9449. };
  9450. DFA.prototype.toLexerString = function() {
  9451. if (this.s0 === null) {
  9452. return "";
  9453. }
  9454. var serializer = new LexerDFASerializer(this);
  9455. return serializer.toString();
  9456. };
  9457. exports.DFA = DFA;
  9458. /***/ }),
  9459. /***/ "./node_modules/antlr4/dfa/DFASerializer.js":
  9460. /*!**************************************************!*\
  9461. !*** ./node_modules/antlr4/dfa/DFASerializer.js ***!
  9462. \**************************************************/
  9463. /*! no static exports found */
  9464. /***/ (function(module, exports) {
  9465. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9466. * Use of this file is governed by the BSD 3-clause license that
  9467. * can be found in the LICENSE.txt file in the project root.
  9468. */
  9469. // A DFA walker that knows how to dump them to serialized strings.#/
  9470. function DFASerializer(dfa, literalNames, symbolicNames) {
  9471. this.dfa = dfa;
  9472. this.literalNames = literalNames || [];
  9473. this.symbolicNames = symbolicNames || [];
  9474. return this;
  9475. }
  9476. DFASerializer.prototype.toString = function() {
  9477. if(this.dfa.s0 === null) {
  9478. return null;
  9479. }
  9480. var buf = "";
  9481. var states = this.dfa.sortedStates();
  9482. for(var i=0;i<states.length;i++) {
  9483. var s = states[i];
  9484. if(s.edges!==null) {
  9485. var n = s.edges.length;
  9486. for(var j=0;j<n;j++) {
  9487. var t = s.edges[j] || null;
  9488. if(t!==null && t.stateNumber !== 0x7FFFFFFF) {
  9489. buf = buf.concat(this.getStateString(s));
  9490. buf = buf.concat("-");
  9491. buf = buf.concat(this.getEdgeLabel(j));
  9492. buf = buf.concat("->");
  9493. buf = buf.concat(this.getStateString(t));
  9494. buf = buf.concat('\n');
  9495. }
  9496. }
  9497. }
  9498. }
  9499. return buf.length===0 ? null : buf;
  9500. };
  9501. DFASerializer.prototype.getEdgeLabel = function(i) {
  9502. if (i===0) {
  9503. return "EOF";
  9504. } else if(this.literalNames !==null || this.symbolicNames!==null) {
  9505. return this.literalNames[i-1] || this.symbolicNames[i-1];
  9506. } else {
  9507. return String.fromCharCode(i-1);
  9508. }
  9509. };
  9510. DFASerializer.prototype.getStateString = function(s) {
  9511. var baseStateStr = ( s.isAcceptState ? ":" : "") + "s" + s.stateNumber + ( s.requiresFullContext ? "^" : "");
  9512. if(s.isAcceptState) {
  9513. if (s.predicates !== null) {
  9514. return baseStateStr + "=>" + s.predicates.toString();
  9515. } else {
  9516. return baseStateStr + "=>" + s.prediction.toString();
  9517. }
  9518. } else {
  9519. return baseStateStr;
  9520. }
  9521. };
  9522. function LexerDFASerializer(dfa) {
  9523. DFASerializer.call(this, dfa, null);
  9524. return this;
  9525. }
  9526. LexerDFASerializer.prototype = Object.create(DFASerializer.prototype);
  9527. LexerDFASerializer.prototype.constructor = LexerDFASerializer;
  9528. LexerDFASerializer.prototype.getEdgeLabel = function(i) {
  9529. return "'" + String.fromCharCode(i) + "'";
  9530. };
  9531. exports.DFASerializer = DFASerializer;
  9532. exports.LexerDFASerializer = LexerDFASerializer;
  9533. /***/ }),
  9534. /***/ "./node_modules/antlr4/dfa/DFAState.js":
  9535. /*!*********************************************!*\
  9536. !*** ./node_modules/antlr4/dfa/DFAState.js ***!
  9537. \*********************************************/
  9538. /*! no static exports found */
  9539. /***/ (function(module, exports, __webpack_require__) {
  9540. //
  9541. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9542. * Use of this file is governed by the BSD 3-clause license that
  9543. * can be found in the LICENSE.txt file in the project root.
  9544. */
  9545. ///
  9546. var ATNConfigSet = __webpack_require__(/*! ./../atn/ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  9547. var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
  9548. var Hash = Utils.Hash;
  9549. var Set = Utils.Set;
  9550. // Map a predicate to a predicted alternative.///
  9551. function PredPrediction(pred, alt) {
  9552. this.alt = alt;
  9553. this.pred = pred;
  9554. return this;
  9555. }
  9556. PredPrediction.prototype.toString = function() {
  9557. return "(" + this.pred + ", " + this.alt + ")";
  9558. };
  9559. // A DFA state represents a set of possible ATN configurations.
  9560. // As Aho, Sethi, Ullman p. 117 says "The DFA uses its state
  9561. // to keep track of all possible states the ATN can be in after
  9562. // reading each input symbol. That is to say, after reading
  9563. // input a1a2..an, the DFA is in a state that represents the
  9564. // subset T of the states of the ATN that are reachable from the
  9565. // ATN's start state along some path labeled a1a2..an."
  9566. // In conventional NFA&rarr;DFA conversion, therefore, the subset T
  9567. // would be a bitset representing the set of states the
  9568. // ATN could be in. We need to track the alt predicted by each
  9569. // state as well, however. More importantly, we need to maintain
  9570. // a stack of states, tracking the closure operations as they
  9571. // jump from rule to rule, emulating rule invocations (method calls).
  9572. // I have to add a stack to simulate the proper lookahead sequences for
  9573. // the underlying LL grammar from which the ATN was derived.
  9574. //
  9575. // <p>I use a set of ATNConfig objects not simple states. An ATNConfig
  9576. // is both a state (ala normal conversion) and a RuleContext describing
  9577. // the chain of rules (if any) followed to arrive at that state.</p>
  9578. //
  9579. // <p>A DFA state may have multiple references to a particular state,
  9580. // but with different ATN contexts (with same or different alts)
  9581. // meaning that state was reached via a different set of rule invocations.</p>
  9582. // /
  9583. function DFAState(stateNumber, configs) {
  9584. if (stateNumber === null) {
  9585. stateNumber = -1;
  9586. }
  9587. if (configs === null) {
  9588. configs = new ATNConfigSet();
  9589. }
  9590. this.stateNumber = stateNumber;
  9591. this.configs = configs;
  9592. // {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)
  9593. // {@link Token//EOF} maps to {@code edges[0]}.
  9594. this.edges = null;
  9595. this.isAcceptState = false;
  9596. // if accept state, what ttype do we match or alt do we predict?
  9597. // This is set to {@link ATN//INVALID_ALT_NUMBER} when {@link
  9598. // //predicates}{@code !=null} or
  9599. // {@link //requiresFullContext}.
  9600. this.prediction = 0;
  9601. this.lexerActionExecutor = null;
  9602. // Indicates that this state was created during SLL prediction that
  9603. // discovered a conflict between the configurations in the state. Future
  9604. // {@link ParserATNSimulator//execATN} invocations immediately jumped doing
  9605. // full context prediction if this field is true.
  9606. this.requiresFullContext = false;
  9607. // During SLL parsing, this is a list of predicates associated with the
  9608. // ATN configurations of the DFA state. When we have predicates,
  9609. // {@link //requiresFullContext} is {@code false} since full context
  9610. // prediction evaluates predicates
  9611. // on-the-fly. If this is not null, then {@link //prediction} is
  9612. // {@link ATN//INVALID_ALT_NUMBER}.
  9613. //
  9614. // <p>We only use these for non-{@link //requiresFullContext} but
  9615. // conflicting states. That
  9616. // means we know from the context (it's $ or we don't dip into outer
  9617. // context) that it's an ambiguity not a conflict.</p>
  9618. //
  9619. // <p>This list is computed by {@link
  9620. // ParserATNSimulator//predicateDFAState}.</p>
  9621. this.predicates = null;
  9622. return this;
  9623. }
  9624. // Get the set of all alts mentioned by all ATN configurations in this
  9625. // DFA state.
  9626. DFAState.prototype.getAltSet = function() {
  9627. var alts = new Set();
  9628. if (this.configs !== null) {
  9629. for (var i = 0; i < this.configs.length; i++) {
  9630. var c = this.configs[i];
  9631. alts.add(c.alt);
  9632. }
  9633. }
  9634. if (alts.length === 0) {
  9635. return null;
  9636. } else {
  9637. return alts;
  9638. }
  9639. };
  9640. // Two {@link DFAState} instances are equal if their ATN configuration sets
  9641. // are the same. This method is used to see if a state already exists.
  9642. //
  9643. // <p>Because the number of alternatives and number of ATN configurations are
  9644. // finite, there is a finite number of DFA states that can be processed.
  9645. // This is necessary to show that the algorithm terminates.</p>
  9646. //
  9647. // <p>Cannot test the DFA state numbers here because in
  9648. // {@link ParserATNSimulator//addDFAState} we need to know if any other state
  9649. // exists that has this exact set of ATN configurations. The
  9650. // {@link //stateNumber} is irrelevant.</p>
  9651. DFAState.prototype.equals = function(other) {
  9652. // compare set of ATN configurations in this set with other
  9653. return this === other ||
  9654. (other instanceof DFAState &&
  9655. this.configs.equals(other.configs));
  9656. };
  9657. DFAState.prototype.toString = function() {
  9658. var s = "" + this.stateNumber + ":" + this.configs;
  9659. if(this.isAcceptState) {
  9660. s = s + "=>";
  9661. if (this.predicates !== null)
  9662. s = s + this.predicates;
  9663. else
  9664. s = s + this.prediction;
  9665. }
  9666. return s;
  9667. };
  9668. DFAState.prototype.hashCode = function() {
  9669. var hash = new Hash();
  9670. hash.update(this.configs);
  9671. if(this.isAcceptState) {
  9672. if (this.predicates !== null)
  9673. hash.update(this.predicates);
  9674. else
  9675. hash.update(this.prediction);
  9676. }
  9677. return hash.finish();
  9678. };
  9679. exports.DFAState = DFAState;
  9680. exports.PredPrediction = PredPrediction;
  9681. /***/ }),
  9682. /***/ "./node_modules/antlr4/dfa/index.js":
  9683. /*!******************************************!*\
  9684. !*** ./node_modules/antlr4/dfa/index.js ***!
  9685. \******************************************/
  9686. /*! no static exports found */
  9687. /***/ (function(module, exports, __webpack_require__) {
  9688. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9689. * Use of this file is governed by the BSD 3-clause license that
  9690. * can be found in the LICENSE.txt file in the project root.
  9691. */
  9692. exports.DFA = __webpack_require__(/*! ./DFA */ "./node_modules/antlr4/dfa/DFA.js").DFA;
  9693. exports.DFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").DFASerializer;
  9694. exports.LexerDFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").LexerDFASerializer;
  9695. exports.PredPrediction = __webpack_require__(/*! ./DFAState */ "./node_modules/antlr4/dfa/DFAState.js").PredPrediction;
  9696. /***/ }),
  9697. /***/ "./node_modules/antlr4/error/DiagnosticErrorListener.js":
  9698. /*!**************************************************************!*\
  9699. !*** ./node_modules/antlr4/error/DiagnosticErrorListener.js ***!
  9700. \**************************************************************/
  9701. /*! no static exports found */
  9702. /***/ (function(module, exports, __webpack_require__) {
  9703. //
  9704. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9705. * Use of this file is governed by the BSD 3-clause license that
  9706. * can be found in the LICENSE.txt file in the project root.
  9707. */
  9708. //
  9709. //
  9710. // This implementation of {@link ANTLRErrorListener} can be used to identify
  9711. // certain potential correctness and performance problems in grammars. "Reports"
  9712. // are made by calling {@link Parser//notifyErrorListeners} with the appropriate
  9713. // message.
  9714. //
  9715. // <ul>
  9716. // <li><b>Ambiguities</b>: These are cases where more than one path through the
  9717. // grammar can match the input.</li>
  9718. // <li><b>Weak context sensitivity</b>: These are cases where full-context
  9719. // prediction resolved an SLL conflict to a unique alternative which equaled the
  9720. // minimum alternative of the SLL conflict.</li>
  9721. // <li><b>Strong (forced) context sensitivity</b>: These are cases where the
  9722. // full-context prediction resolved an SLL conflict to a unique alternative,
  9723. // <em>and</em> the minimum alternative of the SLL conflict was found to not be
  9724. // a truly viable alternative. Two-stage parsing cannot be used for inputs where
  9725. // this situation occurs.</li>
  9726. // </ul>
  9727. var BitSet = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").BitSet;
  9728. var ErrorListener = __webpack_require__(/*! ./ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ErrorListener;
  9729. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  9730. function DiagnosticErrorListener(exactOnly) {
  9731. ErrorListener.call(this);
  9732. exactOnly = exactOnly || true;
  9733. // whether all ambiguities or only exact ambiguities are reported.
  9734. this.exactOnly = exactOnly;
  9735. return this;
  9736. }
  9737. DiagnosticErrorListener.prototype = Object.create(ErrorListener.prototype);
  9738. DiagnosticErrorListener.prototype.constructor = DiagnosticErrorListener;
  9739. DiagnosticErrorListener.prototype.reportAmbiguity = function(recognizer, dfa,
  9740. startIndex, stopIndex, exact, ambigAlts, configs) {
  9741. if (this.exactOnly && !exact) {
  9742. return;
  9743. }
  9744. var msg = "reportAmbiguity d=" +
  9745. this.getDecisionDescription(recognizer, dfa) +
  9746. ": ambigAlts=" +
  9747. this.getConflictingAlts(ambigAlts, configs) +
  9748. ", input='" +
  9749. recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'";
  9750. recognizer.notifyErrorListeners(msg);
  9751. };
  9752. DiagnosticErrorListener.prototype.reportAttemptingFullContext = function(
  9753. recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
  9754. var msg = "reportAttemptingFullContext d=" +
  9755. this.getDecisionDescription(recognizer, dfa) +
  9756. ", input='" +
  9757. recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'";
  9758. recognizer.notifyErrorListeners(msg);
  9759. };
  9760. DiagnosticErrorListener.prototype.reportContextSensitivity = function(
  9761. recognizer, dfa, startIndex, stopIndex, prediction, configs) {
  9762. var msg = "reportContextSensitivity d=" +
  9763. this.getDecisionDescription(recognizer, dfa) +
  9764. ", input='" +
  9765. recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'";
  9766. recognizer.notifyErrorListeners(msg);
  9767. };
  9768. DiagnosticErrorListener.prototype.getDecisionDescription = function(recognizer, dfa) {
  9769. var decision = dfa.decision;
  9770. var ruleIndex = dfa.atnStartState.ruleIndex;
  9771. var ruleNames = recognizer.ruleNames;
  9772. if (ruleIndex < 0 || ruleIndex >= ruleNames.length) {
  9773. return "" + decision;
  9774. }
  9775. var ruleName = ruleNames[ruleIndex] || null;
  9776. if (ruleName === null || ruleName.length === 0) {
  9777. return "" + decision;
  9778. }
  9779. return "" + decision + " (" + ruleName + ")";
  9780. };
  9781. //
  9782. // Computes the set of conflicting or ambiguous alternatives from a
  9783. // configuration set, if that information was not already provided by the
  9784. // parser.
  9785. //
  9786. // @param reportedAlts The set of conflicting or ambiguous alternatives, as
  9787. // reported by the parser.
  9788. // @param configs The conflicting or ambiguous configuration set.
  9789. // @return Returns {@code reportedAlts} if it is not {@code null}, otherwise
  9790. // returns the set of alternatives represented in {@code configs}.
  9791. //
  9792. DiagnosticErrorListener.prototype.getConflictingAlts = function(reportedAlts, configs) {
  9793. if (reportedAlts !== null) {
  9794. return reportedAlts;
  9795. }
  9796. var result = new BitSet();
  9797. for (var i = 0; i < configs.items.length; i++) {
  9798. result.add(configs.items[i].alt);
  9799. }
  9800. return "{" + result.values().join(", ") + "}";
  9801. };
  9802. exports.DiagnosticErrorListener = DiagnosticErrorListener;
  9803. /***/ }),
  9804. /***/ "./node_modules/antlr4/error/ErrorListener.js":
  9805. /*!****************************************************!*\
  9806. !*** ./node_modules/antlr4/error/ErrorListener.js ***!
  9807. \****************************************************/
  9808. /*! no static exports found */
  9809. /***/ (function(module, exports) {
  9810. //
  9811. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9812. * Use of this file is governed by the BSD 3-clause license that
  9813. * can be found in the LICENSE.txt file in the project root.
  9814. */
  9815. // Provides an empty default implementation of {@link ANTLRErrorListener}. The
  9816. // default implementation of each method does nothing, but can be overridden as
  9817. // necessary.
  9818. function ErrorListener() {
  9819. return this;
  9820. }
  9821. ErrorListener.prototype.syntaxError = function(recognizer, offendingSymbol, line, column, msg, e) {
  9822. };
  9823. ErrorListener.prototype.reportAmbiguity = function(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {
  9824. };
  9825. ErrorListener.prototype.reportAttemptingFullContext = function(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
  9826. };
  9827. ErrorListener.prototype.reportContextSensitivity = function(recognizer, dfa, startIndex, stopIndex, prediction, configs) {
  9828. };
  9829. function ConsoleErrorListener() {
  9830. ErrorListener.call(this);
  9831. return this;
  9832. }
  9833. ConsoleErrorListener.prototype = Object.create(ErrorListener.prototype);
  9834. ConsoleErrorListener.prototype.constructor = ConsoleErrorListener;
  9835. //
  9836. // Provides a default instance of {@link ConsoleErrorListener}.
  9837. //
  9838. ConsoleErrorListener.INSTANCE = new ConsoleErrorListener();
  9839. //
  9840. // {@inheritDoc}
  9841. //
  9842. // <p>
  9843. // This implementation prints messages to {@link System//err} containing the
  9844. // values of {@code line}, {@code charPositionInLine}, and {@code msg} using
  9845. // the following format.</p>
  9846. //
  9847. // <pre>
  9848. // line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>
  9849. // </pre>
  9850. //
  9851. ConsoleErrorListener.prototype.syntaxError = function(recognizer, offendingSymbol, line, column, msg, e) {
  9852. console.error("line " + line + ":" + column + " " + msg);
  9853. };
  9854. function ProxyErrorListener(delegates) {
  9855. ErrorListener.call(this);
  9856. if (delegates===null) {
  9857. throw "delegates";
  9858. }
  9859. this.delegates = delegates;
  9860. return this;
  9861. }
  9862. ProxyErrorListener.prototype = Object.create(ErrorListener.prototype);
  9863. ProxyErrorListener.prototype.constructor = ProxyErrorListener;
  9864. ProxyErrorListener.prototype.syntaxError = function(recognizer, offendingSymbol, line, column, msg, e) {
  9865. this.delegates.map(function(d) { d.syntaxError(recognizer, offendingSymbol, line, column, msg, e); });
  9866. };
  9867. ProxyErrorListener.prototype.reportAmbiguity = function(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {
  9868. this.delegates.map(function(d) { d.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs); });
  9869. };
  9870. ProxyErrorListener.prototype.reportAttemptingFullContext = function(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
  9871. this.delegates.map(function(d) { d.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs); });
  9872. };
  9873. ProxyErrorListener.prototype.reportContextSensitivity = function(recognizer, dfa, startIndex, stopIndex, prediction, configs) {
  9874. this.delegates.map(function(d) { d.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs); });
  9875. };
  9876. exports.ErrorListener = ErrorListener;
  9877. exports.ConsoleErrorListener = ConsoleErrorListener;
  9878. exports.ProxyErrorListener = ProxyErrorListener;
  9879. /***/ }),
  9880. /***/ "./node_modules/antlr4/error/ErrorStrategy.js":
  9881. /*!****************************************************!*\
  9882. !*** ./node_modules/antlr4/error/ErrorStrategy.js ***!
  9883. \****************************************************/
  9884. /*! no static exports found */
  9885. /***/ (function(module, exports, __webpack_require__) {
  9886. //
  9887. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9888. * Use of this file is governed by the BSD 3-clause license that
  9889. * can be found in the LICENSE.txt file in the project root.
  9890. */
  9891. //
  9892. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  9893. var Errors = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js");
  9894. var NoViableAltException = Errors.NoViableAltException;
  9895. var InputMismatchException = Errors.InputMismatchException;
  9896. var FailedPredicateException = Errors.FailedPredicateException;
  9897. var ParseCancellationException = Errors.ParseCancellationException;
  9898. var ATNState = __webpack_require__(/*! ./../atn/ATNState */ "./node_modules/antlr4/atn/ATNState.js").ATNState;
  9899. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  9900. var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  9901. function ErrorStrategy() {
  9902. }
  9903. ErrorStrategy.prototype.reset = function(recognizer){
  9904. };
  9905. ErrorStrategy.prototype.recoverInline = function(recognizer){
  9906. };
  9907. ErrorStrategy.prototype.recover = function(recognizer, e){
  9908. };
  9909. ErrorStrategy.prototype.sync = function(recognizer){
  9910. };
  9911. ErrorStrategy.prototype.inErrorRecoveryMode = function(recognizer){
  9912. };
  9913. ErrorStrategy.prototype.reportError = function(recognizer){
  9914. };
  9915. // This is the default implementation of {@link ANTLRErrorStrategy} used for
  9916. // error reporting and recovery in ANTLR parsers.
  9917. //
  9918. function DefaultErrorStrategy() {
  9919. ErrorStrategy.call(this);
  9920. // Indicates whether the error strategy is currently "recovering from an
  9921. // error". This is used to suppress reporting multiple error messages while
  9922. // attempting to recover from a detected syntax error.
  9923. //
  9924. // @see //inErrorRecoveryMode
  9925. //
  9926. this.errorRecoveryMode = false;
  9927. // The index into the input stream where the last error occurred.
  9928. // This is used to prevent infinite loops where an error is found
  9929. // but no token is consumed during recovery...another error is found,
  9930. // ad nauseum. This is a failsafe mechanism to guarantee that at least
  9931. // one token/tree node is consumed for two errors.
  9932. //
  9933. this.lastErrorIndex = -1;
  9934. this.lastErrorStates = null;
  9935. return this;
  9936. }
  9937. DefaultErrorStrategy.prototype = Object.create(ErrorStrategy.prototype);
  9938. DefaultErrorStrategy.prototype.constructor = DefaultErrorStrategy;
  9939. // <p>The default implementation simply calls {@link //endErrorCondition} to
  9940. // ensure that the handler is not in error recovery mode.</p>
  9941. DefaultErrorStrategy.prototype.reset = function(recognizer) {
  9942. this.endErrorCondition(recognizer);
  9943. };
  9944. //
  9945. // This method is called to enter error recovery mode when a recognition
  9946. // exception is reported.
  9947. //
  9948. // @param recognizer the parser instance
  9949. //
  9950. DefaultErrorStrategy.prototype.beginErrorCondition = function(recognizer) {
  9951. this.errorRecoveryMode = true;
  9952. };
  9953. DefaultErrorStrategy.prototype.inErrorRecoveryMode = function(recognizer) {
  9954. return this.errorRecoveryMode;
  9955. };
  9956. //
  9957. // This method is called to leave error recovery mode after recovering from
  9958. // a recognition exception.
  9959. //
  9960. // @param recognizer
  9961. //
  9962. DefaultErrorStrategy.prototype.endErrorCondition = function(recognizer) {
  9963. this.errorRecoveryMode = false;
  9964. this.lastErrorStates = null;
  9965. this.lastErrorIndex = -1;
  9966. };
  9967. //
  9968. // {@inheritDoc}
  9969. //
  9970. // <p>The default implementation simply calls {@link //endErrorCondition}.</p>
  9971. //
  9972. DefaultErrorStrategy.prototype.reportMatch = function(recognizer) {
  9973. this.endErrorCondition(recognizer);
  9974. };
  9975. //
  9976. // {@inheritDoc}
  9977. //
  9978. // <p>The default implementation returns immediately if the handler is already
  9979. // in error recovery mode. Otherwise, it calls {@link //beginErrorCondition}
  9980. // and dispatches the reporting task based on the runtime type of {@code e}
  9981. // according to the following table.</p>
  9982. //
  9983. // <ul>
  9984. // <li>{@link NoViableAltException}: Dispatches the call to
  9985. // {@link //reportNoViableAlternative}</li>
  9986. // <li>{@link InputMismatchException}: Dispatches the call to
  9987. // {@link //reportInputMismatch}</li>
  9988. // <li>{@link FailedPredicateException}: Dispatches the call to
  9989. // {@link //reportFailedPredicate}</li>
  9990. // <li>All other types: calls {@link Parser//notifyErrorListeners} to report
  9991. // the exception</li>
  9992. // </ul>
  9993. //
  9994. DefaultErrorStrategy.prototype.reportError = function(recognizer, e) {
  9995. // if we've already reported an error and have not matched a token
  9996. // yet successfully, don't report any errors.
  9997. if(this.inErrorRecoveryMode(recognizer)) {
  9998. return; // don't report spurious errors
  9999. }
  10000. this.beginErrorCondition(recognizer);
  10001. if ( e instanceof NoViableAltException ) {
  10002. this.reportNoViableAlternative(recognizer, e);
  10003. } else if ( e instanceof InputMismatchException ) {
  10004. this.reportInputMismatch(recognizer, e);
  10005. } else if ( e instanceof FailedPredicateException ) {
  10006. this.reportFailedPredicate(recognizer, e);
  10007. } else {
  10008. console.log("unknown recognition error type: " + e.constructor.name);
  10009. console.log(e.stack);
  10010. recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);
  10011. }
  10012. };
  10013. //
  10014. // {@inheritDoc}
  10015. //
  10016. // <p>The default implementation resynchronizes the parser by consuming tokens
  10017. // until we find one in the resynchronization set--loosely the set of tokens
  10018. // that can follow the current rule.</p>
  10019. //
  10020. DefaultErrorStrategy.prototype.recover = function(recognizer, e) {
  10021. if (this.lastErrorIndex===recognizer.getInputStream().index &&
  10022. this.lastErrorStates !== null && this.lastErrorStates.indexOf(recognizer.state)>=0) {
  10023. // uh oh, another error at same token index and previously-visited
  10024. // state in ATN; must be a case where LT(1) is in the recovery
  10025. // token set so nothing got consumed. Consume a single token
  10026. // at least to prevent an infinite loop; this is a failsafe.
  10027. recognizer.consume();
  10028. }
  10029. this.lastErrorIndex = recognizer._input.index;
  10030. if (this.lastErrorStates === null) {
  10031. this.lastErrorStates = [];
  10032. }
  10033. this.lastErrorStates.push(recognizer.state);
  10034. var followSet = this.getErrorRecoverySet(recognizer);
  10035. this.consumeUntil(recognizer, followSet);
  10036. };
  10037. // The default implementation of {@link ANTLRErrorStrategy//sync} makes sure
  10038. // that the current lookahead symbol is consistent with what were expecting
  10039. // at this point in the ATN. You can call this anytime but ANTLR only
  10040. // generates code to check before subrules/loops and each iteration.
  10041. //
  10042. // <p>Implements Jim Idle's magic sync mechanism in closures and optional
  10043. // subrules. E.g.,</p>
  10044. //
  10045. // <pre>
  10046. // a : sync ( stuff sync )* ;
  10047. // sync : {consume to what can follow sync} ;
  10048. // </pre>
  10049. //
  10050. // At the start of a sub rule upon error, {@link //sync} performs single
  10051. // token deletion, if possible. If it can't do that, it bails on the current
  10052. // rule and uses the default error recovery, which consumes until the
  10053. // resynchronization set of the current rule.
  10054. //
  10055. // <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block
  10056. // with an empty alternative), then the expected set includes what follows
  10057. // the subrule.</p>
  10058. //
  10059. // <p>During loop iteration, it consumes until it sees a token that can start a
  10060. // sub rule or what follows loop. Yes, that is pretty aggressive. We opt to
  10061. // stay in the loop as long as possible.</p>
  10062. //
  10063. // <p><strong>ORIGINS</strong></p>
  10064. //
  10065. // <p>Previous versions of ANTLR did a poor job of their recovery within loops.
  10066. // A single mismatch token or missing token would force the parser to bail
  10067. // out of the entire rules surrounding the loop. So, for rule</p>
  10068. //
  10069. // <pre>
  10070. // classDef : 'class' ID '{' member* '}'
  10071. // </pre>
  10072. //
  10073. // input with an extra token between members would force the parser to
  10074. // consume until it found the next class definition rather than the next
  10075. // member definition of the current class.
  10076. //
  10077. // <p>This functionality cost a little bit of effort because the parser has to
  10078. // compare token set at the start of the loop and at each iteration. If for
  10079. // some reason speed is suffering for you, you can turn off this
  10080. // functionality by simply overriding this method as a blank { }.</p>
  10081. //
  10082. DefaultErrorStrategy.prototype.sync = function(recognizer) {
  10083. // If already recovering, don't try to sync
  10084. if (this.inErrorRecoveryMode(recognizer)) {
  10085. return;
  10086. }
  10087. var s = recognizer._interp.atn.states[recognizer.state];
  10088. var la = recognizer.getTokenStream().LA(1);
  10089. // try cheaper subset first; might get lucky. seems to shave a wee bit off
  10090. var nextTokens = recognizer.atn.nextTokens(s);
  10091. if (nextTokens.contains(Token.EPSILON) || nextTokens.contains(la)) {
  10092. return;
  10093. }
  10094. switch (s.stateType) {
  10095. case ATNState.BLOCK_START:
  10096. case ATNState.STAR_BLOCK_START:
  10097. case ATNState.PLUS_BLOCK_START:
  10098. case ATNState.STAR_LOOP_ENTRY:
  10099. // report error and recover if possible
  10100. if( this.singleTokenDeletion(recognizer) !== null) {
  10101. return;
  10102. } else {
  10103. throw new InputMismatchException(recognizer);
  10104. }
  10105. break;
  10106. case ATNState.PLUS_LOOP_BACK:
  10107. case ATNState.STAR_LOOP_BACK:
  10108. this.reportUnwantedToken(recognizer);
  10109. var expecting = new IntervalSet();
  10110. expecting.addSet(recognizer.getExpectedTokens());
  10111. var whatFollowsLoopIterationOrRule = expecting.addSet(this.getErrorRecoverySet(recognizer));
  10112. this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule);
  10113. break;
  10114. default:
  10115. // do nothing if we can't identify the exact kind of ATN state
  10116. }
  10117. };
  10118. // This is called by {@link //reportError} when the exception is a
  10119. // {@link NoViableAltException}.
  10120. //
  10121. // @see //reportError
  10122. //
  10123. // @param recognizer the parser instance
  10124. // @param e the recognition exception
  10125. //
  10126. DefaultErrorStrategy.prototype.reportNoViableAlternative = function(recognizer, e) {
  10127. var tokens = recognizer.getTokenStream();
  10128. var input;
  10129. if(tokens !== null) {
  10130. if (e.startToken.type===Token.EOF) {
  10131. input = "<EOF>";
  10132. } else {
  10133. input = tokens.getText(new Interval(e.startToken.tokenIndex, e.offendingToken.tokenIndex));
  10134. }
  10135. } else {
  10136. input = "<unknown input>";
  10137. }
  10138. var msg = "no viable alternative at input " + this.escapeWSAndQuote(input);
  10139. recognizer.notifyErrorListeners(msg, e.offendingToken, e);
  10140. };
  10141. //
  10142. // This is called by {@link //reportError} when the exception is an
  10143. // {@link InputMismatchException}.
  10144. //
  10145. // @see //reportError
  10146. //
  10147. // @param recognizer the parser instance
  10148. // @param e the recognition exception
  10149. //
  10150. DefaultErrorStrategy.prototype.reportInputMismatch = function(recognizer, e) {
  10151. var msg = "mismatched input " + this.getTokenErrorDisplay(e.offendingToken) +
  10152. " expecting " + e.getExpectedTokens().toString(recognizer.literalNames, recognizer.symbolicNames);
  10153. recognizer.notifyErrorListeners(msg, e.offendingToken, e);
  10154. };
  10155. //
  10156. // This is called by {@link //reportError} when the exception is a
  10157. // {@link FailedPredicateException}.
  10158. //
  10159. // @see //reportError
  10160. //
  10161. // @param recognizer the parser instance
  10162. // @param e the recognition exception
  10163. //
  10164. DefaultErrorStrategy.prototype.reportFailedPredicate = function(recognizer, e) {
  10165. var ruleName = recognizer.ruleNames[recognizer._ctx.ruleIndex];
  10166. var msg = "rule " + ruleName + " " + e.message;
  10167. recognizer.notifyErrorListeners(msg, e.offendingToken, e);
  10168. };
  10169. // This method is called to report a syntax error which requires the removal
  10170. // of a token from the input stream. At the time this method is called, the
  10171. // erroneous symbol is current {@code LT(1)} symbol and has not yet been
  10172. // removed from the input stream. When this method returns,
  10173. // {@code recognizer} is in error recovery mode.
  10174. //
  10175. // <p>This method is called when {@link //singleTokenDeletion} identifies
  10176. // single-token deletion as a viable recovery strategy for a mismatched
  10177. // input error.</p>
  10178. //
  10179. // <p>The default implementation simply returns if the handler is already in
  10180. // error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to
  10181. // enter error recovery mode, followed by calling
  10182. // {@link Parser//notifyErrorListeners}.</p>
  10183. //
  10184. // @param recognizer the parser instance
  10185. //
  10186. DefaultErrorStrategy.prototype.reportUnwantedToken = function(recognizer) {
  10187. if (this.inErrorRecoveryMode(recognizer)) {
  10188. return;
  10189. }
  10190. this.beginErrorCondition(recognizer);
  10191. var t = recognizer.getCurrentToken();
  10192. var tokenName = this.getTokenErrorDisplay(t);
  10193. var expecting = this.getExpectedTokens(recognizer);
  10194. var msg = "extraneous input " + tokenName + " expecting " +
  10195. expecting.toString(recognizer.literalNames, recognizer.symbolicNames);
  10196. recognizer.notifyErrorListeners(msg, t, null);
  10197. };
  10198. // This method is called to report a syntax error which requires the
  10199. // insertion of a missing token into the input stream. At the time this
  10200. // method is called, the missing token has not yet been inserted. When this
  10201. // method returns, {@code recognizer} is in error recovery mode.
  10202. //
  10203. // <p>This method is called when {@link //singleTokenInsertion} identifies
  10204. // single-token insertion as a viable recovery strategy for a mismatched
  10205. // input error.</p>
  10206. //
  10207. // <p>The default implementation simply returns if the handler is already in
  10208. // error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to
  10209. // enter error recovery mode, followed by calling
  10210. // {@link Parser//notifyErrorListeners}.</p>
  10211. //
  10212. // @param recognizer the parser instance
  10213. //
  10214. DefaultErrorStrategy.prototype.reportMissingToken = function(recognizer) {
  10215. if ( this.inErrorRecoveryMode(recognizer)) {
  10216. return;
  10217. }
  10218. this.beginErrorCondition(recognizer);
  10219. var t = recognizer.getCurrentToken();
  10220. var expecting = this.getExpectedTokens(recognizer);
  10221. var msg = "missing " + expecting.toString(recognizer.literalNames, recognizer.symbolicNames) +
  10222. " at " + this.getTokenErrorDisplay(t);
  10223. recognizer.notifyErrorListeners(msg, t, null);
  10224. };
  10225. // <p>The default implementation attempts to recover from the mismatched input
  10226. // by using single token insertion and deletion as described below. If the
  10227. // recovery attempt fails, this method throws an
  10228. // {@link InputMismatchException}.</p>
  10229. //
  10230. // <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>
  10231. //
  10232. // <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the
  10233. // right token, however, then assume {@code LA(1)} is some extra spurious
  10234. // token and delete it. Then consume and return the next token (which was
  10235. // the {@code LA(2)} token) as the successful result of the match operation.</p>
  10236. //
  10237. // <p>This recovery strategy is implemented by {@link
  10238. // //singleTokenDeletion}.</p>
  10239. //
  10240. // <p><strong>MISSING TOKEN</strong> (single token insertion)</p>
  10241. //
  10242. // <p>If current token (at {@code LA(1)}) is consistent with what could come
  10243. // after the expected {@code LA(1)} token, then assume the token is missing
  10244. // and use the parser's {@link TokenFactory} to create it on the fly. The
  10245. // "insertion" is performed by returning the created token as the successful
  10246. // result of the match operation.</p>
  10247. //
  10248. // <p>This recovery strategy is implemented by {@link
  10249. // //singleTokenInsertion}.</p>
  10250. //
  10251. // <p><strong>EXAMPLE</strong></p>
  10252. //
  10253. // <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When
  10254. // the parser returns from the nested call to {@code expr}, it will have
  10255. // call chain:</p>
  10256. //
  10257. // <pre>
  10258. // stat &rarr; expr &rarr; atom
  10259. // </pre>
  10260. //
  10261. // and it will be trying to match the {@code ')'} at this point in the
  10262. // derivation:
  10263. //
  10264. // <pre>
  10265. // =&gt; ID '=' '(' INT ')' ('+' atom)* ';'
  10266. // ^
  10267. // </pre>
  10268. //
  10269. // The attempt to match {@code ')'} will fail when it sees {@code ';'} and
  10270. // call {@link //recoverInline}. To recover, it sees that {@code LA(1)==';'}
  10271. // is in the set of tokens that can follow the {@code ')'} token reference
  10272. // in rule {@code atom}. It can assume that you forgot the {@code ')'}.
  10273. //
  10274. DefaultErrorStrategy.prototype.recoverInline = function(recognizer) {
  10275. // SINGLE TOKEN DELETION
  10276. var matchedSymbol = this.singleTokenDeletion(recognizer);
  10277. if (matchedSymbol !== null) {
  10278. // we have deleted the extra token.
  10279. // now, move past ttype token as if all were ok
  10280. recognizer.consume();
  10281. return matchedSymbol;
  10282. }
  10283. // SINGLE TOKEN INSERTION
  10284. if (this.singleTokenInsertion(recognizer)) {
  10285. return this.getMissingSymbol(recognizer);
  10286. }
  10287. // even that didn't work; must throw the exception
  10288. throw new InputMismatchException(recognizer);
  10289. };
  10290. //
  10291. // This method implements the single-token insertion inline error recovery
  10292. // strategy. It is called by {@link //recoverInline} if the single-token
  10293. // deletion strategy fails to recover from the mismatched input. If this
  10294. // method returns {@code true}, {@code recognizer} will be in error recovery
  10295. // mode.
  10296. //
  10297. // <p>This method determines whether or not single-token insertion is viable by
  10298. // checking if the {@code LA(1)} input symbol could be successfully matched
  10299. // if it were instead the {@code LA(2)} symbol. If this method returns
  10300. // {@code true}, the caller is responsible for creating and inserting a
  10301. // token with the correct type to produce this behavior.</p>
  10302. //
  10303. // @param recognizer the parser instance
  10304. // @return {@code true} if single-token insertion is a viable recovery
  10305. // strategy for the current mismatched input, otherwise {@code false}
  10306. //
  10307. DefaultErrorStrategy.prototype.singleTokenInsertion = function(recognizer) {
  10308. var currentSymbolType = recognizer.getTokenStream().LA(1);
  10309. // if current token is consistent with what could come after current
  10310. // ATN state, then we know we're missing a token; error recovery
  10311. // is free to conjure up and insert the missing token
  10312. var atn = recognizer._interp.atn;
  10313. var currentState = atn.states[recognizer.state];
  10314. var next = currentState.transitions[0].target;
  10315. var expectingAtLL2 = atn.nextTokens(next, recognizer._ctx);
  10316. if (expectingAtLL2.contains(currentSymbolType) ){
  10317. this.reportMissingToken(recognizer);
  10318. return true;
  10319. } else {
  10320. return false;
  10321. }
  10322. };
  10323. // This method implements the single-token deletion inline error recovery
  10324. // strategy. It is called by {@link //recoverInline} to attempt to recover
  10325. // from mismatched input. If this method returns null, the parser and error
  10326. // handler state will not have changed. If this method returns non-null,
  10327. // {@code recognizer} will <em>not</em> be in error recovery mode since the
  10328. // returned token was a successful match.
  10329. //
  10330. // <p>If the single-token deletion is successful, this method calls
  10331. // {@link //reportUnwantedToken} to report the error, followed by
  10332. // {@link Parser//consume} to actually "delete" the extraneous token. Then,
  10333. // before returning {@link //reportMatch} is called to signal a successful
  10334. // match.</p>
  10335. //
  10336. // @param recognizer the parser instance
  10337. // @return the successfully matched {@link Token} instance if single-token
  10338. // deletion successfully recovers from the mismatched input, otherwise
  10339. // {@code null}
  10340. //
  10341. DefaultErrorStrategy.prototype.singleTokenDeletion = function(recognizer) {
  10342. var nextTokenType = recognizer.getTokenStream().LA(2);
  10343. var expecting = this.getExpectedTokens(recognizer);
  10344. if (expecting.contains(nextTokenType)) {
  10345. this.reportUnwantedToken(recognizer);
  10346. // print("recoverFromMismatchedToken deleting " \
  10347. // + str(recognizer.getTokenStream().LT(1)) \
  10348. // + " since " + str(recognizer.getTokenStream().LT(2)) \
  10349. // + " is what we want", file=sys.stderr)
  10350. recognizer.consume(); // simply delete extra token
  10351. // we want to return the token we're actually matching
  10352. var matchedSymbol = recognizer.getCurrentToken();
  10353. this.reportMatch(recognizer); // we know current token is correct
  10354. return matchedSymbol;
  10355. } else {
  10356. return null;
  10357. }
  10358. };
  10359. // Conjure up a missing token during error recovery.
  10360. //
  10361. // The recognizer attempts to recover from single missing
  10362. // symbols. But, actions might refer to that missing symbol.
  10363. // For example, x=ID {f($x);}. The action clearly assumes
  10364. // that there has been an identifier matched previously and that
  10365. // $x points at that token. If that token is missing, but
  10366. // the next token in the stream is what we want we assume that
  10367. // this token is missing and we keep going. Because we
  10368. // have to return some token to replace the missing token,
  10369. // we have to conjure one up. This method gives the user control
  10370. // over the tokens returned for missing tokens. Mostly,
  10371. // you will want to create something special for identifier
  10372. // tokens. For literals such as '{' and ',', the default
  10373. // action in the parser or tree parser works. It simply creates
  10374. // a CommonToken of the appropriate type. The text will be the token.
  10375. // If you change what tokens must be created by the lexer,
  10376. // override this method to create the appropriate tokens.
  10377. //
  10378. DefaultErrorStrategy.prototype.getMissingSymbol = function(recognizer) {
  10379. var currentSymbol = recognizer.getCurrentToken();
  10380. var expecting = this.getExpectedTokens(recognizer);
  10381. var expectedTokenType = expecting.first(); // get any element
  10382. var tokenText;
  10383. if (expectedTokenType===Token.EOF) {
  10384. tokenText = "<missing EOF>";
  10385. } else {
  10386. tokenText = "<missing " + recognizer.literalNames[expectedTokenType] + ">";
  10387. }
  10388. var current = currentSymbol;
  10389. var lookback = recognizer.getTokenStream().LT(-1);
  10390. if (current.type===Token.EOF && lookback !== null) {
  10391. current = lookback;
  10392. }
  10393. return recognizer.getTokenFactory().create(current.source,
  10394. expectedTokenType, tokenText, Token.DEFAULT_CHANNEL,
  10395. -1, -1, current.line, current.column);
  10396. };
  10397. DefaultErrorStrategy.prototype.getExpectedTokens = function(recognizer) {
  10398. return recognizer.getExpectedTokens();
  10399. };
  10400. // How should a token be displayed in an error message? The default
  10401. // is to display just the text, but during development you might
  10402. // want to have a lot of information spit out. Override in that case
  10403. // to use t.toString() (which, for CommonToken, dumps everything about
  10404. // the token). This is better than forcing you to override a method in
  10405. // your token objects because you don't have to go modify your lexer
  10406. // so that it creates a new Java type.
  10407. //
  10408. DefaultErrorStrategy.prototype.getTokenErrorDisplay = function(t) {
  10409. if (t === null) {
  10410. return "<no token>";
  10411. }
  10412. var s = t.text;
  10413. if (s === null) {
  10414. if (t.type===Token.EOF) {
  10415. s = "<EOF>";
  10416. } else {
  10417. s = "<" + t.type + ">";
  10418. }
  10419. }
  10420. return this.escapeWSAndQuote(s);
  10421. };
  10422. DefaultErrorStrategy.prototype.escapeWSAndQuote = function(s) {
  10423. s = s.replace(/\n/g,"\\n");
  10424. s = s.replace(/\r/g,"\\r");
  10425. s = s.replace(/\t/g,"\\t");
  10426. return "'" + s + "'";
  10427. };
  10428. // Compute the error recovery set for the current rule. During
  10429. // rule invocation, the parser pushes the set of tokens that can
  10430. // follow that rule reference on the stack; this amounts to
  10431. // computing FIRST of what follows the rule reference in the
  10432. // enclosing rule. See LinearApproximator.FIRST().
  10433. // This local follow set only includes tokens
  10434. // from within the rule; i.e., the FIRST computation done by
  10435. // ANTLR stops at the end of a rule.
  10436. //
  10437. // EXAMPLE
  10438. //
  10439. // When you find a "no viable alt exception", the input is not
  10440. // consistent with any of the alternatives for rule r. The best
  10441. // thing to do is to consume tokens until you see something that
  10442. // can legally follow a call to r//or* any rule that called r.
  10443. // You don't want the exact set of viable next tokens because the
  10444. // input might just be missing a token--you might consume the
  10445. // rest of the input looking for one of the missing tokens.
  10446. //
  10447. // Consider grammar:
  10448. //
  10449. // a : '[' b ']'
  10450. // | '(' b ')'
  10451. // ;
  10452. // b : c '^' INT ;
  10453. // c : ID
  10454. // | INT
  10455. // ;
  10456. //
  10457. // At each rule invocation, the set of tokens that could follow
  10458. // that rule is pushed on a stack. Here are the various
  10459. // context-sensitive follow sets:
  10460. //
  10461. // FOLLOW(b1_in_a) = FIRST(']') = ']'
  10462. // FOLLOW(b2_in_a) = FIRST(')') = ')'
  10463. // FOLLOW(c_in_b) = FIRST('^') = '^'
  10464. //
  10465. // Upon erroneous input "[]", the call chain is
  10466. //
  10467. // a -> b -> c
  10468. //
  10469. // and, hence, the follow context stack is:
  10470. //
  10471. // depth follow set start of rule execution
  10472. // 0 <EOF> a (from main())
  10473. // 1 ']' b
  10474. // 2 '^' c
  10475. //
  10476. // Notice that ')' is not included, because b would have to have
  10477. // been called from a different context in rule a for ')' to be
  10478. // included.
  10479. //
  10480. // For error recovery, we cannot consider FOLLOW(c)
  10481. // (context-sensitive or otherwise). We need the combined set of
  10482. // all context-sensitive FOLLOW sets--the set of all tokens that
  10483. // could follow any reference in the call chain. We need to
  10484. // resync to one of those tokens. Note that FOLLOW(c)='^' and if
  10485. // we resync'd to that token, we'd consume until EOF. We need to
  10486. // sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.
  10487. // In this case, for input "[]", LA(1) is ']' and in the set, so we would
  10488. // not consume anything. After printing an error, rule c would
  10489. // return normally. Rule b would not find the required '^' though.
  10490. // At this point, it gets a mismatched token error and throws an
  10491. // exception (since LA(1) is not in the viable following token
  10492. // set). The rule exception handler tries to recover, but finds
  10493. // the same recovery set and doesn't consume anything. Rule b
  10494. // exits normally returning to rule a. Now it finds the ']' (and
  10495. // with the successful match exits errorRecovery mode).
  10496. //
  10497. // So, you can see that the parser walks up the call chain looking
  10498. // for the token that was a member of the recovery set.
  10499. //
  10500. // Errors are not generated in errorRecovery mode.
  10501. //
  10502. // ANTLR's error recovery mechanism is based upon original ideas:
  10503. //
  10504. // "Algorithms + Data Structures = Programs" by Niklaus Wirth
  10505. //
  10506. // and
  10507. //
  10508. // "A note on error recovery in recursive descent parsers":
  10509. // http://portal.acm.org/citation.cfm?id=947902.947905
  10510. //
  10511. // Later, Josef Grosch had some good ideas:
  10512. //
  10513. // "Efficient and Comfortable Error Recovery in Recursive Descent
  10514. // Parsers":
  10515. // ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
  10516. //
  10517. // Like Grosch I implement context-sensitive FOLLOW sets that are combined
  10518. // at run-time upon error to avoid overhead during parsing.
  10519. //
  10520. DefaultErrorStrategy.prototype.getErrorRecoverySet = function(recognizer) {
  10521. var atn = recognizer._interp.atn;
  10522. var ctx = recognizer._ctx;
  10523. var recoverSet = new IntervalSet();
  10524. while (ctx !== null && ctx.invokingState>=0) {
  10525. // compute what follows who invoked us
  10526. var invokingState = atn.states[ctx.invokingState];
  10527. var rt = invokingState.transitions[0];
  10528. var follow = atn.nextTokens(rt.followState);
  10529. recoverSet.addSet(follow);
  10530. ctx = ctx.parentCtx;
  10531. }
  10532. recoverSet.removeOne(Token.EPSILON);
  10533. return recoverSet;
  10534. };
  10535. // Consume tokens until one matches the given token set.//
  10536. DefaultErrorStrategy.prototype.consumeUntil = function(recognizer, set) {
  10537. var ttype = recognizer.getTokenStream().LA(1);
  10538. while( ttype !== Token.EOF && !set.contains(ttype)) {
  10539. recognizer.consume();
  10540. ttype = recognizer.getTokenStream().LA(1);
  10541. }
  10542. };
  10543. //
  10544. // This implementation of {@link ANTLRErrorStrategy} responds to syntax errors
  10545. // by immediately canceling the parse operation with a
  10546. // {@link ParseCancellationException}. The implementation ensures that the
  10547. // {@link ParserRuleContext//exception} field is set for all parse tree nodes
  10548. // that were not completed prior to encountering the error.
  10549. //
  10550. // <p>
  10551. // This error strategy is useful in the following scenarios.</p>
  10552. //
  10553. // <ul>
  10554. // <li><strong>Two-stage parsing:</strong> This error strategy allows the first
  10555. // stage of two-stage parsing to immediately terminate if an error is
  10556. // encountered, and immediately fall back to the second stage. In addition to
  10557. // avoiding wasted work by attempting to recover from errors here, the empty
  10558. // implementation of {@link BailErrorStrategy//sync} improves the performance of
  10559. // the first stage.</li>
  10560. // <li><strong>Silent validation:</strong> When syntax errors are not being
  10561. // reported or logged, and the parse result is simply ignored if errors occur,
  10562. // the {@link BailErrorStrategy} avoids wasting work on recovering from errors
  10563. // when the result will be ignored either way.</li>
  10564. // </ul>
  10565. //
  10566. // <p>
  10567. // {@code myparser.setErrorHandler(new BailErrorStrategy());}</p>
  10568. //
  10569. // @see Parser//setErrorHandler(ANTLRErrorStrategy)
  10570. //
  10571. function BailErrorStrategy() {
  10572. DefaultErrorStrategy.call(this);
  10573. return this;
  10574. }
  10575. BailErrorStrategy.prototype = Object.create(DefaultErrorStrategy.prototype);
  10576. BailErrorStrategy.prototype.constructor = BailErrorStrategy;
  10577. // Instead of recovering from exception {@code e}, re-throw it wrapped
  10578. // in a {@link ParseCancellationException} so it is not caught by the
  10579. // rule function catches. Use {@link Exception//getCause()} to get the
  10580. // original {@link RecognitionException}.
  10581. //
  10582. BailErrorStrategy.prototype.recover = function(recognizer, e) {
  10583. var context = recognizer._ctx;
  10584. while (context !== null) {
  10585. context.exception = e;
  10586. context = context.parentCtx;
  10587. }
  10588. throw new ParseCancellationException(e);
  10589. };
  10590. // Make sure we don't attempt to recover inline; if the parser
  10591. // successfully recovers, it won't throw an exception.
  10592. //
  10593. BailErrorStrategy.prototype.recoverInline = function(recognizer) {
  10594. this.recover(recognizer, new InputMismatchException(recognizer));
  10595. };
  10596. // Make sure we don't attempt to recover from problems in subrules.//
  10597. BailErrorStrategy.prototype.sync = function(recognizer) {
  10598. // pass
  10599. };
  10600. exports.BailErrorStrategy = BailErrorStrategy;
  10601. exports.DefaultErrorStrategy = DefaultErrorStrategy;
  10602. /***/ }),
  10603. /***/ "./node_modules/antlr4/error/Errors.js":
  10604. /*!*********************************************!*\
  10605. !*** ./node_modules/antlr4/error/Errors.js ***!
  10606. \*********************************************/
  10607. /*! no static exports found */
  10608. /***/ (function(module, exports, __webpack_require__) {
  10609. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  10610. * Use of this file is governed by the BSD 3-clause license that
  10611. * can be found in the LICENSE.txt file in the project root.
  10612. */
  10613. // The root of the ANTLR exception hierarchy. In general, ANTLR tracks just
  10614. // 3 kinds of errors: prediction errors, failed predicate errors, and
  10615. // mismatched input errors. In each case, the parser knows where it is
  10616. // in the input, where it is in the ATN, the rule invocation stack,
  10617. // and what kind of problem occurred.
  10618. var PredicateTransition = __webpack_require__(/*! ./../atn/Transition */ "./node_modules/antlr4/atn/Transition.js").PredicateTransition;
  10619. function RecognitionException(params) {
  10620. Error.call(this);
  10621. if (!!Error.captureStackTrace) {
  10622. Error.captureStackTrace(this, RecognitionException);
  10623. } else {
  10624. var stack = new Error().stack;
  10625. }
  10626. this.message = params.message;
  10627. this.recognizer = params.recognizer;
  10628. this.input = params.input;
  10629. this.ctx = params.ctx;
  10630. // The current {@link Token} when an error occurred. Since not all streams
  10631. // support accessing symbols by index, we have to track the {@link Token}
  10632. // instance itself.
  10633. this.offendingToken = null;
  10634. // Get the ATN state number the parser was in at the time the error
  10635. // occurred. For {@link NoViableAltException} and
  10636. // {@link LexerNoViableAltException} exceptions, this is the
  10637. // {@link DecisionState} number. For others, it is the state whose outgoing
  10638. // edge we couldn't match.
  10639. this.offendingState = -1;
  10640. if (this.recognizer!==null) {
  10641. this.offendingState = this.recognizer.state;
  10642. }
  10643. return this;
  10644. }
  10645. RecognitionException.prototype = Object.create(Error.prototype);
  10646. RecognitionException.prototype.constructor = RecognitionException;
  10647. // <p>If the state number is not known, this method returns -1.</p>
  10648. //
  10649. // Gets the set of input symbols which could potentially follow the
  10650. // previously matched symbol at the time this exception was thrown.
  10651. //
  10652. // <p>If the set of expected tokens is not known and could not be computed,
  10653. // this method returns {@code null}.</p>
  10654. //
  10655. // @return The set of token types that could potentially follow the current
  10656. // state in the ATN, or {@code null} if the information is not available.
  10657. // /
  10658. RecognitionException.prototype.getExpectedTokens = function() {
  10659. if (this.recognizer!==null) {
  10660. return this.recognizer.atn.getExpectedTokens(this.offendingState, this.ctx);
  10661. } else {
  10662. return null;
  10663. }
  10664. };
  10665. RecognitionException.prototype.toString = function() {
  10666. return this.message;
  10667. };
  10668. function LexerNoViableAltException(lexer, input, startIndex, deadEndConfigs) {
  10669. RecognitionException.call(this, {message:"", recognizer:lexer, input:input, ctx:null});
  10670. this.startIndex = startIndex;
  10671. this.deadEndConfigs = deadEndConfigs;
  10672. return this;
  10673. }
  10674. LexerNoViableAltException.prototype = Object.create(RecognitionException.prototype);
  10675. LexerNoViableAltException.prototype.constructor = LexerNoViableAltException;
  10676. LexerNoViableAltException.prototype.toString = function() {
  10677. var symbol = "";
  10678. if (this.startIndex >= 0 && this.startIndex < this.input.size) {
  10679. symbol = this.input.getText((this.startIndex,this.startIndex));
  10680. }
  10681. return "LexerNoViableAltException" + symbol;
  10682. };
  10683. // Indicates that the parser could not decide which of two or more paths
  10684. // to take based upon the remaining input. It tracks the starting token
  10685. // of the offending input and also knows where the parser was
  10686. // in the various paths when the error. Reported by reportNoViableAlternative()
  10687. //
  10688. function NoViableAltException(recognizer, input, startToken, offendingToken, deadEndConfigs, ctx) {
  10689. ctx = ctx || recognizer._ctx;
  10690. offendingToken = offendingToken || recognizer.getCurrentToken();
  10691. startToken = startToken || recognizer.getCurrentToken();
  10692. input = input || recognizer.getInputStream();
  10693. RecognitionException.call(this, {message:"", recognizer:recognizer, input:input, ctx:ctx});
  10694. // Which configurations did we try at input.index() that couldn't match
  10695. // input.LT(1)?//
  10696. this.deadEndConfigs = deadEndConfigs;
  10697. // The token object at the start index; the input stream might
  10698. // not be buffering tokens so get a reference to it. (At the
  10699. // time the error occurred, of course the stream needs to keep a
  10700. // buffer all of the tokens but later we might not have access to those.)
  10701. this.startToken = startToken;
  10702. this.offendingToken = offendingToken;
  10703. }
  10704. NoViableAltException.prototype = Object.create(RecognitionException.prototype);
  10705. NoViableAltException.prototype.constructor = NoViableAltException;
  10706. // This signifies any kind of mismatched input exceptions such as
  10707. // when the current input does not match the expected token.
  10708. //
  10709. function InputMismatchException(recognizer) {
  10710. RecognitionException.call(this, {message:"", recognizer:recognizer, input:recognizer.getInputStream(), ctx:recognizer._ctx});
  10711. this.offendingToken = recognizer.getCurrentToken();
  10712. }
  10713. InputMismatchException.prototype = Object.create(RecognitionException.prototype);
  10714. InputMismatchException.prototype.constructor = InputMismatchException;
  10715. // A semantic predicate failed during validation. Validation of predicates
  10716. // occurs when normally parsing the alternative just like matching a token.
  10717. // Disambiguating predicate evaluation occurs when we test a predicate during
  10718. // prediction.
  10719. function FailedPredicateException(recognizer, predicate, message) {
  10720. RecognitionException.call(this, {message:this.formatMessage(predicate,message || null), recognizer:recognizer,
  10721. input:recognizer.getInputStream(), ctx:recognizer._ctx});
  10722. var s = recognizer._interp.atn.states[recognizer.state];
  10723. var trans = s.transitions[0];
  10724. if (trans instanceof PredicateTransition) {
  10725. this.ruleIndex = trans.ruleIndex;
  10726. this.predicateIndex = trans.predIndex;
  10727. } else {
  10728. this.ruleIndex = 0;
  10729. this.predicateIndex = 0;
  10730. }
  10731. this.predicate = predicate;
  10732. this.offendingToken = recognizer.getCurrentToken();
  10733. return this;
  10734. }
  10735. FailedPredicateException.prototype = Object.create(RecognitionException.prototype);
  10736. FailedPredicateException.prototype.constructor = FailedPredicateException;
  10737. FailedPredicateException.prototype.formatMessage = function(predicate, message) {
  10738. if (message !==null) {
  10739. return message;
  10740. } else {
  10741. return "failed predicate: {" + predicate + "}?";
  10742. }
  10743. };
  10744. function ParseCancellationException() {
  10745. Error.call(this);
  10746. Error.captureStackTrace(this, ParseCancellationException);
  10747. return this;
  10748. }
  10749. ParseCancellationException.prototype = Object.create(Error.prototype);
  10750. ParseCancellationException.prototype.constructor = ParseCancellationException;
  10751. exports.RecognitionException = RecognitionException;
  10752. exports.NoViableAltException = NoViableAltException;
  10753. exports.LexerNoViableAltException = LexerNoViableAltException;
  10754. exports.InputMismatchException = InputMismatchException;
  10755. exports.FailedPredicateException = FailedPredicateException;
  10756. exports.ParseCancellationException = ParseCancellationException;
  10757. /***/ }),
  10758. /***/ "./node_modules/antlr4/error/index.js":
  10759. /*!********************************************!*\
  10760. !*** ./node_modules/antlr4/error/index.js ***!
  10761. \********************************************/
  10762. /*! no static exports found */
  10763. /***/ (function(module, exports, __webpack_require__) {
  10764. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  10765. * Use of this file is governed by the BSD 3-clause license that
  10766. * can be found in the LICENSE.txt file in the project root.
  10767. */
  10768. exports.RecognitionException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").RecognitionException;
  10769. exports.NoViableAltException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").NoViableAltException;
  10770. exports.LexerNoViableAltException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").LexerNoViableAltException;
  10771. exports.InputMismatchException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").InputMismatchException;
  10772. exports.FailedPredicateException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").FailedPredicateException;
  10773. exports.DiagnosticErrorListener = __webpack_require__(/*! ./DiagnosticErrorListener */ "./node_modules/antlr4/error/DiagnosticErrorListener.js").DiagnosticErrorListener;
  10774. exports.BailErrorStrategy = __webpack_require__(/*! ./ErrorStrategy */ "./node_modules/antlr4/error/ErrorStrategy.js").BailErrorStrategy;
  10775. exports.ErrorListener = __webpack_require__(/*! ./ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ErrorListener;
  10776. /***/ }),
  10777. /***/ "./node_modules/antlr4/index.js":
  10778. /*!**************************************!*\
  10779. !*** ./node_modules/antlr4/index.js ***!
  10780. \**************************************/
  10781. /*! no static exports found */
  10782. /***/ (function(module, exports, __webpack_require__) {
  10783. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  10784. * Use of this file is governed by the BSD 3-clause license that
  10785. * can be found in the LICENSE.txt file in the project root.
  10786. */
  10787. exports.atn = __webpack_require__(/*! ./atn/index */ "./node_modules/antlr4/atn/index.js");
  10788. exports.codepointat = __webpack_require__(/*! ./polyfills/codepointat */ "./node_modules/antlr4/polyfills/codepointat.js");
  10789. exports.dfa = __webpack_require__(/*! ./dfa/index */ "./node_modules/antlr4/dfa/index.js");
  10790. exports.fromcodepoint = __webpack_require__(/*! ./polyfills/fromcodepoint */ "./node_modules/antlr4/polyfills/fromcodepoint.js");
  10791. exports.tree = __webpack_require__(/*! ./tree/index */ "./node_modules/antlr4/tree/index.js");
  10792. exports.error = __webpack_require__(/*! ./error/index */ "./node_modules/antlr4/error/index.js");
  10793. exports.Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  10794. exports.CharStreams = __webpack_require__(/*! ./CharStreams */ "./node_modules/antlr4/CharStreams.js").CharStreams;
  10795. exports.CommonToken = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").CommonToken;
  10796. exports.InputStream = __webpack_require__(/*! ./InputStream */ "./node_modules/antlr4/InputStream.js").InputStream;
  10797. exports.FileStream = __webpack_require__(/*! ./FileStream */ "./node_modules/antlr4/FileStream.js").FileStream;
  10798. exports.CommonTokenStream = __webpack_require__(/*! ./CommonTokenStream */ "./node_modules/antlr4/CommonTokenStream.js").CommonTokenStream;
  10799. exports.Lexer = __webpack_require__(/*! ./Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
  10800. exports.Parser = __webpack_require__(/*! ./Parser */ "./node_modules/antlr4/Parser.js").Parser;
  10801. var pc = __webpack_require__(/*! ./PredictionContext */ "./node_modules/antlr4/PredictionContext.js");
  10802. exports.PredictionContextCache = pc.PredictionContextCache;
  10803. exports.ParserRuleContext = __webpack_require__(/*! ./ParserRuleContext */ "./node_modules/antlr4/ParserRuleContext.js").ParserRuleContext;
  10804. exports.Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  10805. exports.Utils = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js");
  10806. /***/ }),
  10807. /***/ "./node_modules/antlr4/polyfills/codepointat.js":
  10808. /*!******************************************************!*\
  10809. !*** ./node_modules/antlr4/polyfills/codepointat.js ***!
  10810. \******************************************************/
  10811. /*! no static exports found */
  10812. /***/ (function(module, exports) {
  10813. /*! https://mths.be/codepointat v0.2.0 by @mathias */
  10814. if (!String.prototype.codePointAt) {
  10815. (function() {
  10816. 'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
  10817. var defineProperty = (function() {
  10818. // IE 8 only supports `Object.defineProperty` on DOM elements
  10819. try {
  10820. var object = {};
  10821. var $defineProperty = Object.defineProperty;
  10822. var result = $defineProperty(object, object, object) && $defineProperty;
  10823. } catch(error) {}
  10824. return result;
  10825. }());
  10826. var codePointAt = function(position) {
  10827. if (this == null) {
  10828. throw TypeError();
  10829. }
  10830. var string = String(this);
  10831. var size = string.length;
  10832. // `ToInteger`
  10833. var index = position ? Number(position) : 0;
  10834. if (index != index) { // better `isNaN`
  10835. index = 0;
  10836. }
  10837. // Account for out-of-bounds indices:
  10838. if (index < 0 || index >= size) {
  10839. return undefined;
  10840. }
  10841. // Get the first code unit
  10842. var first = string.charCodeAt(index);
  10843. var second;
  10844. if ( // check if it’s the start of a surrogate pair
  10845. first >= 0xD800 && first <= 0xDBFF && // high surrogate
  10846. size > index + 1 // there is a next code unit
  10847. ) {
  10848. second = string.charCodeAt(index + 1);
  10849. if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
  10850. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  10851. return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  10852. }
  10853. }
  10854. return first;
  10855. };
  10856. if (defineProperty) {
  10857. defineProperty(String.prototype, 'codePointAt', {
  10858. 'value': codePointAt,
  10859. 'configurable': true,
  10860. 'writable': true
  10861. });
  10862. } else {
  10863. String.prototype.codePointAt = codePointAt;
  10864. }
  10865. }());
  10866. }
  10867. /***/ }),
  10868. /***/ "./node_modules/antlr4/polyfills/fromcodepoint.js":
  10869. /*!********************************************************!*\
  10870. !*** ./node_modules/antlr4/polyfills/fromcodepoint.js ***!
  10871. \********************************************************/
  10872. /*! no static exports found */
  10873. /***/ (function(module, exports) {
  10874. /*! https://mths.be/fromcodepoint v0.2.1 by @mathias */
  10875. if (!String.fromCodePoint) {
  10876. (function() {
  10877. var defineProperty = (function() {
  10878. // IE 8 only supports `Object.defineProperty` on DOM elements
  10879. try {
  10880. var object = {};
  10881. var $defineProperty = Object.defineProperty;
  10882. var result = $defineProperty(object, object, object) && $defineProperty;
  10883. } catch(error) {}
  10884. return result;
  10885. }());
  10886. var stringFromCharCode = String.fromCharCode;
  10887. var floor = Math.floor;
  10888. var fromCodePoint = function(_) {
  10889. var MAX_SIZE = 0x4000;
  10890. var codeUnits = [];
  10891. var highSurrogate;
  10892. var lowSurrogate;
  10893. var index = -1;
  10894. var length = arguments.length;
  10895. if (!length) {
  10896. return '';
  10897. }
  10898. var result = '';
  10899. while (++index < length) {
  10900. var codePoint = Number(arguments[index]);
  10901. if (
  10902. !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
  10903. codePoint < 0 || // not a valid Unicode code point
  10904. codePoint > 0x10FFFF || // not a valid Unicode code point
  10905. floor(codePoint) != codePoint // not an integer
  10906. ) {
  10907. throw RangeError('Invalid code point: ' + codePoint);
  10908. }
  10909. if (codePoint <= 0xFFFF) { // BMP code point
  10910. codeUnits.push(codePoint);
  10911. } else { // Astral code point; split in surrogate halves
  10912. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  10913. codePoint -= 0x10000;
  10914. highSurrogate = (codePoint >> 10) + 0xD800;
  10915. lowSurrogate = (codePoint % 0x400) + 0xDC00;
  10916. codeUnits.push(highSurrogate, lowSurrogate);
  10917. }
  10918. if (index + 1 == length || codeUnits.length > MAX_SIZE) {
  10919. result += stringFromCharCode.apply(null, codeUnits);
  10920. codeUnits.length = 0;
  10921. }
  10922. }
  10923. return result;
  10924. };
  10925. if (defineProperty) {
  10926. defineProperty(String, 'fromCodePoint', {
  10927. 'value': fromCodePoint,
  10928. 'configurable': true,
  10929. 'writable': true
  10930. });
  10931. } else {
  10932. String.fromCodePoint = fromCodePoint;
  10933. }
  10934. }());
  10935. }
  10936. /***/ }),
  10937. /***/ "./node_modules/antlr4/tree/Tree.js":
  10938. /*!******************************************!*\
  10939. !*** ./node_modules/antlr4/tree/Tree.js ***!
  10940. \******************************************/
  10941. /*! no static exports found */
  10942. /***/ (function(module, exports, __webpack_require__) {
  10943. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  10944. * Use of this file is governed by the BSD 3-clause license that
  10945. * can be found in the LICENSE.txt file in the project root.
  10946. */
  10947. ///
  10948. // The basic notion of a tree has a parent, a payload, and a list of children.
  10949. // It is the most abstract interface for all the trees used by ANTLR.
  10950. ///
  10951. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  10952. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  10953. var INVALID_INTERVAL = new Interval(-1, -2);
  10954. var Utils = __webpack_require__(/*! ../Utils.js */ "./node_modules/antlr4/Utils.js");
  10955. function Tree() {
  10956. return this;
  10957. }
  10958. function SyntaxTree() {
  10959. Tree.call(this);
  10960. return this;
  10961. }
  10962. SyntaxTree.prototype = Object.create(Tree.prototype);
  10963. SyntaxTree.prototype.constructor = SyntaxTree;
  10964. function ParseTree() {
  10965. SyntaxTree.call(this);
  10966. return this;
  10967. }
  10968. ParseTree.prototype = Object.create(SyntaxTree.prototype);
  10969. ParseTree.prototype.constructor = ParseTree;
  10970. function RuleNode() {
  10971. ParseTree.call(this);
  10972. return this;
  10973. }
  10974. RuleNode.prototype = Object.create(ParseTree.prototype);
  10975. RuleNode.prototype.constructor = RuleNode;
  10976. function TerminalNode() {
  10977. ParseTree.call(this);
  10978. return this;
  10979. }
  10980. TerminalNode.prototype = Object.create(ParseTree.prototype);
  10981. TerminalNode.prototype.constructor = TerminalNode;
  10982. function ErrorNode() {
  10983. TerminalNode.call(this);
  10984. return this;
  10985. }
  10986. ErrorNode.prototype = Object.create(TerminalNode.prototype);
  10987. ErrorNode.prototype.constructor = ErrorNode;
  10988. function ParseTreeVisitor() {
  10989. return this;
  10990. }
  10991. ParseTreeVisitor.prototype.visit = function(ctx) {
  10992. if (Array.isArray(ctx)) {
  10993. return ctx.map(function(child) {
  10994. return child.accept(this);
  10995. }, this);
  10996. } else {
  10997. return ctx.accept(this);
  10998. }
  10999. };
  11000. ParseTreeVisitor.prototype.visitChildren = function(ctx) {
  11001. if (ctx.children) {
  11002. return this.visit(ctx.children);
  11003. } else {
  11004. return null;
  11005. }
  11006. }
  11007. ParseTreeVisitor.prototype.visitTerminal = function(node) {
  11008. };
  11009. ParseTreeVisitor.prototype.visitErrorNode = function(node) {
  11010. };
  11011. function ParseTreeListener() {
  11012. return this;
  11013. }
  11014. ParseTreeListener.prototype.visitTerminal = function(node) {
  11015. };
  11016. ParseTreeListener.prototype.visitErrorNode = function(node) {
  11017. };
  11018. ParseTreeListener.prototype.enterEveryRule = function(node) {
  11019. };
  11020. ParseTreeListener.prototype.exitEveryRule = function(node) {
  11021. };
  11022. function TerminalNodeImpl(symbol) {
  11023. TerminalNode.call(this);
  11024. this.parentCtx = null;
  11025. this.symbol = symbol;
  11026. return this;
  11027. }
  11028. TerminalNodeImpl.prototype = Object.create(TerminalNode.prototype);
  11029. TerminalNodeImpl.prototype.constructor = TerminalNodeImpl;
  11030. TerminalNodeImpl.prototype.getChild = function(i) {
  11031. return null;
  11032. };
  11033. TerminalNodeImpl.prototype.getSymbol = function() {
  11034. return this.symbol;
  11035. };
  11036. TerminalNodeImpl.prototype.getParent = function() {
  11037. return this.parentCtx;
  11038. };
  11039. TerminalNodeImpl.prototype.getPayload = function() {
  11040. return this.symbol;
  11041. };
  11042. TerminalNodeImpl.prototype.getSourceInterval = function() {
  11043. if (this.symbol === null) {
  11044. return INVALID_INTERVAL;
  11045. }
  11046. var tokenIndex = this.symbol.tokenIndex;
  11047. return new Interval(tokenIndex, tokenIndex);
  11048. };
  11049. TerminalNodeImpl.prototype.getChildCount = function() {
  11050. return 0;
  11051. };
  11052. TerminalNodeImpl.prototype.accept = function(visitor) {
  11053. return visitor.visitTerminal(this);
  11054. };
  11055. TerminalNodeImpl.prototype.getText = function() {
  11056. return this.symbol.text;
  11057. };
  11058. TerminalNodeImpl.prototype.toString = function() {
  11059. if (this.symbol.type === Token.EOF) {
  11060. return "<EOF>";
  11061. } else {
  11062. return this.symbol.text;
  11063. }
  11064. };
  11065. // Represents a token that was consumed during resynchronization
  11066. // rather than during a valid match operation. For example,
  11067. // we will create this kind of a node during single token insertion
  11068. // and deletion as well as during "consume until error recovery set"
  11069. // upon no viable alternative exceptions.
  11070. function ErrorNodeImpl(token) {
  11071. TerminalNodeImpl.call(this, token);
  11072. return this;
  11073. }
  11074. ErrorNodeImpl.prototype = Object.create(TerminalNodeImpl.prototype);
  11075. ErrorNodeImpl.prototype.constructor = ErrorNodeImpl;
  11076. ErrorNodeImpl.prototype.isErrorNode = function() {
  11077. return true;
  11078. };
  11079. ErrorNodeImpl.prototype.accept = function(visitor) {
  11080. return visitor.visitErrorNode(this);
  11081. };
  11082. function ParseTreeWalker() {
  11083. return this;
  11084. }
  11085. ParseTreeWalker.prototype.walk = function(listener, t) {
  11086. var errorNode = t instanceof ErrorNode ||
  11087. (t.isErrorNode !== undefined && t.isErrorNode());
  11088. if (errorNode) {
  11089. listener.visitErrorNode(t);
  11090. } else if (t instanceof TerminalNode) {
  11091. listener.visitTerminal(t);
  11092. } else {
  11093. this.enterRule(listener, t);
  11094. for (var i = 0; i < t.getChildCount(); i++) {
  11095. var child = t.getChild(i);
  11096. this.walk(listener, child);
  11097. }
  11098. this.exitRule(listener, t);
  11099. }
  11100. };
  11101. //
  11102. // The discovery of a rule node, involves sending two events: the generic
  11103. // {@link ParseTreeListener//enterEveryRule} and a
  11104. // {@link RuleContext}-specific event. First we trigger the generic and then
  11105. // the rule specific. We to them in reverse order upon finishing the node.
  11106. //
  11107. ParseTreeWalker.prototype.enterRule = function(listener, r) {
  11108. var ctx = r.getRuleContext();
  11109. listener.enterEveryRule(ctx);
  11110. ctx.enterRule(listener);
  11111. };
  11112. ParseTreeWalker.prototype.exitRule = function(listener, r) {
  11113. var ctx = r.getRuleContext();
  11114. ctx.exitRule(listener);
  11115. listener.exitEveryRule(ctx);
  11116. };
  11117. ParseTreeWalker.DEFAULT = new ParseTreeWalker();
  11118. exports.RuleNode = RuleNode;
  11119. exports.ErrorNode = ErrorNode;
  11120. exports.TerminalNode = TerminalNode;
  11121. exports.ErrorNodeImpl = ErrorNodeImpl;
  11122. exports.TerminalNodeImpl = TerminalNodeImpl;
  11123. exports.ParseTreeListener = ParseTreeListener;
  11124. exports.ParseTreeVisitor = ParseTreeVisitor;
  11125. exports.ParseTreeWalker = ParseTreeWalker;
  11126. exports.INVALID_INTERVAL = INVALID_INTERVAL;
  11127. /***/ }),
  11128. /***/ "./node_modules/antlr4/tree/Trees.js":
  11129. /*!*******************************************!*\
  11130. !*** ./node_modules/antlr4/tree/Trees.js ***!
  11131. \*******************************************/
  11132. /*! no static exports found */
  11133. /***/ (function(module, exports, __webpack_require__) {
  11134. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  11135. * Use of this file is governed by the BSD 3-clause license that
  11136. * can be found in the LICENSE.txt file in the project root.
  11137. */
  11138. var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
  11139. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  11140. var RuleNode = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js").RuleNode;
  11141. var ErrorNode = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js").ErrorNode;
  11142. var TerminalNode = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js").TerminalNode;
  11143. var ParserRuleContext = __webpack_require__(/*! ./../ParserRuleContext */ "./node_modules/antlr4/ParserRuleContext.js").ParserRuleContext;
  11144. var RuleContext = __webpack_require__(/*! ./../RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
  11145. var INVALID_ALT_NUMBER = __webpack_require__(/*! ./../atn/ATN */ "./node_modules/antlr4/atn/ATN.js").INVALID_ALT_NUMBER;
  11146. /** A set of utility routines useful for all kinds of ANTLR trees. */
  11147. function Trees() {
  11148. }
  11149. // Print out a whole tree in LISP form. {@link //getNodeText} is used on the
  11150. // node payloads to get the text for the nodes. Detect
  11151. // parse trees and extract data appropriately.
  11152. Trees.toStringTree = function(tree, ruleNames, recog) {
  11153. ruleNames = ruleNames || null;
  11154. recog = recog || null;
  11155. if(recog!==null) {
  11156. ruleNames = recog.ruleNames;
  11157. }
  11158. var s = Trees.getNodeText(tree, ruleNames);
  11159. s = Utils.escapeWhitespace(s, false);
  11160. var c = tree.getChildCount();
  11161. if(c===0) {
  11162. return s;
  11163. }
  11164. var res = "(" + s + ' ';
  11165. if(c>0) {
  11166. s = Trees.toStringTree(tree.getChild(0), ruleNames);
  11167. res = res.concat(s);
  11168. }
  11169. for(var i=1;i<c;i++) {
  11170. s = Trees.toStringTree(tree.getChild(i), ruleNames);
  11171. res = res.concat(' ' + s);
  11172. }
  11173. res = res.concat(")");
  11174. return res;
  11175. };
  11176. Trees.getNodeText = function(t, ruleNames, recog) {
  11177. ruleNames = ruleNames || null;
  11178. recog = recog || null;
  11179. if(recog!==null) {
  11180. ruleNames = recog.ruleNames;
  11181. }
  11182. if(ruleNames!==null) {
  11183. if (t instanceof RuleContext) {
  11184. var altNumber = t.getAltNumber();
  11185. if ( altNumber!=INVALID_ALT_NUMBER ) {
  11186. return ruleNames[t.ruleIndex]+":"+altNumber;
  11187. }
  11188. return ruleNames[t.ruleIndex];
  11189. } else if ( t instanceof ErrorNode) {
  11190. return t.toString();
  11191. } else if(t instanceof TerminalNode) {
  11192. if(t.symbol!==null) {
  11193. return t.symbol.text;
  11194. }
  11195. }
  11196. }
  11197. // no recog for rule names
  11198. var payload = t.getPayload();
  11199. if (payload instanceof Token ) {
  11200. return payload.text;
  11201. }
  11202. return t.getPayload().toString();
  11203. };
  11204. // Return ordered list of all children of this node
  11205. Trees.getChildren = function(t) {
  11206. var list = [];
  11207. for(var i=0;i<t.getChildCount();i++) {
  11208. list.push(t.getChild(i));
  11209. }
  11210. return list;
  11211. };
  11212. // Return a list of all ancestors of this node. The first node of
  11213. // list is the root and the last is the parent of this node.
  11214. //
  11215. Trees.getAncestors = function(t) {
  11216. var ancestors = [];
  11217. t = t.getParent();
  11218. while(t!==null) {
  11219. ancestors = [t].concat(ancestors);
  11220. t = t.getParent();
  11221. }
  11222. return ancestors;
  11223. };
  11224. Trees.findAllTokenNodes = function(t, ttype) {
  11225. return Trees.findAllNodes(t, ttype, true);
  11226. };
  11227. Trees.findAllRuleNodes = function(t, ruleIndex) {
  11228. return Trees.findAllNodes(t, ruleIndex, false);
  11229. };
  11230. Trees.findAllNodes = function(t, index, findTokens) {
  11231. var nodes = [];
  11232. Trees._findAllNodes(t, index, findTokens, nodes);
  11233. return nodes;
  11234. };
  11235. Trees._findAllNodes = function(t, index, findTokens, nodes) {
  11236. // check this node (the root) first
  11237. if(findTokens && (t instanceof TerminalNode)) {
  11238. if(t.symbol.type===index) {
  11239. nodes.push(t);
  11240. }
  11241. } else if(!findTokens && (t instanceof ParserRuleContext)) {
  11242. if(t.ruleIndex===index) {
  11243. nodes.push(t);
  11244. }
  11245. }
  11246. // check children
  11247. for(var i=0;i<t.getChildCount();i++) {
  11248. Trees._findAllNodes(t.getChild(i), index, findTokens, nodes);
  11249. }
  11250. };
  11251. Trees.descendants = function(t) {
  11252. var nodes = [t];
  11253. for(var i=0;i<t.getChildCount();i++) {
  11254. nodes = nodes.concat(Trees.descendants(t.getChild(i)));
  11255. }
  11256. return nodes;
  11257. };
  11258. exports.Trees = Trees;
  11259. /***/ }),
  11260. /***/ "./node_modules/antlr4/tree/index.js":
  11261. /*!*******************************************!*\
  11262. !*** ./node_modules/antlr4/tree/index.js ***!
  11263. \*******************************************/
  11264. /*! no static exports found */
  11265. /***/ (function(module, exports, __webpack_require__) {
  11266. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  11267. * Use of this file is governed by the BSD 3-clause license that
  11268. * can be found in the LICENSE.txt file in the project root.
  11269. */
  11270. var Tree = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js");
  11271. exports.Trees = __webpack_require__(/*! ./Trees */ "./node_modules/antlr4/tree/Trees.js").Trees;
  11272. exports.RuleNode = Tree.RuleNode;
  11273. exports.ParseTreeListener = Tree.ParseTreeListener;
  11274. exports.ParseTreeVisitor = Tree.ParseTreeVisitor;
  11275. exports.ParseTreeWalker = Tree.ParseTreeWalker;
  11276. /***/ }),
  11277. /***/ "./node_modules/codemirror/addon/edit/closebrackets.js":
  11278. /*!*************************************************************!*\
  11279. !*** ./node_modules/codemirror/addon/edit/closebrackets.js ***!
  11280. \*************************************************************/
  11281. /*! no static exports found */
  11282. /***/ (function(module, exports, __webpack_require__) {
  11283. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11284. // Distributed under an MIT license: https://codemirror.net/LICENSE
  11285. (function(mod) {
  11286. if (true) // CommonJS
  11287. mod(__webpack_require__(/*! ../../lib/codemirror */ "./node_modules/codemirror/lib/codemirror.js"));
  11288. else {}
  11289. })(function(CodeMirror) {
  11290. var defaults = {
  11291. pairs: "()[]{}''\"\"",
  11292. closeBefore: ")]}'\":;>",
  11293. triples: "",
  11294. explode: "[]{}"
  11295. };
  11296. var Pos = CodeMirror.Pos;
  11297. CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
  11298. if (old && old != CodeMirror.Init) {
  11299. cm.removeKeyMap(keyMap);
  11300. cm.state.closeBrackets = null;
  11301. }
  11302. if (val) {
  11303. ensureBound(getOption(val, "pairs"))
  11304. cm.state.closeBrackets = val;
  11305. cm.addKeyMap(keyMap);
  11306. }
  11307. });
  11308. function getOption(conf, name) {
  11309. if (name == "pairs" && typeof conf == "string") return conf;
  11310. if (typeof conf == "object" && conf[name] != null) return conf[name];
  11311. return defaults[name];
  11312. }
  11313. var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
  11314. function ensureBound(chars) {
  11315. for (var i = 0; i < chars.length; i++) {
  11316. var ch = chars.charAt(i), key = "'" + ch + "'"
  11317. if (!keyMap[key]) keyMap[key] = handler(ch)
  11318. }
  11319. }
  11320. ensureBound(defaults.pairs + "`")
  11321. function handler(ch) {
  11322. return function(cm) { return handleChar(cm, ch); };
  11323. }
  11324. function getConfig(cm) {
  11325. var deflt = cm.state.closeBrackets;
  11326. if (!deflt || deflt.override) return deflt;
  11327. var mode = cm.getModeAt(cm.getCursor());
  11328. return mode.closeBrackets || deflt;
  11329. }
  11330. function handleBackspace(cm) {
  11331. var conf = getConfig(cm);
  11332. if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
  11333. var pairs = getOption(conf, "pairs");
  11334. var ranges = cm.listSelections();
  11335. for (var i = 0; i < ranges.length; i++) {
  11336. if (!ranges[i].empty()) return CodeMirror.Pass;
  11337. var around = charsAround(cm, ranges[i].head);
  11338. if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
  11339. }
  11340. for (var i = ranges.length - 1; i >= 0; i--) {
  11341. var cur = ranges[i].head;
  11342. cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete");
  11343. }
  11344. }
  11345. function handleEnter(cm) {
  11346. var conf = getConfig(cm);
  11347. var explode = conf && getOption(conf, "explode");
  11348. if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;
  11349. var ranges = cm.listSelections();
  11350. for (var i = 0; i < ranges.length; i++) {
  11351. if (!ranges[i].empty()) return CodeMirror.Pass;
  11352. var around = charsAround(cm, ranges[i].head);
  11353. if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
  11354. }
  11355. cm.operation(function() {
  11356. var linesep = cm.lineSeparator() || "\n";
  11357. cm.replaceSelection(linesep + linesep, null);
  11358. cm.execCommand("goCharLeft");
  11359. ranges = cm.listSelections();
  11360. for (var i = 0; i < ranges.length; i++) {
  11361. var line = ranges[i].head.line;
  11362. cm.indentLine(line, null, true);
  11363. cm.indentLine(line + 1, null, true);
  11364. }
  11365. });
  11366. }
  11367. function contractSelection(sel) {
  11368. var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
  11369. return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
  11370. head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
  11371. }
  11372. function handleChar(cm, ch) {
  11373. var conf = getConfig(cm);
  11374. if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
  11375. var pairs = getOption(conf, "pairs");
  11376. var pos = pairs.indexOf(ch);
  11377. if (pos == -1) return CodeMirror.Pass;
  11378. var closeBefore = getOption(conf,"closeBefore");
  11379. var triples = getOption(conf, "triples");
  11380. var identical = pairs.charAt(pos + 1) == ch;
  11381. var ranges = cm.listSelections();
  11382. var opening = pos % 2 == 0;
  11383. var type;
  11384. for (var i = 0; i < ranges.length; i++) {
  11385. var range = ranges[i], cur = range.head, curType;
  11386. var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
  11387. if (opening && !range.empty()) {
  11388. curType = "surround";
  11389. } else if ((identical || !opening) && next == ch) {
  11390. if (identical && stringStartsAfter(cm, cur))
  11391. curType = "both";
  11392. else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
  11393. curType = "skipThree";
  11394. else
  11395. curType = "skip";
  11396. } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
  11397. cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) {
  11398. if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass;
  11399. curType = "addFour";
  11400. } else if (identical) {
  11401. var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur)
  11402. if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";
  11403. else return CodeMirror.Pass;
  11404. } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) {
  11405. curType = "both";
  11406. } else {
  11407. return CodeMirror.Pass;
  11408. }
  11409. if (!type) type = curType;
  11410. else if (type != curType) return CodeMirror.Pass;
  11411. }
  11412. var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
  11413. var right = pos % 2 ? ch : pairs.charAt(pos + 1);
  11414. cm.operation(function() {
  11415. if (type == "skip") {
  11416. cm.execCommand("goCharRight");
  11417. } else if (type == "skipThree") {
  11418. for (var i = 0; i < 3; i++)
  11419. cm.execCommand("goCharRight");
  11420. } else if (type == "surround") {
  11421. var sels = cm.getSelections();
  11422. for (var i = 0; i < sels.length; i++)
  11423. sels[i] = left + sels[i] + right;
  11424. cm.replaceSelections(sels, "around");
  11425. sels = cm.listSelections().slice();
  11426. for (var i = 0; i < sels.length; i++)
  11427. sels[i] = contractSelection(sels[i]);
  11428. cm.setSelections(sels);
  11429. } else if (type == "both") {
  11430. cm.replaceSelection(left + right, null);
  11431. cm.triggerElectric(left + right);
  11432. cm.execCommand("goCharLeft");
  11433. } else if (type == "addFour") {
  11434. cm.replaceSelection(left + left + left + left, "before");
  11435. cm.execCommand("goCharRight");
  11436. }
  11437. });
  11438. }
  11439. function charsAround(cm, pos) {
  11440. var str = cm.getRange(Pos(pos.line, pos.ch - 1),
  11441. Pos(pos.line, pos.ch + 1));
  11442. return str.length == 2 ? str : null;
  11443. }
  11444. function stringStartsAfter(cm, pos) {
  11445. var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
  11446. return /\bstring/.test(token.type) && token.start == pos.ch &&
  11447. (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos)))
  11448. }
  11449. });
  11450. /***/ }),
  11451. /***/ "./node_modules/codemirror/addon/edit/matchbrackets.js":
  11452. /*!*************************************************************!*\
  11453. !*** ./node_modules/codemirror/addon/edit/matchbrackets.js ***!
  11454. \*************************************************************/
  11455. /*! no static exports found */
  11456. /***/ (function(module, exports, __webpack_require__) {
  11457. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11458. // Distributed under an MIT license: https://codemirror.net/LICENSE
  11459. (function(mod) {
  11460. if (true) // CommonJS
  11461. mod(__webpack_require__(/*! ../../lib/codemirror */ "./node_modules/codemirror/lib/codemirror.js"));
  11462. else {}
  11463. })(function(CodeMirror) {
  11464. var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
  11465. (document.documentMode == null || document.documentMode < 8);
  11466. var Pos = CodeMirror.Pos;
  11467. var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<", "<": ">>", ">": "<<"};
  11468. function bracketRegex(config) {
  11469. return config && config.bracketRegex || /[(){}[\]]/
  11470. }
  11471. function findMatchingBracket(cm, where, config) {
  11472. var line = cm.getLineHandle(where.line), pos = where.ch - 1;
  11473. var afterCursor = config && config.afterCursor
  11474. if (afterCursor == null)
  11475. afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)
  11476. var re = bracketRegex(config)
  11477. // A cursor is defined as between two characters, but in in vim command mode
  11478. // (i.e. not insert mode), the cursor is visually represented as a
  11479. // highlighted box on top of the 2nd character. Otherwise, we allow matches
  11480. // from before or after the cursor.
  11481. var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) ||
  11482. re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)];
  11483. if (!match) return null;
  11484. var dir = match.charAt(1) == ">" ? 1 : -1;
  11485. if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;
  11486. var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
  11487. var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
  11488. if (found == null) return null;
  11489. return {from: Pos(where.line, pos), to: found && found.pos,
  11490. match: found && found.ch == match.charAt(0), forward: dir > 0};
  11491. }
  11492. // bracketRegex is used to specify which type of bracket to scan
  11493. // should be a regexp, e.g. /[[\]]/
  11494. //
  11495. // Note: If "where" is on an open bracket, then this bracket is ignored.
  11496. //
  11497. // Returns false when no bracket was found, null when it reached
  11498. // maxScanLines and gave up
  11499. function scanForBracket(cm, where, dir, style, config) {
  11500. var maxScanLen = (config && config.maxScanLineLength) || 10000;
  11501. var maxScanLines = (config && config.maxScanLines) || 1000;
  11502. var stack = [];
  11503. var re = bracketRegex(config)
  11504. var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
  11505. : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
  11506. for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
  11507. var line = cm.getLine(lineNo);
  11508. if (!line) continue;
  11509. var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
  11510. if (line.length > maxScanLen) continue;
  11511. if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
  11512. for (; pos != end; pos += dir) {
  11513. var ch = line.charAt(pos);
  11514. if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
  11515. var match = matching[ch];
  11516. if (match && (match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
  11517. else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
  11518. else stack.pop();
  11519. }
  11520. }
  11521. }
  11522. return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
  11523. }
  11524. function matchBrackets(cm, autoclear, config) {
  11525. // Disable brace matching in long lines, since it'll cause hugely slow updates
  11526. var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
  11527. var marks = [], ranges = cm.listSelections();
  11528. for (var i = 0; i < ranges.length; i++) {
  11529. var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
  11530. if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
  11531. var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
  11532. marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
  11533. if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
  11534. marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
  11535. }
  11536. }
  11537. if (marks.length) {
  11538. // Kludge to work around the IE bug from issue #1193, where text
  11539. // input stops going to the textare whever this fires.
  11540. if (ie_lt8 && cm.state.focused) cm.focus();
  11541. var clear = function() {
  11542. cm.operation(function() {
  11543. for (var i = 0; i < marks.length; i++) marks[i].clear();
  11544. });
  11545. };
  11546. if (autoclear) setTimeout(clear, 800);
  11547. else return clear;
  11548. }
  11549. }
  11550. function doMatchBrackets(cm) {
  11551. cm.operation(function() {
  11552. if (cm.state.matchBrackets.currentlyHighlighted) {
  11553. cm.state.matchBrackets.currentlyHighlighted();
  11554. cm.state.matchBrackets.currentlyHighlighted = null;
  11555. }
  11556. cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
  11557. });
  11558. }
  11559. CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
  11560. if (old && old != CodeMirror.Init) {
  11561. cm.off("cursorActivity", doMatchBrackets);
  11562. if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
  11563. cm.state.matchBrackets.currentlyHighlighted();
  11564. cm.state.matchBrackets.currentlyHighlighted = null;
  11565. }
  11566. }
  11567. if (val) {
  11568. cm.state.matchBrackets = typeof val == "object" ? val : {};
  11569. cm.on("cursorActivity", doMatchBrackets);
  11570. }
  11571. });
  11572. CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
  11573. CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){
  11574. // Backwards-compatibility kludge
  11575. if (oldConfig || typeof config == "boolean") {
  11576. if (!oldConfig) {
  11577. config = config ? {strict: true} : null
  11578. } else {
  11579. oldConfig.strict = config
  11580. config = oldConfig
  11581. }
  11582. }
  11583. return findMatchingBracket(this, pos, config)
  11584. });
  11585. CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
  11586. return scanForBracket(this, pos, dir, style, config);
  11587. });
  11588. });
  11589. /***/ }),
  11590. /***/ "./node_modules/codemirror/addon/selection/active-line.js":
  11591. /*!****************************************************************!*\
  11592. !*** ./node_modules/codemirror/addon/selection/active-line.js ***!
  11593. \****************************************************************/
  11594. /*! no static exports found */
  11595. /***/ (function(module, exports, __webpack_require__) {
  11596. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11597. // Distributed under an MIT license: https://codemirror.net/LICENSE
  11598. (function(mod) {
  11599. if (true) // CommonJS
  11600. mod(__webpack_require__(/*! ../../lib/codemirror */ "./node_modules/codemirror/lib/codemirror.js"));
  11601. else {}
  11602. })(function(CodeMirror) {
  11603. "use strict";
  11604. var WRAP_CLASS = "CodeMirror-activeline";
  11605. var BACK_CLASS = "CodeMirror-activeline-background";
  11606. var GUTT_CLASS = "CodeMirror-activeline-gutter";
  11607. CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
  11608. var prev = old == CodeMirror.Init ? false : old;
  11609. if (val == prev) return
  11610. if (prev) {
  11611. cm.off("beforeSelectionChange", selectionChange);
  11612. clearActiveLines(cm);
  11613. delete cm.state.activeLines;
  11614. }
  11615. if (val) {
  11616. cm.state.activeLines = [];
  11617. updateActiveLines(cm, cm.listSelections());
  11618. cm.on("beforeSelectionChange", selectionChange);
  11619. }
  11620. });
  11621. function clearActiveLines(cm) {
  11622. for (var i = 0; i < cm.state.activeLines.length; i++) {
  11623. cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
  11624. cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
  11625. cm.removeLineClass(cm.state.activeLines[i], "gutter", GUTT_CLASS);
  11626. }
  11627. }
  11628. function sameArray(a, b) {
  11629. if (a.length != b.length) return false;
  11630. for (var i = 0; i < a.length; i++)
  11631. if (a[i] != b[i]) return false;
  11632. return true;
  11633. }
  11634. function updateActiveLines(cm, ranges) {
  11635. var active = [];
  11636. for (var i = 0; i < ranges.length; i++) {
  11637. var range = ranges[i];
  11638. var option = cm.getOption("styleActiveLine");
  11639. if (typeof option == "object" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())
  11640. continue
  11641. var line = cm.getLineHandleVisualStart(range.head.line);
  11642. if (active[active.length - 1] != line) active.push(line);
  11643. }
  11644. if (sameArray(cm.state.activeLines, active)) return;
  11645. cm.operation(function() {
  11646. clearActiveLines(cm);
  11647. for (var i = 0; i < active.length; i++) {
  11648. cm.addLineClass(active[i], "wrap", WRAP_CLASS);
  11649. cm.addLineClass(active[i], "background", BACK_CLASS);
  11650. cm.addLineClass(active[i], "gutter", GUTT_CLASS);
  11651. }
  11652. cm.state.activeLines = active;
  11653. });
  11654. }
  11655. function selectionChange(cm, sel) {
  11656. updateActiveLines(cm, sel.ranges);
  11657. }
  11658. });
  11659. /***/ }),
  11660. /***/ "./node_modules/codemirror/lib/codemirror.js":
  11661. /*!***************************************************!*\
  11662. !*** ./node_modules/codemirror/lib/codemirror.js ***!
  11663. \***************************************************/
  11664. /*! no static exports found */
  11665. /***/ (function(module, exports, __webpack_require__) {
  11666. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11667. // Distributed under an MIT license: https://codemirror.net/LICENSE
  11668. // This is CodeMirror (https://codemirror.net), a code editor
  11669. // implemented in JavaScript on top of the browser's DOM.
  11670. //
  11671. // You can find some technical background for some of the code below
  11672. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  11673. (function (global, factory) {
  11674. true ? module.exports = factory() :
  11675. undefined;
  11676. }(this, (function () { 'use strict';
  11677. // Kludges for bugs and behavior differences that can't be feature
  11678. // detected are enabled based on userAgent etc sniffing.
  11679. var userAgent = navigator.userAgent;
  11680. var platform = navigator.platform;
  11681. var gecko = /gecko\/\d/i.test(userAgent);
  11682. var ie_upto10 = /MSIE \d/.test(userAgent);
  11683. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  11684. var edge = /Edge\/(\d+)/.exec(userAgent);
  11685. var ie = ie_upto10 || ie_11up || edge;
  11686. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  11687. var webkit = !edge && /WebKit\//.test(userAgent);
  11688. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  11689. var chrome = !edge && /Chrome\//.test(userAgent);
  11690. var presto = /Opera\//.test(userAgent);
  11691. var safari = /Apple Computer/.test(navigator.vendor);
  11692. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  11693. var phantom = /PhantomJS/.test(userAgent);
  11694. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  11695. var android = /Android/.test(userAgent);
  11696. // This is woefully incomplete. Suggestions for alternative methods welcome.
  11697. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  11698. var mac = ios || /Mac/.test(platform);
  11699. var chromeOS = /\bCrOS\b/.test(userAgent);
  11700. var windows = /win/i.test(platform);
  11701. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  11702. if (presto_version) { presto_version = Number(presto_version[1]); }
  11703. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  11704. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  11705. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  11706. var captureRightClick = gecko || (ie && ie_version >= 9);
  11707. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  11708. var rmClass = function(node, cls) {
  11709. var current = node.className;
  11710. var match = classTest(cls).exec(current);
  11711. if (match) {
  11712. var after = current.slice(match.index + match[0].length);
  11713. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  11714. }
  11715. };
  11716. function removeChildren(e) {
  11717. for (var count = e.childNodes.length; count > 0; --count)
  11718. { e.removeChild(e.firstChild); }
  11719. return e
  11720. }
  11721. function removeChildrenAndAdd(parent, e) {
  11722. return removeChildren(parent).appendChild(e)
  11723. }
  11724. function elt(tag, content, className, style) {
  11725. var e = document.createElement(tag);
  11726. if (className) { e.className = className; }
  11727. if (style) { e.style.cssText = style; }
  11728. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  11729. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  11730. return e
  11731. }
  11732. // wrapper for elt, which removes the elt from the accessibility tree
  11733. function eltP(tag, content, className, style) {
  11734. var e = elt(tag, content, className, style);
  11735. e.setAttribute("role", "presentation");
  11736. return e
  11737. }
  11738. var range;
  11739. if (document.createRange) { range = function(node, start, end, endNode) {
  11740. var r = document.createRange();
  11741. r.setEnd(endNode || node, end);
  11742. r.setStart(node, start);
  11743. return r
  11744. }; }
  11745. else { range = function(node, start, end) {
  11746. var r = document.body.createTextRange();
  11747. try { r.moveToElementText(node.parentNode); }
  11748. catch(e) { return r }
  11749. r.collapse(true);
  11750. r.moveEnd("character", end);
  11751. r.moveStart("character", start);
  11752. return r
  11753. }; }
  11754. function contains(parent, child) {
  11755. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  11756. { child = child.parentNode; }
  11757. if (parent.contains)
  11758. { return parent.contains(child) }
  11759. do {
  11760. if (child.nodeType == 11) { child = child.host; }
  11761. if (child == parent) { return true }
  11762. } while (child = child.parentNode)
  11763. }
  11764. function activeElt() {
  11765. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  11766. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  11767. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  11768. var activeElement;
  11769. try {
  11770. activeElement = document.activeElement;
  11771. } catch(e) {
  11772. activeElement = document.body || null;
  11773. }
  11774. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  11775. { activeElement = activeElement.shadowRoot.activeElement; }
  11776. return activeElement
  11777. }
  11778. function addClass(node, cls) {
  11779. var current = node.className;
  11780. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  11781. }
  11782. function joinClasses(a, b) {
  11783. var as = a.split(" ");
  11784. for (var i = 0; i < as.length; i++)
  11785. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  11786. return b
  11787. }
  11788. var selectInput = function(node) { node.select(); };
  11789. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  11790. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  11791. else if (ie) // Suppress mysterious IE10 errors
  11792. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  11793. function bind(f) {
  11794. var args = Array.prototype.slice.call(arguments, 1);
  11795. return function(){return f.apply(null, args)}
  11796. }
  11797. function copyObj(obj, target, overwrite) {
  11798. if (!target) { target = {}; }
  11799. for (var prop in obj)
  11800. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  11801. { target[prop] = obj[prop]; } }
  11802. return target
  11803. }
  11804. // Counts the column offset in a string, taking tabs into account.
  11805. // Used mostly to find indentation.
  11806. function countColumn(string, end, tabSize, startIndex, startValue) {
  11807. if (end == null) {
  11808. end = string.search(/[^\s\u00a0]/);
  11809. if (end == -1) { end = string.length; }
  11810. }
  11811. for (var i = startIndex || 0, n = startValue || 0;;) {
  11812. var nextTab = string.indexOf("\t", i);
  11813. if (nextTab < 0 || nextTab >= end)
  11814. { return n + (end - i) }
  11815. n += nextTab - i;
  11816. n += tabSize - (n % tabSize);
  11817. i = nextTab + 1;
  11818. }
  11819. }
  11820. var Delayed = function() {this.id = null;};
  11821. Delayed.prototype.set = function (ms, f) {
  11822. clearTimeout(this.id);
  11823. this.id = setTimeout(f, ms);
  11824. };
  11825. function indexOf(array, elt) {
  11826. for (var i = 0; i < array.length; ++i)
  11827. { if (array[i] == elt) { return i } }
  11828. return -1
  11829. }
  11830. // Number of pixels added to scroller and sizer to hide scrollbar
  11831. var scrollerGap = 30;
  11832. // Returned or thrown by various protocols to signal 'I'm not
  11833. // handling this'.
  11834. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  11835. // Reused option objects for setSelection & friends
  11836. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  11837. // The inverse of countColumn -- find the offset that corresponds to
  11838. // a particular column.
  11839. function findColumn(string, goal, tabSize) {
  11840. for (var pos = 0, col = 0;;) {
  11841. var nextTab = string.indexOf("\t", pos);
  11842. if (nextTab == -1) { nextTab = string.length; }
  11843. var skipped = nextTab - pos;
  11844. if (nextTab == string.length || col + skipped >= goal)
  11845. { return pos + Math.min(skipped, goal - col) }
  11846. col += nextTab - pos;
  11847. col += tabSize - (col % tabSize);
  11848. pos = nextTab + 1;
  11849. if (col >= goal) { return pos }
  11850. }
  11851. }
  11852. var spaceStrs = [""];
  11853. function spaceStr(n) {
  11854. while (spaceStrs.length <= n)
  11855. { spaceStrs.push(lst(spaceStrs) + " "); }
  11856. return spaceStrs[n]
  11857. }
  11858. function lst(arr) { return arr[arr.length-1] }
  11859. function map(array, f) {
  11860. var out = [];
  11861. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  11862. return out
  11863. }
  11864. function insertSorted(array, value, score) {
  11865. var pos = 0, priority = score(value);
  11866. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  11867. array.splice(pos, 0, value);
  11868. }
  11869. function nothing() {}
  11870. function createObj(base, props) {
  11871. var inst;
  11872. if (Object.create) {
  11873. inst = Object.create(base);
  11874. } else {
  11875. nothing.prototype = base;
  11876. inst = new nothing();
  11877. }
  11878. if (props) { copyObj(props, inst); }
  11879. return inst
  11880. }
  11881. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  11882. function isWordCharBasic(ch) {
  11883. return /\w/.test(ch) || ch > "\x80" &&
  11884. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  11885. }
  11886. function isWordChar(ch, helper) {
  11887. if (!helper) { return isWordCharBasic(ch) }
  11888. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  11889. return helper.test(ch)
  11890. }
  11891. function isEmpty(obj) {
  11892. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  11893. return true
  11894. }
  11895. // Extending unicode characters. A series of a non-extending char +
  11896. // any number of extending chars is treated as a single unit as far
  11897. // as editing and measuring is concerned. This is not fully correct,
  11898. // since some scripts/fonts/browsers also treat other configurations
  11899. // of code points as a group.
  11900. var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\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\u09be\u09c1-\u09c4\u09cd\u09d7\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\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\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\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\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\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
  11901. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  11902. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  11903. function skipExtendingChars(str, pos, dir) {
  11904. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  11905. return pos
  11906. }
  11907. // Returns the value from the range [`from`; `to`] that satisfies
  11908. // `pred` and is closest to `from`. Assumes that at least `to`
  11909. // satisfies `pred`. Supports `from` being greater than `to`.
  11910. function findFirst(pred, from, to) {
  11911. // At any point we are certain `to` satisfies `pred`, don't know
  11912. // whether `from` does.
  11913. var dir = from > to ? -1 : 1;
  11914. for (;;) {
  11915. if (from == to) { return from }
  11916. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  11917. if (mid == from) { return pred(mid) ? from : to }
  11918. if (pred(mid)) { to = mid; }
  11919. else { from = mid + dir; }
  11920. }
  11921. }
  11922. // BIDI HELPERS
  11923. function iterateBidiSections(order, from, to, f) {
  11924. if (!order) { return f(from, to, "ltr", 0) }
  11925. var found = false;
  11926. for (var i = 0; i < order.length; ++i) {
  11927. var part = order[i];
  11928. if (part.from < to && part.to > from || from == to && part.to == from) {
  11929. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  11930. found = true;
  11931. }
  11932. }
  11933. if (!found) { f(from, to, "ltr"); }
  11934. }
  11935. var bidiOther = null;
  11936. function getBidiPartAt(order, ch, sticky) {
  11937. var found;
  11938. bidiOther = null;
  11939. for (var i = 0; i < order.length; ++i) {
  11940. var cur = order[i];
  11941. if (cur.from < ch && cur.to > ch) { return i }
  11942. if (cur.to == ch) {
  11943. if (cur.from != cur.to && sticky == "before") { found = i; }
  11944. else { bidiOther = i; }
  11945. }
  11946. if (cur.from == ch) {
  11947. if (cur.from != cur.to && sticky != "before") { found = i; }
  11948. else { bidiOther = i; }
  11949. }
  11950. }
  11951. return found != null ? found : bidiOther
  11952. }
  11953. // Bidirectional ordering algorithm
  11954. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  11955. // that this (partially) implements.
  11956. // One-char codes used for character types:
  11957. // L (L): Left-to-Right
  11958. // R (R): Right-to-Left
  11959. // r (AL): Right-to-Left Arabic
  11960. // 1 (EN): European Number
  11961. // + (ES): European Number Separator
  11962. // % (ET): European Number Terminator
  11963. // n (AN): Arabic Number
  11964. // , (CS): Common Number Separator
  11965. // m (NSM): Non-Spacing Mark
  11966. // b (BN): Boundary Neutral
  11967. // s (B): Paragraph Separator
  11968. // t (S): Segment Separator
  11969. // w (WS): Whitespace
  11970. // N (ON): Other Neutrals
  11971. // Returns null if characters are ordered as they appear
  11972. // (left-to-right), or an array of sections ({from, to, level}
  11973. // objects) in the order in which they occur visually.
  11974. var bidiOrdering = (function() {
  11975. // Character types for codepoints 0 to 0xff
  11976. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  11977. // Character types for codepoints 0x600 to 0x6f9
  11978. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  11979. function charType(code) {
  11980. if (code <= 0xf7) { return lowTypes.charAt(code) }
  11981. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  11982. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  11983. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  11984. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  11985. else if (code == 0x200c) { return "b" }
  11986. else { return "L" }
  11987. }
  11988. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  11989. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  11990. function BidiSpan(level, from, to) {
  11991. this.level = level;
  11992. this.from = from; this.to = to;
  11993. }
  11994. return function(str, direction) {
  11995. var outerType = direction == "ltr" ? "L" : "R";
  11996. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  11997. var len = str.length, types = [];
  11998. for (var i = 0; i < len; ++i)
  11999. { types.push(charType(str.charCodeAt(i))); }
  12000. // W1. Examine each non-spacing mark (NSM) in the level run, and
  12001. // change the type of the NSM to the type of the previous
  12002. // character. If the NSM is at the start of the level run, it will
  12003. // get the type of sor.
  12004. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  12005. var type = types[i$1];
  12006. if (type == "m") { types[i$1] = prev; }
  12007. else { prev = type; }
  12008. }
  12009. // W2. Search backwards from each instance of a European number
  12010. // until the first strong type (R, L, AL, or sor) is found. If an
  12011. // AL is found, change the type of the European number to Arabic
  12012. // number.
  12013. // W3. Change all ALs to R.
  12014. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  12015. var type$1 = types[i$2];
  12016. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  12017. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  12018. }
  12019. // W4. A single European separator between two European numbers
  12020. // changes to a European number. A single common separator between
  12021. // two numbers of the same type changes to that type.
  12022. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  12023. var type$2 = types[i$3];
  12024. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  12025. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  12026. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  12027. prev$1 = type$2;
  12028. }
  12029. // W5. A sequence of European terminators adjacent to European
  12030. // numbers changes to all European numbers.
  12031. // W6. Otherwise, separators and terminators change to Other
  12032. // Neutral.
  12033. for (var i$4 = 0; i$4 < len; ++i$4) {
  12034. var type$3 = types[i$4];
  12035. if (type$3 == ",") { types[i$4] = "N"; }
  12036. else if (type$3 == "%") {
  12037. var end = (void 0);
  12038. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  12039. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  12040. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  12041. i$4 = end - 1;
  12042. }
  12043. }
  12044. // W7. Search backwards from each instance of a European number
  12045. // until the first strong type (R, L, or sor) is found. If an L is
  12046. // found, then change the type of the European number to L.
  12047. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  12048. var type$4 = types[i$5];
  12049. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  12050. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  12051. }
  12052. // N1. A sequence of neutrals takes the direction of the
  12053. // surrounding strong text if the text on both sides has the same
  12054. // direction. European and Arabic numbers act as if they were R in
  12055. // terms of their influence on neutrals. Start-of-level-run (sor)
  12056. // and end-of-level-run (eor) are used at level run boundaries.
  12057. // N2. Any remaining neutrals take the embedding direction.
  12058. for (var i$6 = 0; i$6 < len; ++i$6) {
  12059. if (isNeutral.test(types[i$6])) {
  12060. var end$1 = (void 0);
  12061. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  12062. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  12063. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  12064. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  12065. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  12066. i$6 = end$1 - 1;
  12067. }
  12068. }
  12069. // Here we depart from the documented algorithm, in order to avoid
  12070. // building up an actual levels array. Since there are only three
  12071. // levels (0, 1, 2) in an implementation that doesn't take
  12072. // explicit embedding into account, we can build up the order on
  12073. // the fly, without following the level-based algorithm.
  12074. var order = [], m;
  12075. for (var i$7 = 0; i$7 < len;) {
  12076. if (countsAsLeft.test(types[i$7])) {
  12077. var start = i$7;
  12078. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  12079. order.push(new BidiSpan(0, start, i$7));
  12080. } else {
  12081. var pos = i$7, at = order.length;
  12082. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  12083. for (var j$2 = pos; j$2 < i$7;) {
  12084. if (countsAsNum.test(types[j$2])) {
  12085. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
  12086. var nstart = j$2;
  12087. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  12088. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  12089. pos = j$2;
  12090. } else { ++j$2; }
  12091. }
  12092. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  12093. }
  12094. }
  12095. if (direction == "ltr") {
  12096. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  12097. order[0].from = m[0].length;
  12098. order.unshift(new BidiSpan(0, 0, m[0].length));
  12099. }
  12100. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  12101. lst(order).to -= m[0].length;
  12102. order.push(new BidiSpan(0, len - m[0].length, len));
  12103. }
  12104. }
  12105. return direction == "rtl" ? order.reverse() : order
  12106. }
  12107. })();
  12108. // Get the bidi ordering for the given line (and cache it). Returns
  12109. // false for lines that are fully left-to-right, and an array of
  12110. // BidiSpan objects otherwise.
  12111. function getOrder(line, direction) {
  12112. var order = line.order;
  12113. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  12114. return order
  12115. }
  12116. // EVENT HANDLING
  12117. // Lightweight event framework. on/off also work on DOM nodes,
  12118. // registering native DOM handlers.
  12119. var noHandlers = [];
  12120. var on = function(emitter, type, f) {
  12121. if (emitter.addEventListener) {
  12122. emitter.addEventListener(type, f, false);
  12123. } else if (emitter.attachEvent) {
  12124. emitter.attachEvent("on" + type, f);
  12125. } else {
  12126. var map$$1 = emitter._handlers || (emitter._handlers = {});
  12127. map$$1[type] = (map$$1[type] || noHandlers).concat(f);
  12128. }
  12129. };
  12130. function getHandlers(emitter, type) {
  12131. return emitter._handlers && emitter._handlers[type] || noHandlers
  12132. }
  12133. function off(emitter, type, f) {
  12134. if (emitter.removeEventListener) {
  12135. emitter.removeEventListener(type, f, false);
  12136. } else if (emitter.detachEvent) {
  12137. emitter.detachEvent("on" + type, f);
  12138. } else {
  12139. var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
  12140. if (arr) {
  12141. var index = indexOf(arr, f);
  12142. if (index > -1)
  12143. { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  12144. }
  12145. }
  12146. }
  12147. function signal(emitter, type /*, values...*/) {
  12148. var handlers = getHandlers(emitter, type);
  12149. if (!handlers.length) { return }
  12150. var args = Array.prototype.slice.call(arguments, 2);
  12151. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  12152. }
  12153. // The DOM events that CodeMirror handles can be overridden by
  12154. // registering a (non-DOM) handler on the editor for the event name,
  12155. // and preventDefault-ing the event in that handler.
  12156. function signalDOMEvent(cm, e, override) {
  12157. if (typeof e == "string")
  12158. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  12159. signal(cm, override || e.type, cm, e);
  12160. return e_defaultPrevented(e) || e.codemirrorIgnore
  12161. }
  12162. function signalCursorActivity(cm) {
  12163. var arr = cm._handlers && cm._handlers.cursorActivity;
  12164. if (!arr) { return }
  12165. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  12166. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  12167. { set.push(arr[i]); } }
  12168. }
  12169. function hasHandler(emitter, type) {
  12170. return getHandlers(emitter, type).length > 0
  12171. }
  12172. // Add on and off methods to a constructor's prototype, to make
  12173. // registering events on such objects more convenient.
  12174. function eventMixin(ctor) {
  12175. ctor.prototype.on = function(type, f) {on(this, type, f);};
  12176. ctor.prototype.off = function(type, f) {off(this, type, f);};
  12177. }
  12178. // Due to the fact that we still support jurassic IE versions, some
  12179. // compatibility wrappers are needed.
  12180. function e_preventDefault(e) {
  12181. if (e.preventDefault) { e.preventDefault(); }
  12182. else { e.returnValue = false; }
  12183. }
  12184. function e_stopPropagation(e) {
  12185. if (e.stopPropagation) { e.stopPropagation(); }
  12186. else { e.cancelBubble = true; }
  12187. }
  12188. function e_defaultPrevented(e) {
  12189. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  12190. }
  12191. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  12192. function e_target(e) {return e.target || e.srcElement}
  12193. function e_button(e) {
  12194. var b = e.which;
  12195. if (b == null) {
  12196. if (e.button & 1) { b = 1; }
  12197. else if (e.button & 2) { b = 3; }
  12198. else if (e.button & 4) { b = 2; }
  12199. }
  12200. if (mac && e.ctrlKey && b == 1) { b = 3; }
  12201. return b
  12202. }
  12203. // Detect drag-and-drop
  12204. var dragAndDrop = function() {
  12205. // There is *some* kind of drag-and-drop support in IE6-8, but I
  12206. // couldn't get it to work yet.
  12207. if (ie && ie_version < 9) { return false }
  12208. var div = elt('div');
  12209. return "draggable" in div || "dragDrop" in div
  12210. }();
  12211. var zwspSupported;
  12212. function zeroWidthElement(measure) {
  12213. if (zwspSupported == null) {
  12214. var test = elt("span", "\u200b");
  12215. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  12216. if (measure.firstChild.offsetHeight != 0)
  12217. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  12218. }
  12219. var node = zwspSupported ? elt("span", "\u200b") :
  12220. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  12221. node.setAttribute("cm-text", "");
  12222. return node
  12223. }
  12224. // Feature-detect IE's crummy client rect reporting for bidi text
  12225. var badBidiRects;
  12226. function hasBadBidiRects(measure) {
  12227. if (badBidiRects != null) { return badBidiRects }
  12228. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  12229. var r0 = range(txt, 0, 1).getBoundingClientRect();
  12230. var r1 = range(txt, 1, 2).getBoundingClientRect();
  12231. removeChildren(measure);
  12232. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  12233. return badBidiRects = (r1.right - r0.right < 3)
  12234. }
  12235. // See if "".split is the broken IE version, if so, provide an
  12236. // alternative way to split lines.
  12237. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  12238. var pos = 0, result = [], l = string.length;
  12239. while (pos <= l) {
  12240. var nl = string.indexOf("\n", pos);
  12241. if (nl == -1) { nl = string.length; }
  12242. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  12243. var rt = line.indexOf("\r");
  12244. if (rt != -1) {
  12245. result.push(line.slice(0, rt));
  12246. pos += rt + 1;
  12247. } else {
  12248. result.push(line);
  12249. pos = nl + 1;
  12250. }
  12251. }
  12252. return result
  12253. } : function (string) { return string.split(/\r\n?|\n/); };
  12254. var hasSelection = window.getSelection ? function (te) {
  12255. try { return te.selectionStart != te.selectionEnd }
  12256. catch(e) { return false }
  12257. } : function (te) {
  12258. var range$$1;
  12259. try {range$$1 = te.ownerDocument.selection.createRange();}
  12260. catch(e) {}
  12261. if (!range$$1 || range$$1.parentElement() != te) { return false }
  12262. return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
  12263. };
  12264. var hasCopyEvent = (function () {
  12265. var e = elt("div");
  12266. if ("oncopy" in e) { return true }
  12267. e.setAttribute("oncopy", "return;");
  12268. return typeof e.oncopy == "function"
  12269. })();
  12270. var badZoomedRects = null;
  12271. function hasBadZoomedRects(measure) {
  12272. if (badZoomedRects != null) { return badZoomedRects }
  12273. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  12274. var normal = node.getBoundingClientRect();
  12275. var fromRange = range(node, 0, 1).getBoundingClientRect();
  12276. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  12277. }
  12278. // Known modes, by name and by MIME
  12279. var modes = {}, mimeModes = {};
  12280. // Extra arguments are stored as the mode's dependencies, which is
  12281. // used by (legacy) mechanisms like loadmode.js to automatically
  12282. // load a mode. (Preferred mechanism is the require/define calls.)
  12283. function defineMode(name, mode) {
  12284. if (arguments.length > 2)
  12285. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  12286. modes[name] = mode;
  12287. }
  12288. function defineMIME(mime, spec) {
  12289. mimeModes[mime] = spec;
  12290. }
  12291. // Given a MIME type, a {name, ...options} config object, or a name
  12292. // string, return a mode config object.
  12293. function resolveMode(spec) {
  12294. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  12295. spec = mimeModes[spec];
  12296. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  12297. var found = mimeModes[spec.name];
  12298. if (typeof found == "string") { found = {name: found}; }
  12299. spec = createObj(found, spec);
  12300. spec.name = found.name;
  12301. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  12302. return resolveMode("application/xml")
  12303. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  12304. return resolveMode("application/json")
  12305. }
  12306. if (typeof spec == "string") { return {name: spec} }
  12307. else { return spec || {name: "null"} }
  12308. }
  12309. // Given a mode spec (anything that resolveMode accepts), find and
  12310. // initialize an actual mode object.
  12311. function getMode(options, spec) {
  12312. spec = resolveMode(spec);
  12313. var mfactory = modes[spec.name];
  12314. if (!mfactory) { return getMode(options, "text/plain") }
  12315. var modeObj = mfactory(options, spec);
  12316. if (modeExtensions.hasOwnProperty(spec.name)) {
  12317. var exts = modeExtensions[spec.name];
  12318. for (var prop in exts) {
  12319. if (!exts.hasOwnProperty(prop)) { continue }
  12320. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  12321. modeObj[prop] = exts[prop];
  12322. }
  12323. }
  12324. modeObj.name = spec.name;
  12325. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  12326. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  12327. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  12328. return modeObj
  12329. }
  12330. // This can be used to attach properties to mode objects from
  12331. // outside the actual mode definition.
  12332. var modeExtensions = {};
  12333. function extendMode(mode, properties) {
  12334. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  12335. copyObj(properties, exts);
  12336. }
  12337. function copyState(mode, state) {
  12338. if (state === true) { return state }
  12339. if (mode.copyState) { return mode.copyState(state) }
  12340. var nstate = {};
  12341. for (var n in state) {
  12342. var val = state[n];
  12343. if (val instanceof Array) { val = val.concat([]); }
  12344. nstate[n] = val;
  12345. }
  12346. return nstate
  12347. }
  12348. // Given a mode and a state (for that mode), find the inner mode and
  12349. // state at the position that the state refers to.
  12350. function innerMode(mode, state) {
  12351. var info;
  12352. while (mode.innerMode) {
  12353. info = mode.innerMode(state);
  12354. if (!info || info.mode == mode) { break }
  12355. state = info.state;
  12356. mode = info.mode;
  12357. }
  12358. return info || {mode: mode, state: state}
  12359. }
  12360. function startState(mode, a1, a2) {
  12361. return mode.startState ? mode.startState(a1, a2) : true
  12362. }
  12363. // STRING STREAM
  12364. // Fed to the mode parsers, provides helper functions to make
  12365. // parsers more succinct.
  12366. var StringStream = function(string, tabSize, lineOracle) {
  12367. this.pos = this.start = 0;
  12368. this.string = string;
  12369. this.tabSize = tabSize || 8;
  12370. this.lastColumnPos = this.lastColumnValue = 0;
  12371. this.lineStart = 0;
  12372. this.lineOracle = lineOracle;
  12373. };
  12374. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  12375. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  12376. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  12377. StringStream.prototype.next = function () {
  12378. if (this.pos < this.string.length)
  12379. { return this.string.charAt(this.pos++) }
  12380. };
  12381. StringStream.prototype.eat = function (match) {
  12382. var ch = this.string.charAt(this.pos);
  12383. var ok;
  12384. if (typeof match == "string") { ok = ch == match; }
  12385. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  12386. if (ok) {++this.pos; return ch}
  12387. };
  12388. StringStream.prototype.eatWhile = function (match) {
  12389. var start = this.pos;
  12390. while (this.eat(match)){}
  12391. return this.pos > start
  12392. };
  12393. StringStream.prototype.eatSpace = function () {
  12394. var this$1 = this;
  12395. var start = this.pos;
  12396. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
  12397. return this.pos > start
  12398. };
  12399. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  12400. StringStream.prototype.skipTo = function (ch) {
  12401. var found = this.string.indexOf(ch, this.pos);
  12402. if (found > -1) {this.pos = found; return true}
  12403. };
  12404. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  12405. StringStream.prototype.column = function () {
  12406. if (this.lastColumnPos < this.start) {
  12407. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  12408. this.lastColumnPos = this.start;
  12409. }
  12410. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  12411. };
  12412. StringStream.prototype.indentation = function () {
  12413. return countColumn(this.string, null, this.tabSize) -
  12414. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  12415. };
  12416. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  12417. if (typeof pattern == "string") {
  12418. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  12419. var substr = this.string.substr(this.pos, pattern.length);
  12420. if (cased(substr) == cased(pattern)) {
  12421. if (consume !== false) { this.pos += pattern.length; }
  12422. return true
  12423. }
  12424. } else {
  12425. var match = this.string.slice(this.pos).match(pattern);
  12426. if (match && match.index > 0) { return null }
  12427. if (match && consume !== false) { this.pos += match[0].length; }
  12428. return match
  12429. }
  12430. };
  12431. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  12432. StringStream.prototype.hideFirstChars = function (n, inner) {
  12433. this.lineStart += n;
  12434. try { return inner() }
  12435. finally { this.lineStart -= n; }
  12436. };
  12437. StringStream.prototype.lookAhead = function (n) {
  12438. var oracle = this.lineOracle;
  12439. return oracle && oracle.lookAhead(n)
  12440. };
  12441. StringStream.prototype.baseToken = function () {
  12442. var oracle = this.lineOracle;
  12443. return oracle && oracle.baseToken(this.pos)
  12444. };
  12445. // Find the line object corresponding to the given line number.
  12446. function getLine(doc, n) {
  12447. n -= doc.first;
  12448. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  12449. var chunk = doc;
  12450. while (!chunk.lines) {
  12451. for (var i = 0;; ++i) {
  12452. var child = chunk.children[i], sz = child.chunkSize();
  12453. if (n < sz) { chunk = child; break }
  12454. n -= sz;
  12455. }
  12456. }
  12457. return chunk.lines[n]
  12458. }
  12459. // Get the part of a document between two positions, as an array of
  12460. // strings.
  12461. function getBetween(doc, start, end) {
  12462. var out = [], n = start.line;
  12463. doc.iter(start.line, end.line + 1, function (line) {
  12464. var text = line.text;
  12465. if (n == end.line) { text = text.slice(0, end.ch); }
  12466. if (n == start.line) { text = text.slice(start.ch); }
  12467. out.push(text);
  12468. ++n;
  12469. });
  12470. return out
  12471. }
  12472. // Get the lines between from and to, as array of strings.
  12473. function getLines(doc, from, to) {
  12474. var out = [];
  12475. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  12476. return out
  12477. }
  12478. // Update the height of a line, propagating the height change
  12479. // upwards to parent nodes.
  12480. function updateLineHeight(line, height) {
  12481. var diff = height - line.height;
  12482. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  12483. }
  12484. // Given a line object, find its line number by walking up through
  12485. // its parent links.
  12486. function lineNo(line) {
  12487. if (line.parent == null) { return null }
  12488. var cur = line.parent, no = indexOf(cur.lines, line);
  12489. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  12490. for (var i = 0;; ++i) {
  12491. if (chunk.children[i] == cur) { break }
  12492. no += chunk.children[i].chunkSize();
  12493. }
  12494. }
  12495. return no + cur.first
  12496. }
  12497. // Find the line at the given vertical position, using the height
  12498. // information in the document tree.
  12499. function lineAtHeight(chunk, h) {
  12500. var n = chunk.first;
  12501. outer: do {
  12502. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  12503. var child = chunk.children[i$1], ch = child.height;
  12504. if (h < ch) { chunk = child; continue outer }
  12505. h -= ch;
  12506. n += child.chunkSize();
  12507. }
  12508. return n
  12509. } while (!chunk.lines)
  12510. var i = 0;
  12511. for (; i < chunk.lines.length; ++i) {
  12512. var line = chunk.lines[i], lh = line.height;
  12513. if (h < lh) { break }
  12514. h -= lh;
  12515. }
  12516. return n + i
  12517. }
  12518. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  12519. function lineNumberFor(options, i) {
  12520. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  12521. }
  12522. // A Pos instance represents a position within the text.
  12523. function Pos(line, ch, sticky) {
  12524. if ( sticky === void 0 ) sticky = null;
  12525. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  12526. this.line = line;
  12527. this.ch = ch;
  12528. this.sticky = sticky;
  12529. }
  12530. // Compare two positions, return 0 if they are the same, a negative
  12531. // number when a is less, and a positive number otherwise.
  12532. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  12533. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  12534. function copyPos(x) {return Pos(x.line, x.ch)}
  12535. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  12536. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  12537. // Most of the external API clips given positions to make sure they
  12538. // actually exist within the document.
  12539. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  12540. function clipPos(doc, pos) {
  12541. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  12542. var last = doc.first + doc.size - 1;
  12543. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  12544. return clipToLen(pos, getLine(doc, pos.line).text.length)
  12545. }
  12546. function clipToLen(pos, linelen) {
  12547. var ch = pos.ch;
  12548. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  12549. else if (ch < 0) { return Pos(pos.line, 0) }
  12550. else { return pos }
  12551. }
  12552. function clipPosArray(doc, array) {
  12553. var out = [];
  12554. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  12555. return out
  12556. }
  12557. var SavedContext = function(state, lookAhead) {
  12558. this.state = state;
  12559. this.lookAhead = lookAhead;
  12560. };
  12561. var Context = function(doc, state, line, lookAhead) {
  12562. this.state = state;
  12563. this.doc = doc;
  12564. this.line = line;
  12565. this.maxLookAhead = lookAhead || 0;
  12566. this.baseTokens = null;
  12567. this.baseTokenPos = 1;
  12568. };
  12569. Context.prototype.lookAhead = function (n) {
  12570. var line = this.doc.getLine(this.line + n);
  12571. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  12572. return line
  12573. };
  12574. Context.prototype.baseToken = function (n) {
  12575. var this$1 = this;
  12576. if (!this.baseTokens) { return null }
  12577. while (this.baseTokens[this.baseTokenPos] <= n)
  12578. { this$1.baseTokenPos += 2; }
  12579. var type = this.baseTokens[this.baseTokenPos + 1];
  12580. return {type: type && type.replace(/( |^)overlay .*/, ""),
  12581. size: this.baseTokens[this.baseTokenPos] - n}
  12582. };
  12583. Context.prototype.nextLine = function () {
  12584. this.line++;
  12585. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  12586. };
  12587. Context.fromSaved = function (doc, saved, line) {
  12588. if (saved instanceof SavedContext)
  12589. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  12590. else
  12591. { return new Context(doc, copyState(doc.mode, saved), line) }
  12592. };
  12593. Context.prototype.save = function (copy) {
  12594. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  12595. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  12596. };
  12597. // Compute a style array (an array starting with a mode generation
  12598. // -- for invalidation -- followed by pairs of end positions and
  12599. // style strings), which is used to highlight the tokens on the
  12600. // line.
  12601. function highlightLine(cm, line, context, forceToEnd) {
  12602. // A styles array always starts with a number identifying the
  12603. // mode/overlays that it is based on (for easy invalidation).
  12604. var st = [cm.state.modeGen], lineClasses = {};
  12605. // Compute the base array of styles
  12606. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  12607. lineClasses, forceToEnd);
  12608. var state = context.state;
  12609. // Run overlays, adjust style array.
  12610. var loop = function ( o ) {
  12611. context.baseTokens = st;
  12612. var overlay = cm.state.overlays[o], i = 1, at = 0;
  12613. context.state = true;
  12614. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  12615. var start = i;
  12616. // Ensure there's a token end at the current position, and that i points at it
  12617. while (at < end) {
  12618. var i_end = st[i];
  12619. if (i_end > end)
  12620. { st.splice(i, 1, end, st[i+1], i_end); }
  12621. i += 2;
  12622. at = Math.min(end, i_end);
  12623. }
  12624. if (!style) { return }
  12625. if (overlay.opaque) {
  12626. st.splice(start, i - start, end, "overlay " + style);
  12627. i = start + 2;
  12628. } else {
  12629. for (; start < i; start += 2) {
  12630. var cur = st[start+1];
  12631. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  12632. }
  12633. }
  12634. }, lineClasses);
  12635. context.state = state;
  12636. context.baseTokens = null;
  12637. context.baseTokenPos = 1;
  12638. };
  12639. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  12640. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  12641. }
  12642. function getLineStyles(cm, line, updateFrontier) {
  12643. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  12644. var context = getContextBefore(cm, lineNo(line));
  12645. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  12646. var result = highlightLine(cm, line, context);
  12647. if (resetState) { context.state = resetState; }
  12648. line.stateAfter = context.save(!resetState);
  12649. line.styles = result.styles;
  12650. if (result.classes) { line.styleClasses = result.classes; }
  12651. else if (line.styleClasses) { line.styleClasses = null; }
  12652. if (updateFrontier === cm.doc.highlightFrontier)
  12653. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  12654. }
  12655. return line.styles
  12656. }
  12657. function getContextBefore(cm, n, precise) {
  12658. var doc = cm.doc, display = cm.display;
  12659. if (!doc.mode.startState) { return new Context(doc, true, n) }
  12660. var start = findStartLine(cm, n, precise);
  12661. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  12662. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  12663. doc.iter(start, n, function (line) {
  12664. processLine(cm, line.text, context);
  12665. var pos = context.line;
  12666. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  12667. context.nextLine();
  12668. });
  12669. if (precise) { doc.modeFrontier = context.line; }
  12670. return context
  12671. }
  12672. // Lightweight form of highlight -- proceed over this line and
  12673. // update state, but don't save a style array. Used for lines that
  12674. // aren't currently visible.
  12675. function processLine(cm, text, context, startAt) {
  12676. var mode = cm.doc.mode;
  12677. var stream = new StringStream(text, cm.options.tabSize, context);
  12678. stream.start = stream.pos = startAt || 0;
  12679. if (text == "") { callBlankLine(mode, context.state); }
  12680. while (!stream.eol()) {
  12681. readToken(mode, stream, context.state);
  12682. stream.start = stream.pos;
  12683. }
  12684. }
  12685. function callBlankLine(mode, state) {
  12686. if (mode.blankLine) { return mode.blankLine(state) }
  12687. if (!mode.innerMode) { return }
  12688. var inner = innerMode(mode, state);
  12689. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  12690. }
  12691. function readToken(mode, stream, state, inner) {
  12692. for (var i = 0; i < 10; i++) {
  12693. if (inner) { inner[0] = innerMode(mode, state).mode; }
  12694. var style = mode.token(stream, state);
  12695. if (stream.pos > stream.start) { return style }
  12696. }
  12697. throw new Error("Mode " + mode.name + " failed to advance stream.")
  12698. }
  12699. var Token = function(stream, type, state) {
  12700. this.start = stream.start; this.end = stream.pos;
  12701. this.string = stream.current();
  12702. this.type = type || null;
  12703. this.state = state;
  12704. };
  12705. // Utility for getTokenAt and getLineTokens
  12706. function takeToken(cm, pos, precise, asArray) {
  12707. var doc = cm.doc, mode = doc.mode, style;
  12708. pos = clipPos(doc, pos);
  12709. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  12710. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  12711. if (asArray) { tokens = []; }
  12712. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  12713. stream.start = stream.pos;
  12714. style = readToken(mode, stream, context.state);
  12715. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  12716. }
  12717. return asArray ? tokens : new Token(stream, style, context.state)
  12718. }
  12719. function extractLineClasses(type, output) {
  12720. if (type) { for (;;) {
  12721. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  12722. if (!lineClass) { break }
  12723. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  12724. var prop = lineClass[1] ? "bgClass" : "textClass";
  12725. if (output[prop] == null)
  12726. { output[prop] = lineClass[2]; }
  12727. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  12728. { output[prop] += " " + lineClass[2]; }
  12729. } }
  12730. return type
  12731. }
  12732. // Run the given mode's parser over a line, calling f for each token.
  12733. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  12734. var flattenSpans = mode.flattenSpans;
  12735. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  12736. var curStart = 0, curStyle = null;
  12737. var stream = new StringStream(text, cm.options.tabSize, context), style;
  12738. var inner = cm.options.addModeClass && [null];
  12739. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  12740. while (!stream.eol()) {
  12741. if (stream.pos > cm.options.maxHighlightLength) {
  12742. flattenSpans = false;
  12743. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  12744. stream.pos = text.length;
  12745. style = null;
  12746. } else {
  12747. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  12748. }
  12749. if (inner) {
  12750. var mName = inner[0].name;
  12751. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  12752. }
  12753. if (!flattenSpans || curStyle != style) {
  12754. while (curStart < stream.start) {
  12755. curStart = Math.min(stream.start, curStart + 5000);
  12756. f(curStart, curStyle);
  12757. }
  12758. curStyle = style;
  12759. }
  12760. stream.start = stream.pos;
  12761. }
  12762. while (curStart < stream.pos) {
  12763. // Webkit seems to refuse to render text nodes longer than 57444
  12764. // characters, and returns inaccurate measurements in nodes
  12765. // starting around 5000 chars.
  12766. var pos = Math.min(stream.pos, curStart + 5000);
  12767. f(pos, curStyle);
  12768. curStart = pos;
  12769. }
  12770. }
  12771. // Finds the line to start with when starting a parse. Tries to
  12772. // find a line with a stateAfter, so that it can start with a
  12773. // valid state. If that fails, it returns the line with the
  12774. // smallest indentation, which tends to need the least context to
  12775. // parse correctly.
  12776. function findStartLine(cm, n, precise) {
  12777. var minindent, minline, doc = cm.doc;
  12778. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  12779. for (var search = n; search > lim; --search) {
  12780. if (search <= doc.first) { return doc.first }
  12781. var line = getLine(doc, search - 1), after = line.stateAfter;
  12782. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  12783. { return search }
  12784. var indented = countColumn(line.text, null, cm.options.tabSize);
  12785. if (minline == null || minindent > indented) {
  12786. minline = search - 1;
  12787. minindent = indented;
  12788. }
  12789. }
  12790. return minline
  12791. }
  12792. function retreatFrontier(doc, n) {
  12793. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  12794. if (doc.highlightFrontier < n - 10) { return }
  12795. var start = doc.first;
  12796. for (var line = n - 1; line > start; line--) {
  12797. var saved = getLine(doc, line).stateAfter;
  12798. // change is on 3
  12799. // state on line 1 looked ahead 2 -- so saw 3
  12800. // test 1 + 2 < 3 should cover this
  12801. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  12802. start = line + 1;
  12803. break
  12804. }
  12805. }
  12806. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  12807. }
  12808. // Optimize some code when these features are not used.
  12809. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  12810. function seeReadOnlySpans() {
  12811. sawReadOnlySpans = true;
  12812. }
  12813. function seeCollapsedSpans() {
  12814. sawCollapsedSpans = true;
  12815. }
  12816. // TEXTMARKER SPANS
  12817. function MarkedSpan(marker, from, to) {
  12818. this.marker = marker;
  12819. this.from = from; this.to = to;
  12820. }
  12821. // Search an array of spans for a span matching the given marker.
  12822. function getMarkedSpanFor(spans, marker) {
  12823. if (spans) { for (var i = 0; i < spans.length; ++i) {
  12824. var span = spans[i];
  12825. if (span.marker == marker) { return span }
  12826. } }
  12827. }
  12828. // Remove a span from an array, returning undefined if no spans are
  12829. // left (we don't store arrays for lines without spans).
  12830. function removeMarkedSpan(spans, span) {
  12831. var r;
  12832. for (var i = 0; i < spans.length; ++i)
  12833. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  12834. return r
  12835. }
  12836. // Add a span to a line.
  12837. function addMarkedSpan(line, span) {
  12838. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  12839. span.marker.attachLine(line);
  12840. }
  12841. // Used for the algorithm that adjusts markers for a change in the
  12842. // document. These functions cut an array of spans at a given
  12843. // character position, returning an array of remaining chunks (or
  12844. // undefined if nothing remains).
  12845. function markedSpansBefore(old, startCh, isInsert) {
  12846. var nw;
  12847. if (old) { for (var i = 0; i < old.length; ++i) {
  12848. var span = old[i], marker = span.marker;
  12849. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  12850. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  12851. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  12852. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  12853. }
  12854. } }
  12855. return nw
  12856. }
  12857. function markedSpansAfter(old, endCh, isInsert) {
  12858. var nw;
  12859. if (old) { for (var i = 0; i < old.length; ++i) {
  12860. var span = old[i], marker = span.marker;
  12861. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  12862. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  12863. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  12864. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  12865. span.to == null ? null : span.to - endCh));
  12866. }
  12867. } }
  12868. return nw
  12869. }
  12870. // Given a change object, compute the new set of marker spans that
  12871. // cover the line in which the change took place. Removes spans
  12872. // entirely within the change, reconnects spans belonging to the
  12873. // same marker that appear on both sides of the change, and cuts off
  12874. // spans partially within the change. Returns an array of span
  12875. // arrays with one element for each line in (after) the change.
  12876. function stretchSpansOverChange(doc, change) {
  12877. if (change.full) { return null }
  12878. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  12879. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  12880. if (!oldFirst && !oldLast) { return null }
  12881. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  12882. // Get the spans that 'stick out' on both sides
  12883. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  12884. var last = markedSpansAfter(oldLast, endCh, isInsert);
  12885. // Next, merge those two ends
  12886. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  12887. if (first) {
  12888. // Fix up .to properties of first
  12889. for (var i = 0; i < first.length; ++i) {
  12890. var span = first[i];
  12891. if (span.to == null) {
  12892. var found = getMarkedSpanFor(last, span.marker);
  12893. if (!found) { span.to = startCh; }
  12894. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  12895. }
  12896. }
  12897. }
  12898. if (last) {
  12899. // Fix up .from in last (or move them into first in case of sameLine)
  12900. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  12901. var span$1 = last[i$1];
  12902. if (span$1.to != null) { span$1.to += offset; }
  12903. if (span$1.from == null) {
  12904. var found$1 = getMarkedSpanFor(first, span$1.marker);
  12905. if (!found$1) {
  12906. span$1.from = offset;
  12907. if (sameLine) { (first || (first = [])).push(span$1); }
  12908. }
  12909. } else {
  12910. span$1.from += offset;
  12911. if (sameLine) { (first || (first = [])).push(span$1); }
  12912. }
  12913. }
  12914. }
  12915. // Make sure we didn't create any zero-length spans
  12916. if (first) { first = clearEmptySpans(first); }
  12917. if (last && last != first) { last = clearEmptySpans(last); }
  12918. var newMarkers = [first];
  12919. if (!sameLine) {
  12920. // Fill gap with whole-line-spans
  12921. var gap = change.text.length - 2, gapMarkers;
  12922. if (gap > 0 && first)
  12923. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  12924. { if (first[i$2].to == null)
  12925. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  12926. for (var i$3 = 0; i$3 < gap; ++i$3)
  12927. { newMarkers.push(gapMarkers); }
  12928. newMarkers.push(last);
  12929. }
  12930. return newMarkers
  12931. }
  12932. // Remove spans that are empty and don't have a clearWhenEmpty
  12933. // option of false.
  12934. function clearEmptySpans(spans) {
  12935. for (var i = 0; i < spans.length; ++i) {
  12936. var span = spans[i];
  12937. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  12938. { spans.splice(i--, 1); }
  12939. }
  12940. if (!spans.length) { return null }
  12941. return spans
  12942. }
  12943. // Used to 'clip' out readOnly ranges when making a change.
  12944. function removeReadOnlyRanges(doc, from, to) {
  12945. var markers = null;
  12946. doc.iter(from.line, to.line + 1, function (line) {
  12947. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  12948. var mark = line.markedSpans[i].marker;
  12949. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  12950. { (markers || (markers = [])).push(mark); }
  12951. } }
  12952. });
  12953. if (!markers) { return null }
  12954. var parts = [{from: from, to: to}];
  12955. for (var i = 0; i < markers.length; ++i) {
  12956. var mk = markers[i], m = mk.find(0);
  12957. for (var j = 0; j < parts.length; ++j) {
  12958. var p = parts[j];
  12959. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  12960. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  12961. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  12962. { newParts.push({from: p.from, to: m.from}); }
  12963. if (dto > 0 || !mk.inclusiveRight && !dto)
  12964. { newParts.push({from: m.to, to: p.to}); }
  12965. parts.splice.apply(parts, newParts);
  12966. j += newParts.length - 3;
  12967. }
  12968. }
  12969. return parts
  12970. }
  12971. // Connect or disconnect spans from a line.
  12972. function detachMarkedSpans(line) {
  12973. var spans = line.markedSpans;
  12974. if (!spans) { return }
  12975. for (var i = 0; i < spans.length; ++i)
  12976. { spans[i].marker.detachLine(line); }
  12977. line.markedSpans = null;
  12978. }
  12979. function attachMarkedSpans(line, spans) {
  12980. if (!spans) { return }
  12981. for (var i = 0; i < spans.length; ++i)
  12982. { spans[i].marker.attachLine(line); }
  12983. line.markedSpans = spans;
  12984. }
  12985. // Helpers used when computing which overlapping collapsed span
  12986. // counts as the larger one.
  12987. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  12988. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  12989. // Returns a number indicating which of two overlapping collapsed
  12990. // spans is larger (and thus includes the other). Falls back to
  12991. // comparing ids when the spans cover exactly the same range.
  12992. function compareCollapsedMarkers(a, b) {
  12993. var lenDiff = a.lines.length - b.lines.length;
  12994. if (lenDiff != 0) { return lenDiff }
  12995. var aPos = a.find(), bPos = b.find();
  12996. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  12997. if (fromCmp) { return -fromCmp }
  12998. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  12999. if (toCmp) { return toCmp }
  13000. return b.id - a.id
  13001. }
  13002. // Find out whether a line ends or starts in a collapsed span. If
  13003. // so, return the marker for that span.
  13004. function collapsedSpanAtSide(line, start) {
  13005. var sps = sawCollapsedSpans && line.markedSpans, found;
  13006. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  13007. sp = sps[i];
  13008. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  13009. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  13010. { found = sp.marker; }
  13011. } }
  13012. return found
  13013. }
  13014. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  13015. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  13016. function collapsedSpanAround(line, ch) {
  13017. var sps = sawCollapsedSpans && line.markedSpans, found;
  13018. if (sps) { for (var i = 0; i < sps.length; ++i) {
  13019. var sp = sps[i];
  13020. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  13021. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  13022. } }
  13023. return found
  13024. }
  13025. // Test whether there exists a collapsed span that partially
  13026. // overlaps (covers the start or end, but not both) of a new span.
  13027. // Such overlap is not allowed.
  13028. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  13029. var line = getLine(doc, lineNo$$1);
  13030. var sps = sawCollapsedSpans && line.markedSpans;
  13031. if (sps) { for (var i = 0; i < sps.length; ++i) {
  13032. var sp = sps[i];
  13033. if (!sp.marker.collapsed) { continue }
  13034. var found = sp.marker.find(0);
  13035. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  13036. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  13037. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  13038. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  13039. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  13040. { return true }
  13041. } }
  13042. }
  13043. // A visual line is a line as drawn on the screen. Folding, for
  13044. // example, can cause multiple logical lines to appear on the same
  13045. // visual line. This finds the start of the visual line that the
  13046. // given line is part of (usually that is the line itself).
  13047. function visualLine(line) {
  13048. var merged;
  13049. while (merged = collapsedSpanAtStart(line))
  13050. { line = merged.find(-1, true).line; }
  13051. return line
  13052. }
  13053. function visualLineEnd(line) {
  13054. var merged;
  13055. while (merged = collapsedSpanAtEnd(line))
  13056. { line = merged.find(1, true).line; }
  13057. return line
  13058. }
  13059. // Returns an array of logical lines that continue the visual line
  13060. // started by the argument, or undefined if there are no such lines.
  13061. function visualLineContinued(line) {
  13062. var merged, lines;
  13063. while (merged = collapsedSpanAtEnd(line)) {
  13064. line = merged.find(1, true).line
  13065. ;(lines || (lines = [])).push(line);
  13066. }
  13067. return lines
  13068. }
  13069. // Get the line number of the start of the visual line that the
  13070. // given line number is part of.
  13071. function visualLineNo(doc, lineN) {
  13072. var line = getLine(doc, lineN), vis = visualLine(line);
  13073. if (line == vis) { return lineN }
  13074. return lineNo(vis)
  13075. }
  13076. // Get the line number of the start of the next visual line after
  13077. // the given line.
  13078. function visualLineEndNo(doc, lineN) {
  13079. if (lineN > doc.lastLine()) { return lineN }
  13080. var line = getLine(doc, lineN), merged;
  13081. if (!lineIsHidden(doc, line)) { return lineN }
  13082. while (merged = collapsedSpanAtEnd(line))
  13083. { line = merged.find(1, true).line; }
  13084. return lineNo(line) + 1
  13085. }
  13086. // Compute whether a line is hidden. Lines count as hidden when they
  13087. // are part of a visual line that starts with another line, or when
  13088. // they are entirely covered by collapsed, non-widget span.
  13089. function lineIsHidden(doc, line) {
  13090. var sps = sawCollapsedSpans && line.markedSpans;
  13091. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  13092. sp = sps[i];
  13093. if (!sp.marker.collapsed) { continue }
  13094. if (sp.from == null) { return true }
  13095. if (sp.marker.widgetNode) { continue }
  13096. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  13097. { return true }
  13098. } }
  13099. }
  13100. function lineIsHiddenInner(doc, line, span) {
  13101. if (span.to == null) {
  13102. var end = span.marker.find(1, true);
  13103. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  13104. }
  13105. if (span.marker.inclusiveRight && span.to == line.text.length)
  13106. { return true }
  13107. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  13108. sp = line.markedSpans[i];
  13109. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  13110. (sp.to == null || sp.to != span.from) &&
  13111. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  13112. lineIsHiddenInner(doc, line, sp)) { return true }
  13113. }
  13114. }
  13115. // Find the height above the given line.
  13116. function heightAtLine(lineObj) {
  13117. lineObj = visualLine(lineObj);
  13118. var h = 0, chunk = lineObj.parent;
  13119. for (var i = 0; i < chunk.lines.length; ++i) {
  13120. var line = chunk.lines[i];
  13121. if (line == lineObj) { break }
  13122. else { h += line.height; }
  13123. }
  13124. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  13125. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  13126. var cur = p.children[i$1];
  13127. if (cur == chunk) { break }
  13128. else { h += cur.height; }
  13129. }
  13130. }
  13131. return h
  13132. }
  13133. // Compute the character length of a line, taking into account
  13134. // collapsed ranges (see markText) that might hide parts, and join
  13135. // other lines onto it.
  13136. function lineLength(line) {
  13137. if (line.height == 0) { return 0 }
  13138. var len = line.text.length, merged, cur = line;
  13139. while (merged = collapsedSpanAtStart(cur)) {
  13140. var found = merged.find(0, true);
  13141. cur = found.from.line;
  13142. len += found.from.ch - found.to.ch;
  13143. }
  13144. cur = line;
  13145. while (merged = collapsedSpanAtEnd(cur)) {
  13146. var found$1 = merged.find(0, true);
  13147. len -= cur.text.length - found$1.from.ch;
  13148. cur = found$1.to.line;
  13149. len += cur.text.length - found$1.to.ch;
  13150. }
  13151. return len
  13152. }
  13153. // Find the longest line in the document.
  13154. function findMaxLine(cm) {
  13155. var d = cm.display, doc = cm.doc;
  13156. d.maxLine = getLine(doc, doc.first);
  13157. d.maxLineLength = lineLength(d.maxLine);
  13158. d.maxLineChanged = true;
  13159. doc.iter(function (line) {
  13160. var len = lineLength(line);
  13161. if (len > d.maxLineLength) {
  13162. d.maxLineLength = len;
  13163. d.maxLine = line;
  13164. }
  13165. });
  13166. }
  13167. // LINE DATA STRUCTURE
  13168. // Line objects. These hold state related to a line, including
  13169. // highlighting info (the styles array).
  13170. var Line = function(text, markedSpans, estimateHeight) {
  13171. this.text = text;
  13172. attachMarkedSpans(this, markedSpans);
  13173. this.height = estimateHeight ? estimateHeight(this) : 1;
  13174. };
  13175. Line.prototype.lineNo = function () { return lineNo(this) };
  13176. eventMixin(Line);
  13177. // Change the content (text, markers) of a line. Automatically
  13178. // invalidates cached information and tries to re-estimate the
  13179. // line's height.
  13180. function updateLine(line, text, markedSpans, estimateHeight) {
  13181. line.text = text;
  13182. if (line.stateAfter) { line.stateAfter = null; }
  13183. if (line.styles) { line.styles = null; }
  13184. if (line.order != null) { line.order = null; }
  13185. detachMarkedSpans(line);
  13186. attachMarkedSpans(line, markedSpans);
  13187. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  13188. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  13189. }
  13190. // Detach a line from the document tree and its markers.
  13191. function cleanUpLine(line) {
  13192. line.parent = null;
  13193. detachMarkedSpans(line);
  13194. }
  13195. // Convert a style as returned by a mode (either null, or a string
  13196. // containing one or more styles) to a CSS style. This is cached,
  13197. // and also looks for line-wide styles.
  13198. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  13199. function interpretTokenStyle(style, options) {
  13200. if (!style || /^\s*$/.test(style)) { return null }
  13201. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  13202. return cache[style] ||
  13203. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  13204. }
  13205. // Render the DOM representation of the text of a line. Also builds
  13206. // up a 'line map', which points at the DOM nodes that represent
  13207. // specific stretches of text, and is used by the measuring code.
  13208. // The returned object contains the DOM node, this map, and
  13209. // information about line-wide styles that were set by the mode.
  13210. function buildLineContent(cm, lineView) {
  13211. // The padding-right forces the element to have a 'border', which
  13212. // is needed on Webkit to be able to get line-level bounding
  13213. // rectangles for it (in measureChar).
  13214. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  13215. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  13216. col: 0, pos: 0, cm: cm,
  13217. trailingSpace: false,
  13218. splitSpaces: cm.getOption("lineWrapping")};
  13219. lineView.measure = {};
  13220. // Iterate over the logical lines that make up this visual line.
  13221. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  13222. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  13223. builder.pos = 0;
  13224. builder.addToken = buildToken;
  13225. // Optionally wire in some hacks into the token-rendering
  13226. // algorithm, to deal with browser quirks.
  13227. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  13228. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  13229. builder.map = [];
  13230. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  13231. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  13232. if (line.styleClasses) {
  13233. if (line.styleClasses.bgClass)
  13234. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  13235. if (line.styleClasses.textClass)
  13236. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  13237. }
  13238. // Ensure at least a single node is present, for measuring.
  13239. if (builder.map.length == 0)
  13240. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  13241. // Store the map and a cache object for the current logical line
  13242. if (i == 0) {
  13243. lineView.measure.map = builder.map;
  13244. lineView.measure.cache = {};
  13245. } else {
  13246. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  13247. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  13248. }
  13249. }
  13250. // See issue #2901
  13251. if (webkit) {
  13252. var last = builder.content.lastChild;
  13253. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  13254. { builder.content.className = "cm-tab-wrap-hack"; }
  13255. }
  13256. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  13257. if (builder.pre.className)
  13258. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  13259. return builder
  13260. }
  13261. function defaultSpecialCharPlaceholder(ch) {
  13262. var token = elt("span", "\u2022", "cm-invalidchar");
  13263. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  13264. token.setAttribute("aria-label", token.title);
  13265. return token
  13266. }
  13267. // Build up the DOM representation for a single token, and add it to
  13268. // the line map. Takes care to render special characters separately.
  13269. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  13270. if (!text) { return }
  13271. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  13272. var special = builder.cm.state.specialChars, mustWrap = false;
  13273. var content;
  13274. if (!special.test(text)) {
  13275. builder.col += text.length;
  13276. content = document.createTextNode(displayText);
  13277. builder.map.push(builder.pos, builder.pos + text.length, content);
  13278. if (ie && ie_version < 9) { mustWrap = true; }
  13279. builder.pos += text.length;
  13280. } else {
  13281. content = document.createDocumentFragment();
  13282. var pos = 0;
  13283. while (true) {
  13284. special.lastIndex = pos;
  13285. var m = special.exec(text);
  13286. var skipped = m ? m.index - pos : text.length - pos;
  13287. if (skipped) {
  13288. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  13289. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  13290. else { content.appendChild(txt); }
  13291. builder.map.push(builder.pos, builder.pos + skipped, txt);
  13292. builder.col += skipped;
  13293. builder.pos += skipped;
  13294. }
  13295. if (!m) { break }
  13296. pos += skipped + 1;
  13297. var txt$1 = (void 0);
  13298. if (m[0] == "\t") {
  13299. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  13300. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  13301. txt$1.setAttribute("role", "presentation");
  13302. txt$1.setAttribute("cm-text", "\t");
  13303. builder.col += tabWidth;
  13304. } else if (m[0] == "\r" || m[0] == "\n") {
  13305. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  13306. txt$1.setAttribute("cm-text", m[0]);
  13307. builder.col += 1;
  13308. } else {
  13309. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  13310. txt$1.setAttribute("cm-text", m[0]);
  13311. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  13312. else { content.appendChild(txt$1); }
  13313. builder.col += 1;
  13314. }
  13315. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  13316. builder.pos++;
  13317. }
  13318. }
  13319. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  13320. if (style || startStyle || endStyle || mustWrap || css) {
  13321. var fullStyle = style || "";
  13322. if (startStyle) { fullStyle += startStyle; }
  13323. if (endStyle) { fullStyle += endStyle; }
  13324. var token = elt("span", [content], fullStyle, css);
  13325. if (attributes) {
  13326. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  13327. { token.setAttribute(attr, attributes[attr]); } }
  13328. }
  13329. return builder.content.appendChild(token)
  13330. }
  13331. builder.content.appendChild(content);
  13332. }
  13333. // Change some spaces to NBSP to prevent the browser from collapsing
  13334. // trailing spaces at the end of a line when rendering text (issue #1362).
  13335. function splitSpaces(text, trailingBefore) {
  13336. if (text.length > 1 && !/ /.test(text)) { return text }
  13337. var spaceBefore = trailingBefore, result = "";
  13338. for (var i = 0; i < text.length; i++) {
  13339. var ch = text.charAt(i);
  13340. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  13341. { ch = "\u00a0"; }
  13342. result += ch;
  13343. spaceBefore = ch == " ";
  13344. }
  13345. return result
  13346. }
  13347. // Work around nonsense dimensions being reported for stretches of
  13348. // right-to-left text.
  13349. function buildTokenBadBidi(inner, order) {
  13350. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  13351. style = style ? style + " cm-force-border" : "cm-force-border";
  13352. var start = builder.pos, end = start + text.length;
  13353. for (;;) {
  13354. // Find the part that overlaps with the start of this text
  13355. var part = (void 0);
  13356. for (var i = 0; i < order.length; i++) {
  13357. part = order[i];
  13358. if (part.to > start && part.from <= start) { break }
  13359. }
  13360. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  13361. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  13362. startStyle = null;
  13363. text = text.slice(part.to - start);
  13364. start = part.to;
  13365. }
  13366. }
  13367. }
  13368. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  13369. var widget = !ignoreWidget && marker.widgetNode;
  13370. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  13371. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  13372. if (!widget)
  13373. { widget = builder.content.appendChild(document.createElement("span")); }
  13374. widget.setAttribute("cm-marker", marker.id);
  13375. }
  13376. if (widget) {
  13377. builder.cm.display.input.setUneditable(widget);
  13378. builder.content.appendChild(widget);
  13379. }
  13380. builder.pos += size;
  13381. builder.trailingSpace = false;
  13382. }
  13383. // Outputs a number of spans to make up a line, taking highlighting
  13384. // and marked text into account.
  13385. function insertLineContent(line, builder, styles) {
  13386. var spans = line.markedSpans, allText = line.text, at = 0;
  13387. if (!spans) {
  13388. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  13389. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  13390. return
  13391. }
  13392. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  13393. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  13394. for (;;) {
  13395. if (nextChange == pos) { // Update current marker set
  13396. spanStyle = spanEndStyle = spanStartStyle = css = "";
  13397. attributes = null;
  13398. collapsed = null; nextChange = Infinity;
  13399. var foundBookmarks = [], endStyles = (void 0);
  13400. for (var j = 0; j < spans.length; ++j) {
  13401. var sp = spans[j], m = sp.marker;
  13402. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  13403. foundBookmarks.push(m);
  13404. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  13405. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  13406. nextChange = sp.to;
  13407. spanEndStyle = "";
  13408. }
  13409. if (m.className) { spanStyle += " " + m.className; }
  13410. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  13411. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  13412. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  13413. // support for the old title property
  13414. // https://github.com/codemirror/CodeMirror/pull/5673
  13415. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  13416. if (m.attributes) {
  13417. for (var attr in m.attributes)
  13418. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  13419. }
  13420. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  13421. { collapsed = sp; }
  13422. } else if (sp.from > pos && nextChange > sp.from) {
  13423. nextChange = sp.from;
  13424. }
  13425. }
  13426. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  13427. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  13428. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  13429. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  13430. if (collapsed && (collapsed.from || 0) == pos) {
  13431. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  13432. collapsed.marker, collapsed.from == null);
  13433. if (collapsed.to == null) { return }
  13434. if (collapsed.to == pos) { collapsed = false; }
  13435. }
  13436. }
  13437. if (pos >= len) { break }
  13438. var upto = Math.min(len, nextChange);
  13439. while (true) {
  13440. if (text) {
  13441. var end = pos + text.length;
  13442. if (!collapsed) {
  13443. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  13444. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  13445. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  13446. }
  13447. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  13448. pos = end;
  13449. spanStartStyle = "";
  13450. }
  13451. text = allText.slice(at, at = styles[i++]);
  13452. style = interpretTokenStyle(styles[i++], builder.cm.options);
  13453. }
  13454. }
  13455. }
  13456. // These objects are used to represent the visible (currently drawn)
  13457. // part of the document. A LineView may correspond to multiple
  13458. // logical lines, if those are connected by collapsed ranges.
  13459. function LineView(doc, line, lineN) {
  13460. // The starting line
  13461. this.line = line;
  13462. // Continuing lines, if any
  13463. this.rest = visualLineContinued(line);
  13464. // Number of logical lines in this visual line
  13465. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  13466. this.node = this.text = null;
  13467. this.hidden = lineIsHidden(doc, line);
  13468. }
  13469. // Create a range of LineView objects for the given lines.
  13470. function buildViewArray(cm, from, to) {
  13471. var array = [], nextPos;
  13472. for (var pos = from; pos < to; pos = nextPos) {
  13473. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  13474. nextPos = pos + view.size;
  13475. array.push(view);
  13476. }
  13477. return array
  13478. }
  13479. var operationGroup = null;
  13480. function pushOperation(op) {
  13481. if (operationGroup) {
  13482. operationGroup.ops.push(op);
  13483. } else {
  13484. op.ownsGroup = operationGroup = {
  13485. ops: [op],
  13486. delayedCallbacks: []
  13487. };
  13488. }
  13489. }
  13490. function fireCallbacksForOps(group) {
  13491. // Calls delayed callbacks and cursorActivity handlers until no
  13492. // new ones appear
  13493. var callbacks = group.delayedCallbacks, i = 0;
  13494. do {
  13495. for (; i < callbacks.length; i++)
  13496. { callbacks[i].call(null); }
  13497. for (var j = 0; j < group.ops.length; j++) {
  13498. var op = group.ops[j];
  13499. if (op.cursorActivityHandlers)
  13500. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  13501. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  13502. }
  13503. } while (i < callbacks.length)
  13504. }
  13505. function finishOperation(op, endCb) {
  13506. var group = op.ownsGroup;
  13507. if (!group) { return }
  13508. try { fireCallbacksForOps(group); }
  13509. finally {
  13510. operationGroup = null;
  13511. endCb(group);
  13512. }
  13513. }
  13514. var orphanDelayedCallbacks = null;
  13515. // Often, we want to signal events at a point where we are in the
  13516. // middle of some work, but don't want the handler to start calling
  13517. // other methods on the editor, which might be in an inconsistent
  13518. // state or simply not expect any other events to happen.
  13519. // signalLater looks whether there are any handlers, and schedules
  13520. // them to be executed when the last operation ends, or, if no
  13521. // operation is active, when a timeout fires.
  13522. function signalLater(emitter, type /*, values...*/) {
  13523. var arr = getHandlers(emitter, type);
  13524. if (!arr.length) { return }
  13525. var args = Array.prototype.slice.call(arguments, 2), list;
  13526. if (operationGroup) {
  13527. list = operationGroup.delayedCallbacks;
  13528. } else if (orphanDelayedCallbacks) {
  13529. list = orphanDelayedCallbacks;
  13530. } else {
  13531. list = orphanDelayedCallbacks = [];
  13532. setTimeout(fireOrphanDelayed, 0);
  13533. }
  13534. var loop = function ( i ) {
  13535. list.push(function () { return arr[i].apply(null, args); });
  13536. };
  13537. for (var i = 0; i < arr.length; ++i)
  13538. loop( i );
  13539. }
  13540. function fireOrphanDelayed() {
  13541. var delayed = orphanDelayedCallbacks;
  13542. orphanDelayedCallbacks = null;
  13543. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  13544. }
  13545. // When an aspect of a line changes, a string is added to
  13546. // lineView.changes. This updates the relevant part of the line's
  13547. // DOM structure.
  13548. function updateLineForChanges(cm, lineView, lineN, dims) {
  13549. for (var j = 0; j < lineView.changes.length; j++) {
  13550. var type = lineView.changes[j];
  13551. if (type == "text") { updateLineText(cm, lineView); }
  13552. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  13553. else if (type == "class") { updateLineClasses(cm, lineView); }
  13554. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  13555. }
  13556. lineView.changes = null;
  13557. }
  13558. // Lines with gutter elements, widgets or a background class need to
  13559. // be wrapped, and have the extra elements added to the wrapper div
  13560. function ensureLineWrapped(lineView) {
  13561. if (lineView.node == lineView.text) {
  13562. lineView.node = elt("div", null, null, "position: relative");
  13563. if (lineView.text.parentNode)
  13564. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  13565. lineView.node.appendChild(lineView.text);
  13566. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  13567. }
  13568. return lineView.node
  13569. }
  13570. function updateLineBackground(cm, lineView) {
  13571. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  13572. if (cls) { cls += " CodeMirror-linebackground"; }
  13573. if (lineView.background) {
  13574. if (cls) { lineView.background.className = cls; }
  13575. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  13576. } else if (cls) {
  13577. var wrap = ensureLineWrapped(lineView);
  13578. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  13579. cm.display.input.setUneditable(lineView.background);
  13580. }
  13581. }
  13582. // Wrapper around buildLineContent which will reuse the structure
  13583. // in display.externalMeasured when possible.
  13584. function getLineContent(cm, lineView) {
  13585. var ext = cm.display.externalMeasured;
  13586. if (ext && ext.line == lineView.line) {
  13587. cm.display.externalMeasured = null;
  13588. lineView.measure = ext.measure;
  13589. return ext.built
  13590. }
  13591. return buildLineContent(cm, lineView)
  13592. }
  13593. // Redraw the line's text. Interacts with the background and text
  13594. // classes because the mode may output tokens that influence these
  13595. // classes.
  13596. function updateLineText(cm, lineView) {
  13597. var cls = lineView.text.className;
  13598. var built = getLineContent(cm, lineView);
  13599. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  13600. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  13601. lineView.text = built.pre;
  13602. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  13603. lineView.bgClass = built.bgClass;
  13604. lineView.textClass = built.textClass;
  13605. updateLineClasses(cm, lineView);
  13606. } else if (cls) {
  13607. lineView.text.className = cls;
  13608. }
  13609. }
  13610. function updateLineClasses(cm, lineView) {
  13611. updateLineBackground(cm, lineView);
  13612. if (lineView.line.wrapClass)
  13613. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  13614. else if (lineView.node != lineView.text)
  13615. { lineView.node.className = ""; }
  13616. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  13617. lineView.text.className = textClass || "";
  13618. }
  13619. function updateLineGutter(cm, lineView, lineN, dims) {
  13620. if (lineView.gutter) {
  13621. lineView.node.removeChild(lineView.gutter);
  13622. lineView.gutter = null;
  13623. }
  13624. if (lineView.gutterBackground) {
  13625. lineView.node.removeChild(lineView.gutterBackground);
  13626. lineView.gutterBackground = null;
  13627. }
  13628. if (lineView.line.gutterClass) {
  13629. var wrap = ensureLineWrapped(lineView);
  13630. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  13631. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  13632. cm.display.input.setUneditable(lineView.gutterBackground);
  13633. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  13634. }
  13635. var markers = lineView.line.gutterMarkers;
  13636. if (cm.options.lineNumbers || markers) {
  13637. var wrap$1 = ensureLineWrapped(lineView);
  13638. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  13639. cm.display.input.setUneditable(gutterWrap);
  13640. wrap$1.insertBefore(gutterWrap, lineView.text);
  13641. if (lineView.line.gutterClass)
  13642. { gutterWrap.className += " " + lineView.line.gutterClass; }
  13643. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  13644. { lineView.lineNumber = gutterWrap.appendChild(
  13645. elt("div", lineNumberFor(cm.options, lineN),
  13646. "CodeMirror-linenumber CodeMirror-gutter-elt",
  13647. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  13648. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  13649. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  13650. if (found)
  13651. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  13652. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  13653. } }
  13654. }
  13655. }
  13656. function updateLineWidgets(cm, lineView, dims) {
  13657. if (lineView.alignable) { lineView.alignable = null; }
  13658. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  13659. next = node.nextSibling;
  13660. if (node.className == "CodeMirror-linewidget")
  13661. { lineView.node.removeChild(node); }
  13662. }
  13663. insertLineWidgets(cm, lineView, dims);
  13664. }
  13665. // Build a line's DOM representation from scratch
  13666. function buildLineElement(cm, lineView, lineN, dims) {
  13667. var built = getLineContent(cm, lineView);
  13668. lineView.text = lineView.node = built.pre;
  13669. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  13670. if (built.textClass) { lineView.textClass = built.textClass; }
  13671. updateLineClasses(cm, lineView);
  13672. updateLineGutter(cm, lineView, lineN, dims);
  13673. insertLineWidgets(cm, lineView, dims);
  13674. return lineView.node
  13675. }
  13676. // A lineView may contain multiple logical lines (when merged by
  13677. // collapsed spans). The widgets for all of them need to be drawn.
  13678. function insertLineWidgets(cm, lineView, dims) {
  13679. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  13680. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  13681. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  13682. }
  13683. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  13684. if (!line.widgets) { return }
  13685. var wrap = ensureLineWrapped(lineView);
  13686. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  13687. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  13688. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  13689. positionLineWidget(widget, node, lineView, dims);
  13690. cm.display.input.setUneditable(node);
  13691. if (allowAbove && widget.above)
  13692. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  13693. else
  13694. { wrap.appendChild(node); }
  13695. signalLater(widget, "redraw");
  13696. }
  13697. }
  13698. function positionLineWidget(widget, node, lineView, dims) {
  13699. if (widget.noHScroll) {
  13700. (lineView.alignable || (lineView.alignable = [])).push(node);
  13701. var width = dims.wrapperWidth;
  13702. node.style.left = dims.fixedPos + "px";
  13703. if (!widget.coverGutter) {
  13704. width -= dims.gutterTotalWidth;
  13705. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  13706. }
  13707. node.style.width = width + "px";
  13708. }
  13709. if (widget.coverGutter) {
  13710. node.style.zIndex = 5;
  13711. node.style.position = "relative";
  13712. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  13713. }
  13714. }
  13715. function widgetHeight(widget) {
  13716. if (widget.height != null) { return widget.height }
  13717. var cm = widget.doc.cm;
  13718. if (!cm) { return 0 }
  13719. if (!contains(document.body, widget.node)) {
  13720. var parentStyle = "position: relative;";
  13721. if (widget.coverGutter)
  13722. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  13723. if (widget.noHScroll)
  13724. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  13725. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  13726. }
  13727. return widget.height = widget.node.parentNode.offsetHeight
  13728. }
  13729. // Return true when the given mouse event happened in a widget
  13730. function eventInWidget(display, e) {
  13731. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  13732. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  13733. (n.parentNode == display.sizer && n != display.mover))
  13734. { return true }
  13735. }
  13736. }
  13737. // POSITION MEASUREMENT
  13738. function paddingTop(display) {return display.lineSpace.offsetTop}
  13739. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  13740. function paddingH(display) {
  13741. if (display.cachedPaddingH) { return display.cachedPaddingH }
  13742. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  13743. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  13744. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  13745. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  13746. return data
  13747. }
  13748. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  13749. function displayWidth(cm) {
  13750. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  13751. }
  13752. function displayHeight(cm) {
  13753. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  13754. }
  13755. // Ensure the lineView.wrapping.heights array is populated. This is
  13756. // an array of bottom offsets for the lines that make up a drawn
  13757. // line. When lineWrapping is on, there might be more than one
  13758. // height.
  13759. function ensureLineHeights(cm, lineView, rect) {
  13760. var wrapping = cm.options.lineWrapping;
  13761. var curWidth = wrapping && displayWidth(cm);
  13762. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  13763. var heights = lineView.measure.heights = [];
  13764. if (wrapping) {
  13765. lineView.measure.width = curWidth;
  13766. var rects = lineView.text.firstChild.getClientRects();
  13767. for (var i = 0; i < rects.length - 1; i++) {
  13768. var cur = rects[i], next = rects[i + 1];
  13769. if (Math.abs(cur.bottom - next.bottom) > 2)
  13770. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  13771. }
  13772. }
  13773. heights.push(rect.bottom - rect.top);
  13774. }
  13775. }
  13776. // Find a line map (mapping character offsets to text nodes) and a
  13777. // measurement cache for the given line number. (A line view might
  13778. // contain multiple lines when collapsed ranges are present.)
  13779. function mapFromLineView(lineView, line, lineN) {
  13780. if (lineView.line == line)
  13781. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  13782. for (var i = 0; i < lineView.rest.length; i++)
  13783. { if (lineView.rest[i] == line)
  13784. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  13785. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  13786. { if (lineNo(lineView.rest[i$1]) > lineN)
  13787. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  13788. }
  13789. // Render a line into the hidden node display.externalMeasured. Used
  13790. // when measurement is needed for a line that's not in the viewport.
  13791. function updateExternalMeasurement(cm, line) {
  13792. line = visualLine(line);
  13793. var lineN = lineNo(line);
  13794. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  13795. view.lineN = lineN;
  13796. var built = view.built = buildLineContent(cm, view);
  13797. view.text = built.pre;
  13798. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  13799. return view
  13800. }
  13801. // Get a {top, bottom, left, right} box (in line-local coordinates)
  13802. // for a given character.
  13803. function measureChar(cm, line, ch, bias) {
  13804. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  13805. }
  13806. // Find a line view that corresponds to the given line number.
  13807. function findViewForLine(cm, lineN) {
  13808. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  13809. { return cm.display.view[findViewIndex(cm, lineN)] }
  13810. var ext = cm.display.externalMeasured;
  13811. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  13812. { return ext }
  13813. }
  13814. // Measurement can be split in two steps, the set-up work that
  13815. // applies to the whole line, and the measurement of the actual
  13816. // character. Functions like coordsChar, that need to do a lot of
  13817. // measurements in a row, can thus ensure that the set-up work is
  13818. // only done once.
  13819. function prepareMeasureForLine(cm, line) {
  13820. var lineN = lineNo(line);
  13821. var view = findViewForLine(cm, lineN);
  13822. if (view && !view.text) {
  13823. view = null;
  13824. } else if (view && view.changes) {
  13825. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  13826. cm.curOp.forceUpdate = true;
  13827. }
  13828. if (!view)
  13829. { view = updateExternalMeasurement(cm, line); }
  13830. var info = mapFromLineView(view, line, lineN);
  13831. return {
  13832. line: line, view: view, rect: null,
  13833. map: info.map, cache: info.cache, before: info.before,
  13834. hasHeights: false
  13835. }
  13836. }
  13837. // Given a prepared measurement object, measures the position of an
  13838. // actual character (or fetches it from the cache).
  13839. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  13840. if (prepared.before) { ch = -1; }
  13841. var key = ch + (bias || ""), found;
  13842. if (prepared.cache.hasOwnProperty(key)) {
  13843. found = prepared.cache[key];
  13844. } else {
  13845. if (!prepared.rect)
  13846. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  13847. if (!prepared.hasHeights) {
  13848. ensureLineHeights(cm, prepared.view, prepared.rect);
  13849. prepared.hasHeights = true;
  13850. }
  13851. found = measureCharInner(cm, prepared, ch, bias);
  13852. if (!found.bogus) { prepared.cache[key] = found; }
  13853. }
  13854. return {left: found.left, right: found.right,
  13855. top: varHeight ? found.rtop : found.top,
  13856. bottom: varHeight ? found.rbottom : found.bottom}
  13857. }
  13858. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  13859. function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  13860. var node, start, end, collapse, mStart, mEnd;
  13861. // First, search the line map for the text node corresponding to,
  13862. // or closest to, the target character.
  13863. for (var i = 0; i < map$$1.length; i += 3) {
  13864. mStart = map$$1[i];
  13865. mEnd = map$$1[i + 1];
  13866. if (ch < mStart) {
  13867. start = 0; end = 1;
  13868. collapse = "left";
  13869. } else if (ch < mEnd) {
  13870. start = ch - mStart;
  13871. end = start + 1;
  13872. } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
  13873. end = mEnd - mStart;
  13874. start = end - 1;
  13875. if (ch >= mEnd) { collapse = "right"; }
  13876. }
  13877. if (start != null) {
  13878. node = map$$1[i + 2];
  13879. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  13880. { collapse = bias; }
  13881. if (bias == "left" && start == 0)
  13882. { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
  13883. node = map$$1[(i -= 3) + 2];
  13884. collapse = "left";
  13885. } }
  13886. if (bias == "right" && start == mEnd - mStart)
  13887. { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
  13888. node = map$$1[(i += 3) + 2];
  13889. collapse = "right";
  13890. } }
  13891. break
  13892. }
  13893. }
  13894. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  13895. }
  13896. function getUsefulRect(rects, bias) {
  13897. var rect = nullRect;
  13898. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  13899. if ((rect = rects[i]).left != rect.right) { break }
  13900. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  13901. if ((rect = rects[i$1]).left != rect.right) { break }
  13902. } }
  13903. return rect
  13904. }
  13905. function measureCharInner(cm, prepared, ch, bias) {
  13906. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  13907. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  13908. var rect;
  13909. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  13910. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  13911. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  13912. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  13913. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  13914. { rect = node.parentNode.getBoundingClientRect(); }
  13915. else
  13916. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  13917. if (rect.left || rect.right || start == 0) { break }
  13918. end = start;
  13919. start = start - 1;
  13920. collapse = "right";
  13921. }
  13922. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  13923. } else { // If it is a widget, simply get the box for the whole widget.
  13924. if (start > 0) { collapse = bias = "right"; }
  13925. var rects;
  13926. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  13927. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  13928. else
  13929. { rect = node.getBoundingClientRect(); }
  13930. }
  13931. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  13932. var rSpan = node.parentNode.getClientRects()[0];
  13933. if (rSpan)
  13934. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  13935. else
  13936. { rect = nullRect; }
  13937. }
  13938. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  13939. var mid = (rtop + rbot) / 2;
  13940. var heights = prepared.view.measure.heights;
  13941. var i = 0;
  13942. for (; i < heights.length - 1; i++)
  13943. { if (mid < heights[i]) { break } }
  13944. var top = i ? heights[i - 1] : 0, bot = heights[i];
  13945. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  13946. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  13947. top: top, bottom: bot};
  13948. if (!rect.left && !rect.right) { result.bogus = true; }
  13949. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  13950. return result
  13951. }
  13952. // Work around problem with bounding client rects on ranges being
  13953. // returned incorrectly when zoomed on IE10 and below.
  13954. function maybeUpdateRectForZooming(measure, rect) {
  13955. if (!window.screen || screen.logicalXDPI == null ||
  13956. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  13957. { return rect }
  13958. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  13959. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  13960. return {left: rect.left * scaleX, right: rect.right * scaleX,
  13961. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  13962. }
  13963. function clearLineMeasurementCacheFor(lineView) {
  13964. if (lineView.measure) {
  13965. lineView.measure.cache = {};
  13966. lineView.measure.heights = null;
  13967. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  13968. { lineView.measure.caches[i] = {}; } }
  13969. }
  13970. }
  13971. function clearLineMeasurementCache(cm) {
  13972. cm.display.externalMeasure = null;
  13973. removeChildren(cm.display.lineMeasure);
  13974. for (var i = 0; i < cm.display.view.length; i++)
  13975. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  13976. }
  13977. function clearCaches(cm) {
  13978. clearLineMeasurementCache(cm);
  13979. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  13980. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  13981. cm.display.lineNumChars = null;
  13982. }
  13983. function pageScrollX() {
  13984. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  13985. // which causes page_Offset and bounding client rects to use
  13986. // different reference viewports and invalidate our calculations.
  13987. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  13988. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  13989. }
  13990. function pageScrollY() {
  13991. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  13992. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  13993. }
  13994. function widgetTopHeight(lineObj) {
  13995. var height = 0;
  13996. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  13997. { height += widgetHeight(lineObj.widgets[i]); } } }
  13998. return height
  13999. }
  14000. // Converts a {top, bottom, left, right} box from line-local
  14001. // coordinates into another coordinate system. Context may be one of
  14002. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  14003. // or "page".
  14004. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  14005. if (!includeWidgets) {
  14006. var height = widgetTopHeight(lineObj);
  14007. rect.top += height; rect.bottom += height;
  14008. }
  14009. if (context == "line") { return rect }
  14010. if (!context) { context = "local"; }
  14011. var yOff = heightAtLine(lineObj);
  14012. if (context == "local") { yOff += paddingTop(cm.display); }
  14013. else { yOff -= cm.display.viewOffset; }
  14014. if (context == "page" || context == "window") {
  14015. var lOff = cm.display.lineSpace.getBoundingClientRect();
  14016. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  14017. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  14018. rect.left += xOff; rect.right += xOff;
  14019. }
  14020. rect.top += yOff; rect.bottom += yOff;
  14021. return rect
  14022. }
  14023. // Coverts a box from "div" coords to another coordinate system.
  14024. // Context may be "window", "page", "div", or "local"./null.
  14025. function fromCoordSystem(cm, coords, context) {
  14026. if (context == "div") { return coords }
  14027. var left = coords.left, top = coords.top;
  14028. // First move into "page" coordinate system
  14029. if (context == "page") {
  14030. left -= pageScrollX();
  14031. top -= pageScrollY();
  14032. } else if (context == "local" || !context) {
  14033. var localBox = cm.display.sizer.getBoundingClientRect();
  14034. left += localBox.left;
  14035. top += localBox.top;
  14036. }
  14037. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  14038. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  14039. }
  14040. function charCoords(cm, pos, context, lineObj, bias) {
  14041. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  14042. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  14043. }
  14044. // Returns a box for a given cursor position, which may have an
  14045. // 'other' property containing the position of the secondary cursor
  14046. // on a bidi boundary.
  14047. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  14048. // and after `char - 1` in writing order of `char - 1`
  14049. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  14050. // and before `char` in writing order of `char`
  14051. // Examples (upper-case letters are RTL, lower-case are LTR):
  14052. // Pos(0, 1, ...)
  14053. // before after
  14054. // ab a|b a|b
  14055. // aB a|B aB|
  14056. // Ab |Ab A|b
  14057. // AB B|A B|A
  14058. // Every position after the last character on a line is considered to stick
  14059. // to the last character on the line.
  14060. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  14061. lineObj = lineObj || getLine(cm.doc, pos.line);
  14062. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  14063. function get(ch, right) {
  14064. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  14065. if (right) { m.left = m.right; } else { m.right = m.left; }
  14066. return intoCoordSystem(cm, lineObj, m, context)
  14067. }
  14068. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  14069. if (ch >= lineObj.text.length) {
  14070. ch = lineObj.text.length;
  14071. sticky = "before";
  14072. } else if (ch <= 0) {
  14073. ch = 0;
  14074. sticky = "after";
  14075. }
  14076. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  14077. function getBidi(ch, partPos, invert) {
  14078. var part = order[partPos], right = part.level == 1;
  14079. return get(invert ? ch - 1 : ch, right != invert)
  14080. }
  14081. var partPos = getBidiPartAt(order, ch, sticky);
  14082. var other = bidiOther;
  14083. var val = getBidi(ch, partPos, sticky == "before");
  14084. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  14085. return val
  14086. }
  14087. // Used to cheaply estimate the coordinates for a position. Used for
  14088. // intermediate scroll updates.
  14089. function estimateCoords(cm, pos) {
  14090. var left = 0;
  14091. pos = clipPos(cm.doc, pos);
  14092. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  14093. var lineObj = getLine(cm.doc, pos.line);
  14094. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  14095. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  14096. }
  14097. // Positions returned by coordsChar contain some extra information.
  14098. // xRel is the relative x position of the input coordinates compared
  14099. // to the found position (so xRel > 0 means the coordinates are to
  14100. // the right of the character position, for example). When outside
  14101. // is true, that means the coordinates lie outside the line's
  14102. // vertical range.
  14103. function PosWithInfo(line, ch, sticky, outside, xRel) {
  14104. var pos = Pos(line, ch, sticky);
  14105. pos.xRel = xRel;
  14106. if (outside) { pos.outside = outside; }
  14107. return pos
  14108. }
  14109. // Compute the character position closest to the given coordinates.
  14110. // Input must be lineSpace-local ("div" coordinate system).
  14111. function coordsChar(cm, x, y) {
  14112. var doc = cm.doc;
  14113. y += cm.display.viewOffset;
  14114. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  14115. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  14116. if (lineN > last)
  14117. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  14118. if (x < 0) { x = 0; }
  14119. var lineObj = getLine(doc, lineN);
  14120. for (;;) {
  14121. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  14122. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  14123. if (!collapsed) { return found }
  14124. var rangeEnd = collapsed.find(1);
  14125. if (rangeEnd.line == lineN) { return rangeEnd }
  14126. lineObj = getLine(doc, lineN = rangeEnd.line);
  14127. }
  14128. }
  14129. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  14130. y -= widgetTopHeight(lineObj);
  14131. var end = lineObj.text.length;
  14132. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  14133. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  14134. return {begin: begin, end: end}
  14135. }
  14136. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  14137. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  14138. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  14139. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  14140. }
  14141. // Returns true if the given side of a box is after the given
  14142. // coordinates, in top-to-bottom, left-to-right order.
  14143. function boxIsAfter(box, x, y, left) {
  14144. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  14145. }
  14146. function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  14147. // Move y into line-local coordinate space
  14148. y -= heightAtLine(lineObj);
  14149. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  14150. // When directly calling `measureCharPrepared`, we have to adjust
  14151. // for the widgets at this line.
  14152. var widgetHeight$$1 = widgetTopHeight(lineObj);
  14153. var begin = 0, end = lineObj.text.length, ltr = true;
  14154. var order = getOrder(lineObj, cm.doc.direction);
  14155. // If the line isn't plain left-to-right text, first figure out
  14156. // which bidi section the coordinates fall into.
  14157. if (order) {
  14158. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  14159. (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
  14160. ltr = part.level != 1;
  14161. // The awkward -1 offsets are needed because findFirst (called
  14162. // on these below) will treat its first bound as inclusive,
  14163. // second as exclusive, but we want to actually address the
  14164. // characters in the part's range
  14165. begin = ltr ? part.from : part.to - 1;
  14166. end = ltr ? part.to : part.from - 1;
  14167. }
  14168. // A binary search to find the first character whose bounding box
  14169. // starts after the coordinates. If we run across any whose box wrap
  14170. // the coordinates, store that.
  14171. var chAround = null, boxAround = null;
  14172. var ch = findFirst(function (ch) {
  14173. var box = measureCharPrepared(cm, preparedMeasure, ch);
  14174. box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
  14175. if (!boxIsAfter(box, x, y, false)) { return false }
  14176. if (box.top <= y && box.left <= x) {
  14177. chAround = ch;
  14178. boxAround = box;
  14179. }
  14180. return true
  14181. }, begin, end);
  14182. var baseX, sticky, outside = false;
  14183. // If a box around the coordinates was found, use that
  14184. if (boxAround) {
  14185. // Distinguish coordinates nearer to the left or right side of the box
  14186. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  14187. ch = chAround + (atStart ? 0 : 1);
  14188. sticky = atStart ? "after" : "before";
  14189. baseX = atLeft ? boxAround.left : boxAround.right;
  14190. } else {
  14191. // (Adjust for extended bound, if necessary.)
  14192. if (!ltr && (ch == end || ch == begin)) { ch++; }
  14193. // To determine which side to associate with, get the box to the
  14194. // left of the character and compare it's vertical position to the
  14195. // coordinates
  14196. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  14197. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
  14198. "after" : "before";
  14199. // Now get accurate coordinates for this place, in order to get a
  14200. // base X position
  14201. var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
  14202. baseX = coords.left;
  14203. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  14204. }
  14205. ch = skipExtendingChars(lineObj.text, ch, 1);
  14206. return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
  14207. }
  14208. function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
  14209. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  14210. // situation, we can take this ordering to correspond to the visual
  14211. // ordering. This finds the first part whose end is after the given
  14212. // coordinates.
  14213. var index = findFirst(function (i) {
  14214. var part = order[i], ltr = part.level != 1;
  14215. return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
  14216. "line", lineObj, preparedMeasure), x, y, true)
  14217. }, 0, order.length - 1);
  14218. var part = order[index];
  14219. // If this isn't the first part, the part's start is also after
  14220. // the coordinates, and the coordinates aren't on the same line as
  14221. // that start, move one part back.
  14222. if (index > 0) {
  14223. var ltr = part.level != 1;
  14224. var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
  14225. "line", lineObj, preparedMeasure);
  14226. if (boxIsAfter(start, x, y, true) && start.top > y)
  14227. { part = order[index - 1]; }
  14228. }
  14229. return part
  14230. }
  14231. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  14232. // In a wrapped line, rtl text on wrapping boundaries can do things
  14233. // that don't correspond to the ordering in our `order` array at
  14234. // all, so a binary search doesn't work, and we want to return a
  14235. // part that only spans one line so that the binary search in
  14236. // coordsCharInner is safe. As such, we first find the extent of the
  14237. // wrapped line, and then do a flat search in which we discard any
  14238. // spans that aren't on the line.
  14239. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  14240. var begin = ref.begin;
  14241. var end = ref.end;
  14242. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  14243. var part = null, closestDist = null;
  14244. for (var i = 0; i < order.length; i++) {
  14245. var p = order[i];
  14246. if (p.from >= end || p.to <= begin) { continue }
  14247. var ltr = p.level != 1;
  14248. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  14249. // Weigh against spans ending before this, so that they are only
  14250. // picked if nothing ends after
  14251. var dist = endX < x ? x - endX + 1e9 : endX - x;
  14252. if (!part || closestDist > dist) {
  14253. part = p;
  14254. closestDist = dist;
  14255. }
  14256. }
  14257. if (!part) { part = order[order.length - 1]; }
  14258. // Clip the part to the wrapped line.
  14259. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  14260. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  14261. return part
  14262. }
  14263. var measureText;
  14264. // Compute the default text height.
  14265. function textHeight(display) {
  14266. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  14267. if (measureText == null) {
  14268. measureText = elt("pre", null, "CodeMirror-line-like");
  14269. // Measure a bunch of lines, for browsers that compute
  14270. // fractional heights.
  14271. for (var i = 0; i < 49; ++i) {
  14272. measureText.appendChild(document.createTextNode("x"));
  14273. measureText.appendChild(elt("br"));
  14274. }
  14275. measureText.appendChild(document.createTextNode("x"));
  14276. }
  14277. removeChildrenAndAdd(display.measure, measureText);
  14278. var height = measureText.offsetHeight / 50;
  14279. if (height > 3) { display.cachedTextHeight = height; }
  14280. removeChildren(display.measure);
  14281. return height || 1
  14282. }
  14283. // Compute the default character width.
  14284. function charWidth(display) {
  14285. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  14286. var anchor = elt("span", "xxxxxxxxxx");
  14287. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  14288. removeChildrenAndAdd(display.measure, pre);
  14289. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  14290. if (width > 2) { display.cachedCharWidth = width; }
  14291. return width || 10
  14292. }
  14293. // Do a bulk-read of the DOM positions and sizes needed to draw the
  14294. // view, so that we don't interleave reading and writing to the DOM.
  14295. function getDimensions(cm) {
  14296. var d = cm.display, left = {}, width = {};
  14297. var gutterLeft = d.gutters.clientLeft;
  14298. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  14299. var id = cm.display.gutterSpecs[i].className;
  14300. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  14301. width[id] = n.clientWidth;
  14302. }
  14303. return {fixedPos: compensateForHScroll(d),
  14304. gutterTotalWidth: d.gutters.offsetWidth,
  14305. gutterLeft: left,
  14306. gutterWidth: width,
  14307. wrapperWidth: d.wrapper.clientWidth}
  14308. }
  14309. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  14310. // but using getBoundingClientRect to get a sub-pixel-accurate
  14311. // result.
  14312. function compensateForHScroll(display) {
  14313. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  14314. }
  14315. // Returns a function that estimates the height of a line, to use as
  14316. // first approximation until the line becomes visible (and is thus
  14317. // properly measurable).
  14318. function estimateHeight(cm) {
  14319. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  14320. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  14321. return function (line) {
  14322. if (lineIsHidden(cm.doc, line)) { return 0 }
  14323. var widgetsHeight = 0;
  14324. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  14325. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  14326. } }
  14327. if (wrapping)
  14328. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  14329. else
  14330. { return widgetsHeight + th }
  14331. }
  14332. }
  14333. function estimateLineHeights(cm) {
  14334. var doc = cm.doc, est = estimateHeight(cm);
  14335. doc.iter(function (line) {
  14336. var estHeight = est(line);
  14337. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  14338. });
  14339. }
  14340. // Given a mouse event, find the corresponding position. If liberal
  14341. // is false, it checks whether a gutter or scrollbar was clicked,
  14342. // and returns null if it was. forRect is used by rectangular
  14343. // selections, and tries to estimate a character position even for
  14344. // coordinates beyond the right of the text.
  14345. function posFromMouse(cm, e, liberal, forRect) {
  14346. var display = cm.display;
  14347. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  14348. var x, y, space = display.lineSpace.getBoundingClientRect();
  14349. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  14350. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  14351. catch (e) { return null }
  14352. var coords = coordsChar(cm, x, y), line;
  14353. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  14354. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  14355. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  14356. }
  14357. return coords
  14358. }
  14359. // Find the view element corresponding to a given line. Return null
  14360. // when the line isn't visible.
  14361. function findViewIndex(cm, n) {
  14362. if (n >= cm.display.viewTo) { return null }
  14363. n -= cm.display.viewFrom;
  14364. if (n < 0) { return null }
  14365. var view = cm.display.view;
  14366. for (var i = 0; i < view.length; i++) {
  14367. n -= view[i].size;
  14368. if (n < 0) { return i }
  14369. }
  14370. }
  14371. // Updates the display.view data structure for a given change to the
  14372. // document. From and to are in pre-change coordinates. Lendiff is
  14373. // the amount of lines added or subtracted by the change. This is
  14374. // used for changes that span multiple lines, or change the way
  14375. // lines are divided into visual lines. regLineChange (below)
  14376. // registers single-line changes.
  14377. function regChange(cm, from, to, lendiff) {
  14378. if (from == null) { from = cm.doc.first; }
  14379. if (to == null) { to = cm.doc.first + cm.doc.size; }
  14380. if (!lendiff) { lendiff = 0; }
  14381. var display = cm.display;
  14382. if (lendiff && to < display.viewTo &&
  14383. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  14384. { display.updateLineNumbers = from; }
  14385. cm.curOp.viewChanged = true;
  14386. if (from >= display.viewTo) { // Change after
  14387. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  14388. { resetView(cm); }
  14389. } else if (to <= display.viewFrom) { // Change before
  14390. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  14391. resetView(cm);
  14392. } else {
  14393. display.viewFrom += lendiff;
  14394. display.viewTo += lendiff;
  14395. }
  14396. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  14397. resetView(cm);
  14398. } else if (from <= display.viewFrom) { // Top overlap
  14399. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  14400. if (cut) {
  14401. display.view = display.view.slice(cut.index);
  14402. display.viewFrom = cut.lineN;
  14403. display.viewTo += lendiff;
  14404. } else {
  14405. resetView(cm);
  14406. }
  14407. } else if (to >= display.viewTo) { // Bottom overlap
  14408. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  14409. if (cut$1) {
  14410. display.view = display.view.slice(0, cut$1.index);
  14411. display.viewTo = cut$1.lineN;
  14412. } else {
  14413. resetView(cm);
  14414. }
  14415. } else { // Gap in the middle
  14416. var cutTop = viewCuttingPoint(cm, from, from, -1);
  14417. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  14418. if (cutTop && cutBot) {
  14419. display.view = display.view.slice(0, cutTop.index)
  14420. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  14421. .concat(display.view.slice(cutBot.index));
  14422. display.viewTo += lendiff;
  14423. } else {
  14424. resetView(cm);
  14425. }
  14426. }
  14427. var ext = display.externalMeasured;
  14428. if (ext) {
  14429. if (to < ext.lineN)
  14430. { ext.lineN += lendiff; }
  14431. else if (from < ext.lineN + ext.size)
  14432. { display.externalMeasured = null; }
  14433. }
  14434. }
  14435. // Register a change to a single line. Type must be one of "text",
  14436. // "gutter", "class", "widget"
  14437. function regLineChange(cm, line, type) {
  14438. cm.curOp.viewChanged = true;
  14439. var display = cm.display, ext = cm.display.externalMeasured;
  14440. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  14441. { display.externalMeasured = null; }
  14442. if (line < display.viewFrom || line >= display.viewTo) { return }
  14443. var lineView = display.view[findViewIndex(cm, line)];
  14444. if (lineView.node == null) { return }
  14445. var arr = lineView.changes || (lineView.changes = []);
  14446. if (indexOf(arr, type) == -1) { arr.push(type); }
  14447. }
  14448. // Clear the view.
  14449. function resetView(cm) {
  14450. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  14451. cm.display.view = [];
  14452. cm.display.viewOffset = 0;
  14453. }
  14454. function viewCuttingPoint(cm, oldN, newN, dir) {
  14455. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  14456. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  14457. { return {index: index, lineN: newN} }
  14458. var n = cm.display.viewFrom;
  14459. for (var i = 0; i < index; i++)
  14460. { n += view[i].size; }
  14461. if (n != oldN) {
  14462. if (dir > 0) {
  14463. if (index == view.length - 1) { return null }
  14464. diff = (n + view[index].size) - oldN;
  14465. index++;
  14466. } else {
  14467. diff = n - oldN;
  14468. }
  14469. oldN += diff; newN += diff;
  14470. }
  14471. while (visualLineNo(cm.doc, newN) != newN) {
  14472. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  14473. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  14474. index += dir;
  14475. }
  14476. return {index: index, lineN: newN}
  14477. }
  14478. // Force the view to cover a given range, adding empty view element
  14479. // or clipping off existing ones as needed.
  14480. function adjustView(cm, from, to) {
  14481. var display = cm.display, view = display.view;
  14482. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  14483. display.view = buildViewArray(cm, from, to);
  14484. display.viewFrom = from;
  14485. } else {
  14486. if (display.viewFrom > from)
  14487. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  14488. else if (display.viewFrom < from)
  14489. { display.view = display.view.slice(findViewIndex(cm, from)); }
  14490. display.viewFrom = from;
  14491. if (display.viewTo < to)
  14492. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  14493. else if (display.viewTo > to)
  14494. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  14495. }
  14496. display.viewTo = to;
  14497. }
  14498. // Count the number of lines in the view whose DOM representation is
  14499. // out of date (or nonexistent).
  14500. function countDirtyView(cm) {
  14501. var view = cm.display.view, dirty = 0;
  14502. for (var i = 0; i < view.length; i++) {
  14503. var lineView = view[i];
  14504. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  14505. }
  14506. return dirty
  14507. }
  14508. function updateSelection(cm) {
  14509. cm.display.input.showSelection(cm.display.input.prepareSelection());
  14510. }
  14511. function prepareSelection(cm, primary) {
  14512. if ( primary === void 0 ) primary = true;
  14513. var doc = cm.doc, result = {};
  14514. var curFragment = result.cursors = document.createDocumentFragment();
  14515. var selFragment = result.selection = document.createDocumentFragment();
  14516. for (var i = 0; i < doc.sel.ranges.length; i++) {
  14517. if (!primary && i == doc.sel.primIndex) { continue }
  14518. var range$$1 = doc.sel.ranges[i];
  14519. if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
  14520. var collapsed = range$$1.empty();
  14521. if (collapsed || cm.options.showCursorWhenSelecting)
  14522. { drawSelectionCursor(cm, range$$1.head, curFragment); }
  14523. if (!collapsed)
  14524. { drawSelectionRange(cm, range$$1, selFragment); }
  14525. }
  14526. return result
  14527. }
  14528. // Draws a cursor for the given range
  14529. function drawSelectionCursor(cm, head, output) {
  14530. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  14531. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  14532. cursor.style.left = pos.left + "px";
  14533. cursor.style.top = pos.top + "px";
  14534. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  14535. if (pos.other) {
  14536. // Secondary cursor, shown when on a 'jump' in bi-directional text
  14537. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  14538. otherCursor.style.display = "";
  14539. otherCursor.style.left = pos.other.left + "px";
  14540. otherCursor.style.top = pos.other.top + "px";
  14541. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  14542. }
  14543. }
  14544. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  14545. // Draws the given range as a highlighted selection
  14546. function drawSelectionRange(cm, range$$1, output) {
  14547. var display = cm.display, doc = cm.doc;
  14548. var fragment = document.createDocumentFragment();
  14549. var padding = paddingH(cm.display), leftSide = padding.left;
  14550. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  14551. var docLTR = doc.direction == "ltr";
  14552. function add(left, top, width, bottom) {
  14553. if (top < 0) { top = 0; }
  14554. top = Math.round(top);
  14555. bottom = Math.round(bottom);
  14556. fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
  14557. }
  14558. function drawForLine(line, fromArg, toArg) {
  14559. var lineObj = getLine(doc, line);
  14560. var lineLen = lineObj.text.length;
  14561. var start, end;
  14562. function coords(ch, bias) {
  14563. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  14564. }
  14565. function wrapX(pos, dir, side) {
  14566. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  14567. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  14568. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  14569. return coords(ch, prop)[prop]
  14570. }
  14571. var order = getOrder(lineObj, doc.direction);
  14572. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  14573. var ltr = dir == "ltr";
  14574. var fromPos = coords(from, ltr ? "left" : "right");
  14575. var toPos = coords(to - 1, ltr ? "right" : "left");
  14576. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  14577. var first = i == 0, last = !order || i == order.length - 1;
  14578. if (toPos.top - fromPos.top <= 3) { // Single line
  14579. var openLeft = (docLTR ? openStart : openEnd) && first;
  14580. var openRight = (docLTR ? openEnd : openStart) && last;
  14581. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  14582. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  14583. add(left, fromPos.top, right - left, fromPos.bottom);
  14584. } else { // Multiple lines
  14585. var topLeft, topRight, botLeft, botRight;
  14586. if (ltr) {
  14587. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  14588. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  14589. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  14590. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  14591. } else {
  14592. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  14593. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  14594. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  14595. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  14596. }
  14597. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  14598. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  14599. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  14600. }
  14601. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  14602. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  14603. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  14604. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  14605. });
  14606. return {start: start, end: end}
  14607. }
  14608. var sFrom = range$$1.from(), sTo = range$$1.to();
  14609. if (sFrom.line == sTo.line) {
  14610. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  14611. } else {
  14612. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  14613. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  14614. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  14615. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  14616. if (singleVLine) {
  14617. if (leftEnd.top < rightStart.top - 2) {
  14618. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  14619. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  14620. } else {
  14621. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  14622. }
  14623. }
  14624. if (leftEnd.bottom < rightStart.top)
  14625. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  14626. }
  14627. output.appendChild(fragment);
  14628. }
  14629. // Cursor-blinking
  14630. function restartBlink(cm) {
  14631. if (!cm.state.focused) { return }
  14632. var display = cm.display;
  14633. clearInterval(display.blinker);
  14634. var on = true;
  14635. display.cursorDiv.style.visibility = "";
  14636. if (cm.options.cursorBlinkRate > 0)
  14637. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  14638. cm.options.cursorBlinkRate); }
  14639. else if (cm.options.cursorBlinkRate < 0)
  14640. { display.cursorDiv.style.visibility = "hidden"; }
  14641. }
  14642. function ensureFocus(cm) {
  14643. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  14644. }
  14645. function delayBlurEvent(cm) {
  14646. cm.state.delayingBlurEvent = true;
  14647. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  14648. cm.state.delayingBlurEvent = false;
  14649. onBlur(cm);
  14650. } }, 100);
  14651. }
  14652. function onFocus(cm, e) {
  14653. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  14654. if (cm.options.readOnly == "nocursor") { return }
  14655. if (!cm.state.focused) {
  14656. signal(cm, "focus", cm, e);
  14657. cm.state.focused = true;
  14658. addClass(cm.display.wrapper, "CodeMirror-focused");
  14659. // This test prevents this from firing when a context
  14660. // menu is closed (since the input reset would kill the
  14661. // select-all detection hack)
  14662. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  14663. cm.display.input.reset();
  14664. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  14665. }
  14666. cm.display.input.receivedFocus();
  14667. }
  14668. restartBlink(cm);
  14669. }
  14670. function onBlur(cm, e) {
  14671. if (cm.state.delayingBlurEvent) { return }
  14672. if (cm.state.focused) {
  14673. signal(cm, "blur", cm, e);
  14674. cm.state.focused = false;
  14675. rmClass(cm.display.wrapper, "CodeMirror-focused");
  14676. }
  14677. clearInterval(cm.display.blinker);
  14678. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  14679. }
  14680. // Read the actual heights of the rendered lines, and update their
  14681. // stored heights to match.
  14682. function updateHeightsInViewport(cm) {
  14683. var display = cm.display;
  14684. var prevBottom = display.lineDiv.offsetTop;
  14685. for (var i = 0; i < display.view.length; i++) {
  14686. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  14687. var height = (void 0), width = 0;
  14688. if (cur.hidden) { continue }
  14689. if (ie && ie_version < 8) {
  14690. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  14691. height = bot - prevBottom;
  14692. prevBottom = bot;
  14693. } else {
  14694. var box = cur.node.getBoundingClientRect();
  14695. height = box.bottom - box.top;
  14696. // Check that lines don't extend past the right of the current
  14697. // editor width
  14698. if (!wrapping && cur.text.firstChild)
  14699. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  14700. }
  14701. var diff = cur.line.height - height;
  14702. if (diff > .005 || diff < -.005) {
  14703. updateLineHeight(cur.line, height);
  14704. updateWidgetHeight(cur.line);
  14705. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  14706. { updateWidgetHeight(cur.rest[j]); } }
  14707. }
  14708. if (width > cm.display.sizerWidth) {
  14709. var chWidth = Math.ceil(width / charWidth(cm.display));
  14710. if (chWidth > cm.display.maxLineLength) {
  14711. cm.display.maxLineLength = chWidth;
  14712. cm.display.maxLine = cur.line;
  14713. cm.display.maxLineChanged = true;
  14714. }
  14715. }
  14716. }
  14717. }
  14718. // Read and store the height of line widgets associated with the
  14719. // given line.
  14720. function updateWidgetHeight(line) {
  14721. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  14722. var w = line.widgets[i], parent = w.node.parentNode;
  14723. if (parent) { w.height = parent.offsetHeight; }
  14724. } }
  14725. }
  14726. // Compute the lines that are visible in a given viewport (defaults
  14727. // the the current scroll position). viewport may contain top,
  14728. // height, and ensure (see op.scrollToPos) properties.
  14729. function visibleLines(display, doc, viewport) {
  14730. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  14731. top = Math.floor(top - paddingTop(display));
  14732. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  14733. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  14734. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  14735. // forces those lines into the viewport (if possible).
  14736. if (viewport && viewport.ensure) {
  14737. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  14738. if (ensureFrom < from) {
  14739. from = ensureFrom;
  14740. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  14741. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  14742. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  14743. to = ensureTo;
  14744. }
  14745. }
  14746. return {from: from, to: Math.max(to, from + 1)}
  14747. }
  14748. // SCROLLING THINGS INTO VIEW
  14749. // If an editor sits on the top or bottom of the window, partially
  14750. // scrolled out of view, this ensures that the cursor is visible.
  14751. function maybeScrollWindow(cm, rect) {
  14752. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  14753. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  14754. if (rect.top + box.top < 0) { doScroll = true; }
  14755. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  14756. if (doScroll != null && !phantom) {
  14757. var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
  14758. cm.display.lineSpace.appendChild(scrollNode);
  14759. scrollNode.scrollIntoView(doScroll);
  14760. cm.display.lineSpace.removeChild(scrollNode);
  14761. }
  14762. }
  14763. // Scroll a given position into view (immediately), verifying that
  14764. // it actually became visible (as line heights are accurately
  14765. // measured, the position of something may 'drift' during drawing).
  14766. function scrollPosIntoView(cm, pos, end, margin) {
  14767. if (margin == null) { margin = 0; }
  14768. var rect;
  14769. if (!cm.options.lineWrapping && pos == end) {
  14770. // Set pos and end to the cursor positions around the character pos sticks to
  14771. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  14772. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  14773. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  14774. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  14775. }
  14776. for (var limit = 0; limit < 5; limit++) {
  14777. var changed = false;
  14778. var coords = cursorCoords(cm, pos);
  14779. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  14780. rect = {left: Math.min(coords.left, endCoords.left),
  14781. top: Math.min(coords.top, endCoords.top) - margin,
  14782. right: Math.max(coords.left, endCoords.left),
  14783. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  14784. var scrollPos = calculateScrollPos(cm, rect);
  14785. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  14786. if (scrollPos.scrollTop != null) {
  14787. updateScrollTop(cm, scrollPos.scrollTop);
  14788. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  14789. }
  14790. if (scrollPos.scrollLeft != null) {
  14791. setScrollLeft(cm, scrollPos.scrollLeft);
  14792. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  14793. }
  14794. if (!changed) { break }
  14795. }
  14796. return rect
  14797. }
  14798. // Scroll a given set of coordinates into view (immediately).
  14799. function scrollIntoView(cm, rect) {
  14800. var scrollPos = calculateScrollPos(cm, rect);
  14801. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  14802. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  14803. }
  14804. // Calculate a new scroll position needed to scroll the given
  14805. // rectangle into view. Returns an object with scrollTop and
  14806. // scrollLeft properties. When these are undefined, the
  14807. // vertical/horizontal position does not need to be adjusted.
  14808. function calculateScrollPos(cm, rect) {
  14809. var display = cm.display, snapMargin = textHeight(cm.display);
  14810. if (rect.top < 0) { rect.top = 0; }
  14811. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  14812. var screen = displayHeight(cm), result = {};
  14813. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  14814. var docBottom = cm.doc.height + paddingVert(display);
  14815. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  14816. if (rect.top < screentop) {
  14817. result.scrollTop = atTop ? 0 : rect.top;
  14818. } else if (rect.bottom > screentop + screen) {
  14819. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  14820. if (newTop != screentop) { result.scrollTop = newTop; }
  14821. }
  14822. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  14823. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  14824. var tooWide = rect.right - rect.left > screenw;
  14825. if (tooWide) { rect.right = rect.left + screenw; }
  14826. if (rect.left < 10)
  14827. { result.scrollLeft = 0; }
  14828. else if (rect.left < screenleft)
  14829. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  14830. else if (rect.right > screenw + screenleft - 3)
  14831. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  14832. return result
  14833. }
  14834. // Store a relative adjustment to the scroll position in the current
  14835. // operation (to be applied when the operation finishes).
  14836. function addToScrollTop(cm, top) {
  14837. if (top == null) { return }
  14838. resolveScrollToPos(cm);
  14839. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  14840. }
  14841. // Make sure that at the end of the operation the current cursor is
  14842. // shown.
  14843. function ensureCursorVisible(cm) {
  14844. resolveScrollToPos(cm);
  14845. var cur = cm.getCursor();
  14846. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  14847. }
  14848. function scrollToCoords(cm, x, y) {
  14849. if (x != null || y != null) { resolveScrollToPos(cm); }
  14850. if (x != null) { cm.curOp.scrollLeft = x; }
  14851. if (y != null) { cm.curOp.scrollTop = y; }
  14852. }
  14853. function scrollToRange(cm, range$$1) {
  14854. resolveScrollToPos(cm);
  14855. cm.curOp.scrollToPos = range$$1;
  14856. }
  14857. // When an operation has its scrollToPos property set, and another
  14858. // scroll action is applied before the end of the operation, this
  14859. // 'simulates' scrolling that position into view in a cheap way, so
  14860. // that the effect of intermediate scroll commands is not ignored.
  14861. function resolveScrollToPos(cm) {
  14862. var range$$1 = cm.curOp.scrollToPos;
  14863. if (range$$1) {
  14864. cm.curOp.scrollToPos = null;
  14865. var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
  14866. scrollToCoordsRange(cm, from, to, range$$1.margin);
  14867. }
  14868. }
  14869. function scrollToCoordsRange(cm, from, to, margin) {
  14870. var sPos = calculateScrollPos(cm, {
  14871. left: Math.min(from.left, to.left),
  14872. top: Math.min(from.top, to.top) - margin,
  14873. right: Math.max(from.right, to.right),
  14874. bottom: Math.max(from.bottom, to.bottom) + margin
  14875. });
  14876. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  14877. }
  14878. // Sync the scrollable area and scrollbars, ensure the viewport
  14879. // covers the visible area.
  14880. function updateScrollTop(cm, val) {
  14881. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  14882. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  14883. setScrollTop(cm, val, true);
  14884. if (gecko) { updateDisplaySimple(cm); }
  14885. startWorker(cm, 100);
  14886. }
  14887. function setScrollTop(cm, val, forceScroll) {
  14888. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
  14889. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  14890. cm.doc.scrollTop = val;
  14891. cm.display.scrollbars.setScrollTop(val);
  14892. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  14893. }
  14894. // Sync scroller and scrollbar, ensure the gutter elements are
  14895. // aligned.
  14896. function setScrollLeft(cm, val, isScroller, forceScroll) {
  14897. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  14898. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  14899. cm.doc.scrollLeft = val;
  14900. alignHorizontally(cm);
  14901. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  14902. cm.display.scrollbars.setScrollLeft(val);
  14903. }
  14904. // SCROLLBARS
  14905. // Prepare DOM reads needed to update the scrollbars. Done in one
  14906. // shot to minimize update/measure roundtrips.
  14907. function measureForScrollbars(cm) {
  14908. var d = cm.display, gutterW = d.gutters.offsetWidth;
  14909. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  14910. return {
  14911. clientHeight: d.scroller.clientHeight,
  14912. viewHeight: d.wrapper.clientHeight,
  14913. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  14914. viewWidth: d.wrapper.clientWidth,
  14915. barLeft: cm.options.fixedGutter ? gutterW : 0,
  14916. docHeight: docH,
  14917. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  14918. nativeBarWidth: d.nativeBarWidth,
  14919. gutterWidth: gutterW
  14920. }
  14921. }
  14922. var NativeScrollbars = function(place, scroll, cm) {
  14923. this.cm = cm;
  14924. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  14925. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  14926. vert.tabIndex = horiz.tabIndex = -1;
  14927. place(vert); place(horiz);
  14928. on(vert, "scroll", function () {
  14929. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  14930. });
  14931. on(horiz, "scroll", function () {
  14932. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  14933. });
  14934. this.checkedZeroWidth = false;
  14935. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  14936. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  14937. };
  14938. NativeScrollbars.prototype.update = function (measure) {
  14939. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  14940. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  14941. var sWidth = measure.nativeBarWidth;
  14942. if (needsV) {
  14943. this.vert.style.display = "block";
  14944. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  14945. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  14946. // A bug in IE8 can cause this value to be negative, so guard it.
  14947. this.vert.firstChild.style.height =
  14948. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  14949. } else {
  14950. this.vert.style.display = "";
  14951. this.vert.firstChild.style.height = "0";
  14952. }
  14953. if (needsH) {
  14954. this.horiz.style.display = "block";
  14955. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  14956. this.horiz.style.left = measure.barLeft + "px";
  14957. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  14958. this.horiz.firstChild.style.width =
  14959. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  14960. } else {
  14961. this.horiz.style.display = "";
  14962. this.horiz.firstChild.style.width = "0";
  14963. }
  14964. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  14965. if (sWidth == 0) { this.zeroWidthHack(); }
  14966. this.checkedZeroWidth = true;
  14967. }
  14968. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  14969. };
  14970. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  14971. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  14972. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  14973. };
  14974. NativeScrollbars.prototype.setScrollTop = function (pos) {
  14975. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  14976. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  14977. };
  14978. NativeScrollbars.prototype.zeroWidthHack = function () {
  14979. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  14980. this.horiz.style.height = this.vert.style.width = w;
  14981. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  14982. this.disableHoriz = new Delayed;
  14983. this.disableVert = new Delayed;
  14984. };
  14985. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  14986. bar.style.pointerEvents = "auto";
  14987. function maybeDisable() {
  14988. // To find out whether the scrollbar is still visible, we
  14989. // check whether the element under the pixel in the bottom
  14990. // right corner of the scrollbar box is the scrollbar box
  14991. // itself (when the bar is still visible) or its filler child
  14992. // (when the bar is hidden). If it is still visible, we keep
  14993. // it enabled, if it's hidden, we disable pointer events.
  14994. var box = bar.getBoundingClientRect();
  14995. var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  14996. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  14997. if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
  14998. else { delay.set(1000, maybeDisable); }
  14999. }
  15000. delay.set(1000, maybeDisable);
  15001. };
  15002. NativeScrollbars.prototype.clear = function () {
  15003. var parent = this.horiz.parentNode;
  15004. parent.removeChild(this.horiz);
  15005. parent.removeChild(this.vert);
  15006. };
  15007. var NullScrollbars = function () {};
  15008. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  15009. NullScrollbars.prototype.setScrollLeft = function () {};
  15010. NullScrollbars.prototype.setScrollTop = function () {};
  15011. NullScrollbars.prototype.clear = function () {};
  15012. function updateScrollbars(cm, measure) {
  15013. if (!measure) { measure = measureForScrollbars(cm); }
  15014. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  15015. updateScrollbarsInner(cm, measure);
  15016. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  15017. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  15018. { updateHeightsInViewport(cm); }
  15019. updateScrollbarsInner(cm, measureForScrollbars(cm));
  15020. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  15021. }
  15022. }
  15023. // Re-synchronize the fake scrollbars with the actual size of the
  15024. // content.
  15025. function updateScrollbarsInner(cm, measure) {
  15026. var d = cm.display;
  15027. var sizes = d.scrollbars.update(measure);
  15028. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  15029. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  15030. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  15031. if (sizes.right && sizes.bottom) {
  15032. d.scrollbarFiller.style.display = "block";
  15033. d.scrollbarFiller.style.height = sizes.bottom + "px";
  15034. d.scrollbarFiller.style.width = sizes.right + "px";
  15035. } else { d.scrollbarFiller.style.display = ""; }
  15036. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  15037. d.gutterFiller.style.display = "block";
  15038. d.gutterFiller.style.height = sizes.bottom + "px";
  15039. d.gutterFiller.style.width = measure.gutterWidth + "px";
  15040. } else { d.gutterFiller.style.display = ""; }
  15041. }
  15042. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  15043. function initScrollbars(cm) {
  15044. if (cm.display.scrollbars) {
  15045. cm.display.scrollbars.clear();
  15046. if (cm.display.scrollbars.addClass)
  15047. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  15048. }
  15049. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  15050. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  15051. // Prevent clicks in the scrollbars from killing focus
  15052. on(node, "mousedown", function () {
  15053. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  15054. });
  15055. node.setAttribute("cm-not-content", "true");
  15056. }, function (pos, axis) {
  15057. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  15058. else { updateScrollTop(cm, pos); }
  15059. }, cm);
  15060. if (cm.display.scrollbars.addClass)
  15061. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  15062. }
  15063. // Operations are used to wrap a series of changes to the editor
  15064. // state in such a way that each change won't have to update the
  15065. // cursor and display (which would be awkward, slow, and
  15066. // error-prone). Instead, display updates are batched and then all
  15067. // combined and executed at once.
  15068. var nextOpId = 0;
  15069. // Start a new operation.
  15070. function startOperation(cm) {
  15071. cm.curOp = {
  15072. cm: cm,
  15073. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  15074. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  15075. forceUpdate: false, // Used to force a redraw
  15076. updateInput: 0, // Whether to reset the input textarea
  15077. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  15078. changeObjs: null, // Accumulated changes, for firing change events
  15079. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  15080. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  15081. selectionChanged: false, // Whether the selection needs to be redrawn
  15082. updateMaxLine: false, // Set when the widest line needs to be determined anew
  15083. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  15084. scrollToPos: null, // Used to scroll to a specific position
  15085. focus: false,
  15086. id: ++nextOpId // Unique ID
  15087. };
  15088. pushOperation(cm.curOp);
  15089. }
  15090. // Finish an operation, updating the display and signalling delayed events
  15091. function endOperation(cm) {
  15092. var op = cm.curOp;
  15093. if (op) { finishOperation(op, function (group) {
  15094. for (var i = 0; i < group.ops.length; i++)
  15095. { group.ops[i].cm.curOp = null; }
  15096. endOperations(group);
  15097. }); }
  15098. }
  15099. // The DOM updates done when an operation finishes are batched so
  15100. // that the minimum number of relayouts are required.
  15101. function endOperations(group) {
  15102. var ops = group.ops;
  15103. for (var i = 0; i < ops.length; i++) // Read DOM
  15104. { endOperation_R1(ops[i]); }
  15105. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  15106. { endOperation_W1(ops[i$1]); }
  15107. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  15108. { endOperation_R2(ops[i$2]); }
  15109. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  15110. { endOperation_W2(ops[i$3]); }
  15111. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  15112. { endOperation_finish(ops[i$4]); }
  15113. }
  15114. function endOperation_R1(op) {
  15115. var cm = op.cm, display = cm.display;
  15116. maybeClipScrollbars(cm);
  15117. if (op.updateMaxLine) { findMaxLine(cm); }
  15118. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  15119. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  15120. op.scrollToPos.to.line >= display.viewTo) ||
  15121. display.maxLineChanged && cm.options.lineWrapping;
  15122. op.update = op.mustUpdate &&
  15123. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  15124. }
  15125. function endOperation_W1(op) {
  15126. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  15127. }
  15128. function endOperation_R2(op) {
  15129. var cm = op.cm, display = cm.display;
  15130. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  15131. op.barMeasure = measureForScrollbars(cm);
  15132. // If the max line changed since it was last measured, measure it,
  15133. // and ensure the document's width matches it.
  15134. // updateDisplay_W2 will use these properties to do the actual resizing
  15135. if (display.maxLineChanged && !cm.options.lineWrapping) {
  15136. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  15137. cm.display.sizerWidth = op.adjustWidthTo;
  15138. op.barMeasure.scrollWidth =
  15139. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  15140. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  15141. }
  15142. if (op.updatedDisplay || op.selectionChanged)
  15143. { op.preparedSelection = display.input.prepareSelection(); }
  15144. }
  15145. function endOperation_W2(op) {
  15146. var cm = op.cm;
  15147. if (op.adjustWidthTo != null) {
  15148. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  15149. if (op.maxScrollLeft < cm.doc.scrollLeft)
  15150. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  15151. cm.display.maxLineChanged = false;
  15152. }
  15153. var takeFocus = op.focus && op.focus == activeElt();
  15154. if (op.preparedSelection)
  15155. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  15156. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  15157. { updateScrollbars(cm, op.barMeasure); }
  15158. if (op.updatedDisplay)
  15159. { setDocumentHeight(cm, op.barMeasure); }
  15160. if (op.selectionChanged) { restartBlink(cm); }
  15161. if (cm.state.focused && op.updateInput)
  15162. { cm.display.input.reset(op.typing); }
  15163. if (takeFocus) { ensureFocus(op.cm); }
  15164. }
  15165. function endOperation_finish(op) {
  15166. var cm = op.cm, display = cm.display, doc = cm.doc;
  15167. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  15168. // Abort mouse wheel delta measurement, when scrolling explicitly
  15169. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  15170. { display.wheelStartX = display.wheelStartY = null; }
  15171. // Propagate the scroll position to the actual DOM scroller
  15172. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  15173. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  15174. // If we need to scroll a specific position into view, do so.
  15175. if (op.scrollToPos) {
  15176. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  15177. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  15178. maybeScrollWindow(cm, rect);
  15179. }
  15180. // Fire events for markers that are hidden/unidden by editing or
  15181. // undoing
  15182. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  15183. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  15184. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  15185. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  15186. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  15187. if (display.wrapper.offsetHeight)
  15188. { doc.scrollTop = cm.display.scroller.scrollTop; }
  15189. // Fire change events, and delayed event handlers
  15190. if (op.changeObjs)
  15191. { signal(cm, "changes", cm, op.changeObjs); }
  15192. if (op.update)
  15193. { op.update.finish(); }
  15194. }
  15195. // Run the given function in an operation
  15196. function runInOp(cm, f) {
  15197. if (cm.curOp) { return f() }
  15198. startOperation(cm);
  15199. try { return f() }
  15200. finally { endOperation(cm); }
  15201. }
  15202. // Wraps a function in an operation. Returns the wrapped function.
  15203. function operation(cm, f) {
  15204. return function() {
  15205. if (cm.curOp) { return f.apply(cm, arguments) }
  15206. startOperation(cm);
  15207. try { return f.apply(cm, arguments) }
  15208. finally { endOperation(cm); }
  15209. }
  15210. }
  15211. // Used to add methods to editor and doc instances, wrapping them in
  15212. // operations.
  15213. function methodOp(f) {
  15214. return function() {
  15215. if (this.curOp) { return f.apply(this, arguments) }
  15216. startOperation(this);
  15217. try { return f.apply(this, arguments) }
  15218. finally { endOperation(this); }
  15219. }
  15220. }
  15221. function docMethodOp(f) {
  15222. return function() {
  15223. var cm = this.cm;
  15224. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  15225. startOperation(cm);
  15226. try { return f.apply(this, arguments) }
  15227. finally { endOperation(cm); }
  15228. }
  15229. }
  15230. // HIGHLIGHT WORKER
  15231. function startWorker(cm, time) {
  15232. if (cm.doc.highlightFrontier < cm.display.viewTo)
  15233. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  15234. }
  15235. function highlightWorker(cm) {
  15236. var doc = cm.doc;
  15237. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  15238. var end = +new Date + cm.options.workTime;
  15239. var context = getContextBefore(cm, doc.highlightFrontier);
  15240. var changedLines = [];
  15241. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  15242. if (context.line >= cm.display.viewFrom) { // Visible
  15243. var oldStyles = line.styles;
  15244. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  15245. var highlighted = highlightLine(cm, line, context, true);
  15246. if (resetState) { context.state = resetState; }
  15247. line.styles = highlighted.styles;
  15248. var oldCls = line.styleClasses, newCls = highlighted.classes;
  15249. if (newCls) { line.styleClasses = newCls; }
  15250. else if (oldCls) { line.styleClasses = null; }
  15251. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  15252. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  15253. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  15254. if (ischange) { changedLines.push(context.line); }
  15255. line.stateAfter = context.save();
  15256. context.nextLine();
  15257. } else {
  15258. if (line.text.length <= cm.options.maxHighlightLength)
  15259. { processLine(cm, line.text, context); }
  15260. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  15261. context.nextLine();
  15262. }
  15263. if (+new Date > end) {
  15264. startWorker(cm, cm.options.workDelay);
  15265. return true
  15266. }
  15267. });
  15268. doc.highlightFrontier = context.line;
  15269. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  15270. if (changedLines.length) { runInOp(cm, function () {
  15271. for (var i = 0; i < changedLines.length; i++)
  15272. { regLineChange(cm, changedLines[i], "text"); }
  15273. }); }
  15274. }
  15275. // DISPLAY DRAWING
  15276. var DisplayUpdate = function(cm, viewport, force) {
  15277. var display = cm.display;
  15278. this.viewport = viewport;
  15279. // Store some values that we'll need later (but don't want to force a relayout for)
  15280. this.visible = visibleLines(display, cm.doc, viewport);
  15281. this.editorIsHidden = !display.wrapper.offsetWidth;
  15282. this.wrapperHeight = display.wrapper.clientHeight;
  15283. this.wrapperWidth = display.wrapper.clientWidth;
  15284. this.oldDisplayWidth = displayWidth(cm);
  15285. this.force = force;
  15286. this.dims = getDimensions(cm);
  15287. this.events = [];
  15288. };
  15289. DisplayUpdate.prototype.signal = function (emitter, type) {
  15290. if (hasHandler(emitter, type))
  15291. { this.events.push(arguments); }
  15292. };
  15293. DisplayUpdate.prototype.finish = function () {
  15294. var this$1 = this;
  15295. for (var i = 0; i < this.events.length; i++)
  15296. { signal.apply(null, this$1.events[i]); }
  15297. };
  15298. function maybeClipScrollbars(cm) {
  15299. var display = cm.display;
  15300. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  15301. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  15302. display.heightForcer.style.height = scrollGap(cm) + "px";
  15303. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  15304. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  15305. display.scrollbarsClipped = true;
  15306. }
  15307. }
  15308. function selectionSnapshot(cm) {
  15309. if (cm.hasFocus()) { return null }
  15310. var active = activeElt();
  15311. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  15312. var result = {activeElt: active};
  15313. if (window.getSelection) {
  15314. var sel = window.getSelection();
  15315. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  15316. result.anchorNode = sel.anchorNode;
  15317. result.anchorOffset = sel.anchorOffset;
  15318. result.focusNode = sel.focusNode;
  15319. result.focusOffset = sel.focusOffset;
  15320. }
  15321. }
  15322. return result
  15323. }
  15324. function restoreSelection(snapshot) {
  15325. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  15326. snapshot.activeElt.focus();
  15327. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  15328. var sel = window.getSelection(), range$$1 = document.createRange();
  15329. range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  15330. range$$1.collapse(false);
  15331. sel.removeAllRanges();
  15332. sel.addRange(range$$1);
  15333. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  15334. }
  15335. }
  15336. // Does the actual updating of the line display. Bails out
  15337. // (returning false) when there is nothing to be done and forced is
  15338. // false.
  15339. function updateDisplayIfNeeded(cm, update) {
  15340. var display = cm.display, doc = cm.doc;
  15341. if (update.editorIsHidden) {
  15342. resetView(cm);
  15343. return false
  15344. }
  15345. // Bail out if the visible area is already rendered and nothing changed.
  15346. if (!update.force &&
  15347. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  15348. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  15349. display.renderedView == display.view && countDirtyView(cm) == 0)
  15350. { return false }
  15351. if (maybeUpdateLineNumberWidth(cm)) {
  15352. resetView(cm);
  15353. update.dims = getDimensions(cm);
  15354. }
  15355. // Compute a suitable new viewport (from & to)
  15356. var end = doc.first + doc.size;
  15357. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  15358. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  15359. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  15360. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  15361. if (sawCollapsedSpans) {
  15362. from = visualLineNo(cm.doc, from);
  15363. to = visualLineEndNo(cm.doc, to);
  15364. }
  15365. var different = from != display.viewFrom || to != display.viewTo ||
  15366. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  15367. adjustView(cm, from, to);
  15368. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  15369. // Position the mover div to align with the current scroll position
  15370. cm.display.mover.style.top = display.viewOffset + "px";
  15371. var toUpdate = countDirtyView(cm);
  15372. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  15373. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  15374. { return false }
  15375. // For big changes, we hide the enclosing element during the
  15376. // update, since that speeds up the operations on most browsers.
  15377. var selSnapshot = selectionSnapshot(cm);
  15378. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  15379. patchDisplay(cm, display.updateLineNumbers, update.dims);
  15380. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  15381. display.renderedView = display.view;
  15382. // There might have been a widget with a focused element that got
  15383. // hidden or updated, if so re-focus it.
  15384. restoreSelection(selSnapshot);
  15385. // Prevent selection and cursors from interfering with the scroll
  15386. // width and height.
  15387. removeChildren(display.cursorDiv);
  15388. removeChildren(display.selectionDiv);
  15389. display.gutters.style.height = display.sizer.style.minHeight = 0;
  15390. if (different) {
  15391. display.lastWrapHeight = update.wrapperHeight;
  15392. display.lastWrapWidth = update.wrapperWidth;
  15393. startWorker(cm, 400);
  15394. }
  15395. display.updateLineNumbers = null;
  15396. return true
  15397. }
  15398. function postUpdateDisplay(cm, update) {
  15399. var viewport = update.viewport;
  15400. for (var first = true;; first = false) {
  15401. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  15402. // Clip forced viewport to actual scrollable area.
  15403. if (viewport && viewport.top != null)
  15404. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  15405. // Updated line heights might result in the drawn area not
  15406. // actually covering the viewport. Keep looping until it does.
  15407. update.visible = visibleLines(cm.display, cm.doc, viewport);
  15408. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  15409. { break }
  15410. }
  15411. if (!updateDisplayIfNeeded(cm, update)) { break }
  15412. updateHeightsInViewport(cm);
  15413. var barMeasure = measureForScrollbars(cm);
  15414. updateSelection(cm);
  15415. updateScrollbars(cm, barMeasure);
  15416. setDocumentHeight(cm, barMeasure);
  15417. update.force = false;
  15418. }
  15419. update.signal(cm, "update", cm);
  15420. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  15421. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  15422. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  15423. }
  15424. }
  15425. function updateDisplaySimple(cm, viewport) {
  15426. var update = new DisplayUpdate(cm, viewport);
  15427. if (updateDisplayIfNeeded(cm, update)) {
  15428. updateHeightsInViewport(cm);
  15429. postUpdateDisplay(cm, update);
  15430. var barMeasure = measureForScrollbars(cm);
  15431. updateSelection(cm);
  15432. updateScrollbars(cm, barMeasure);
  15433. setDocumentHeight(cm, barMeasure);
  15434. update.finish();
  15435. }
  15436. }
  15437. // Sync the actual display DOM structure with display.view, removing
  15438. // nodes for lines that are no longer in view, and creating the ones
  15439. // that are not there yet, and updating the ones that are out of
  15440. // date.
  15441. function patchDisplay(cm, updateNumbersFrom, dims) {
  15442. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  15443. var container = display.lineDiv, cur = container.firstChild;
  15444. function rm(node) {
  15445. var next = node.nextSibling;
  15446. // Works around a throw-scroll bug in OS X Webkit
  15447. if (webkit && mac && cm.display.currentWheelTarget == node)
  15448. { node.style.display = "none"; }
  15449. else
  15450. { node.parentNode.removeChild(node); }
  15451. return next
  15452. }
  15453. var view = display.view, lineN = display.viewFrom;
  15454. // Loop over the elements in the view, syncing cur (the DOM nodes
  15455. // in display.lineDiv) with the view as we go.
  15456. for (var i = 0; i < view.length; i++) {
  15457. var lineView = view[i];
  15458. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  15459. var node = buildLineElement(cm, lineView, lineN, dims);
  15460. container.insertBefore(node, cur);
  15461. } else { // Already drawn
  15462. while (cur != lineView.node) { cur = rm(cur); }
  15463. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  15464. updateNumbersFrom <= lineN && lineView.lineNumber;
  15465. if (lineView.changes) {
  15466. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  15467. updateLineForChanges(cm, lineView, lineN, dims);
  15468. }
  15469. if (updateNumber) {
  15470. removeChildren(lineView.lineNumber);
  15471. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  15472. }
  15473. cur = lineView.node.nextSibling;
  15474. }
  15475. lineN += lineView.size;
  15476. }
  15477. while (cur) { cur = rm(cur); }
  15478. }
  15479. function updateGutterSpace(display) {
  15480. var width = display.gutters.offsetWidth;
  15481. display.sizer.style.marginLeft = width + "px";
  15482. }
  15483. function setDocumentHeight(cm, measure) {
  15484. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  15485. cm.display.heightForcer.style.top = measure.docHeight + "px";
  15486. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  15487. }
  15488. // Re-align line numbers and gutter marks to compensate for
  15489. // horizontal scrolling.
  15490. function alignHorizontally(cm) {
  15491. var display = cm.display, view = display.view;
  15492. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  15493. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  15494. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  15495. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  15496. if (cm.options.fixedGutter) {
  15497. if (view[i].gutter)
  15498. { view[i].gutter.style.left = left; }
  15499. if (view[i].gutterBackground)
  15500. { view[i].gutterBackground.style.left = left; }
  15501. }
  15502. var align = view[i].alignable;
  15503. if (align) { for (var j = 0; j < align.length; j++)
  15504. { align[j].style.left = left; } }
  15505. } }
  15506. if (cm.options.fixedGutter)
  15507. { display.gutters.style.left = (comp + gutterW) + "px"; }
  15508. }
  15509. // Used to ensure that the line number gutter is still the right
  15510. // size for the current document size. Returns true when an update
  15511. // is needed.
  15512. function maybeUpdateLineNumberWidth(cm) {
  15513. if (!cm.options.lineNumbers) { return false }
  15514. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  15515. if (last.length != display.lineNumChars) {
  15516. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  15517. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  15518. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  15519. display.lineGutter.style.width = "";
  15520. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  15521. display.lineNumWidth = display.lineNumInnerWidth + padding;
  15522. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  15523. display.lineGutter.style.width = display.lineNumWidth + "px";
  15524. updateGutterSpace(cm.display);
  15525. return true
  15526. }
  15527. return false
  15528. }
  15529. function getGutters(gutters, lineNumbers) {
  15530. var result = [], sawLineNumbers = false;
  15531. for (var i = 0; i < gutters.length; i++) {
  15532. var name = gutters[i], style = null;
  15533. if (typeof name != "string") { style = name.style; name = name.className; }
  15534. if (name == "CodeMirror-linenumbers") {
  15535. if (!lineNumbers) { continue }
  15536. else { sawLineNumbers = true; }
  15537. }
  15538. result.push({className: name, style: style});
  15539. }
  15540. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  15541. return result
  15542. }
  15543. // Rebuild the gutter elements, ensure the margin to the left of the
  15544. // code matches their width.
  15545. function renderGutters(display) {
  15546. var gutters = display.gutters, specs = display.gutterSpecs;
  15547. removeChildren(gutters);
  15548. display.lineGutter = null;
  15549. for (var i = 0; i < specs.length; ++i) {
  15550. var ref = specs[i];
  15551. var className = ref.className;
  15552. var style = ref.style;
  15553. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  15554. if (style) { gElt.style.cssText = style; }
  15555. if (className == "CodeMirror-linenumbers") {
  15556. display.lineGutter = gElt;
  15557. gElt.style.width = (display.lineNumWidth || 1) + "px";
  15558. }
  15559. }
  15560. gutters.style.display = specs.length ? "" : "none";
  15561. updateGutterSpace(display);
  15562. }
  15563. function updateGutters(cm) {
  15564. renderGutters(cm.display);
  15565. regChange(cm);
  15566. alignHorizontally(cm);
  15567. }
  15568. // The display handles the DOM integration, both for input reading
  15569. // and content drawing. It holds references to DOM nodes and
  15570. // display-related state.
  15571. function Display(place, doc, input, options) {
  15572. var d = this;
  15573. this.input = input;
  15574. // Covers bottom-right square when both scrollbars are present.
  15575. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  15576. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  15577. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  15578. // and h scrollbar is present.
  15579. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  15580. d.gutterFiller.setAttribute("cm-not-content", "true");
  15581. // Will contain the actual code, positioned to cover the viewport.
  15582. d.lineDiv = eltP("div", null, "CodeMirror-code");
  15583. // Elements are added to these to represent selection and cursors.
  15584. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  15585. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  15586. // A visibility: hidden element used to find the size of things.
  15587. d.measure = elt("div", null, "CodeMirror-measure");
  15588. // When lines outside of the viewport are measured, they are drawn in this.
  15589. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  15590. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  15591. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  15592. null, "position: relative; outline: none");
  15593. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  15594. // Moved around its parent to cover visible view.
  15595. d.mover = elt("div", [lines], null, "position: relative");
  15596. // Set to the height of the document, allowing scrolling.
  15597. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  15598. d.sizerWidth = null;
  15599. // Behavior of elts with overflow: auto and padding is
  15600. // inconsistent across browsers. This is used to ensure the
  15601. // scrollable area is big enough.
  15602. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  15603. // Will contain the gutters, if any.
  15604. d.gutters = elt("div", null, "CodeMirror-gutters");
  15605. d.lineGutter = null;
  15606. // Actual scrollable element.
  15607. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  15608. d.scroller.setAttribute("tabIndex", "-1");
  15609. // The element in which the editor lives.
  15610. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  15611. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  15612. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  15613. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  15614. if (place) {
  15615. if (place.appendChild) { place.appendChild(d.wrapper); }
  15616. else { place(d.wrapper); }
  15617. }
  15618. // Current rendered range (may be bigger than the view window).
  15619. d.viewFrom = d.viewTo = doc.first;
  15620. d.reportedViewFrom = d.reportedViewTo = doc.first;
  15621. // Information about the rendered lines.
  15622. d.view = [];
  15623. d.renderedView = null;
  15624. // Holds info about a single rendered line when it was rendered
  15625. // for measurement, while not in view.
  15626. d.externalMeasured = null;
  15627. // Empty space (in pixels) above the view
  15628. d.viewOffset = 0;
  15629. d.lastWrapHeight = d.lastWrapWidth = 0;
  15630. d.updateLineNumbers = null;
  15631. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  15632. d.scrollbarsClipped = false;
  15633. // Used to only resize the line number gutter when necessary (when
  15634. // the amount of lines crosses a boundary that makes its width change)
  15635. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  15636. // Set to true when a non-horizontal-scrolling line widget is
  15637. // added. As an optimization, line widget aligning is skipped when
  15638. // this is false.
  15639. d.alignWidgets = false;
  15640. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  15641. // Tracks the maximum line length so that the horizontal scrollbar
  15642. // can be kept static when scrolling.
  15643. d.maxLine = null;
  15644. d.maxLineLength = 0;
  15645. d.maxLineChanged = false;
  15646. // Used for measuring wheel scrolling granularity
  15647. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  15648. // True when shift is held down.
  15649. d.shift = false;
  15650. // Used to track whether anything happened since the context menu
  15651. // was opened.
  15652. d.selForContextMenu = null;
  15653. d.activeTouch = null;
  15654. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  15655. renderGutters(d);
  15656. input.init(d);
  15657. }
  15658. // Since the delta values reported on mouse wheel events are
  15659. // unstandardized between browsers and even browser versions, and
  15660. // generally horribly unpredictable, this code starts by measuring
  15661. // the scroll effect that the first few mouse wheel events have,
  15662. // and, from that, detects the way it can convert deltas to pixel
  15663. // offsets afterwards.
  15664. //
  15665. // The reason we want to know the amount a wheel event will scroll
  15666. // is that it gives us a chance to update the display before the
  15667. // actual scrolling happens, reducing flickering.
  15668. var wheelSamples = 0, wheelPixelsPerUnit = null;
  15669. // Fill in a browser-detected starting value on browsers where we
  15670. // know one. These don't have to be accurate -- the result of them
  15671. // being wrong would just be a slight flicker on the first wheel
  15672. // scroll (if it is large enough).
  15673. if (ie) { wheelPixelsPerUnit = -.53; }
  15674. else if (gecko) { wheelPixelsPerUnit = 15; }
  15675. else if (chrome) { wheelPixelsPerUnit = -.7; }
  15676. else if (safari) { wheelPixelsPerUnit = -1/3; }
  15677. function wheelEventDelta(e) {
  15678. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  15679. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  15680. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  15681. else if (dy == null) { dy = e.wheelDelta; }
  15682. return {x: dx, y: dy}
  15683. }
  15684. function wheelEventPixels(e) {
  15685. var delta = wheelEventDelta(e);
  15686. delta.x *= wheelPixelsPerUnit;
  15687. delta.y *= wheelPixelsPerUnit;
  15688. return delta
  15689. }
  15690. function onScrollWheel(cm, e) {
  15691. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  15692. var display = cm.display, scroll = display.scroller;
  15693. // Quit if there's nothing to scroll here
  15694. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  15695. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  15696. if (!(dx && canScrollX || dy && canScrollY)) { return }
  15697. // Webkit browsers on OS X abort momentum scrolls when the target
  15698. // of the scroll event is removed from the scrollable element.
  15699. // This hack (see related code in patchDisplay) makes sure the
  15700. // element is kept around.
  15701. if (dy && mac && webkit) {
  15702. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  15703. for (var i = 0; i < view.length; i++) {
  15704. if (view[i].node == cur) {
  15705. cm.display.currentWheelTarget = cur;
  15706. break outer
  15707. }
  15708. }
  15709. }
  15710. }
  15711. // On some browsers, horizontal scrolling will cause redraws to
  15712. // happen before the gutter has been realigned, causing it to
  15713. // wriggle around in a most unseemly way. When we have an
  15714. // estimated pixels/delta value, we just handle horizontal
  15715. // scrolling entirely here. It'll be slightly off from native, but
  15716. // better than glitching out.
  15717. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  15718. if (dy && canScrollY)
  15719. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  15720. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  15721. // Only prevent default scrolling if vertical scrolling is
  15722. // actually possible. Otherwise, it causes vertical scroll
  15723. // jitter on OSX trackpads when deltaX is small and deltaY
  15724. // is large (issue #3579)
  15725. if (!dy || (dy && canScrollY))
  15726. { e_preventDefault(e); }
  15727. display.wheelStartX = null; // Abort measurement, if in progress
  15728. return
  15729. }
  15730. // 'Project' the visible viewport to cover the area that is being
  15731. // scrolled into view (if we know enough to estimate it).
  15732. if (dy && wheelPixelsPerUnit != null) {
  15733. var pixels = dy * wheelPixelsPerUnit;
  15734. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  15735. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  15736. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  15737. updateDisplaySimple(cm, {top: top, bottom: bot});
  15738. }
  15739. if (wheelSamples < 20) {
  15740. if (display.wheelStartX == null) {
  15741. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  15742. display.wheelDX = dx; display.wheelDY = dy;
  15743. setTimeout(function () {
  15744. if (display.wheelStartX == null) { return }
  15745. var movedX = scroll.scrollLeft - display.wheelStartX;
  15746. var movedY = scroll.scrollTop - display.wheelStartY;
  15747. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  15748. (movedX && display.wheelDX && movedX / display.wheelDX);
  15749. display.wheelStartX = display.wheelStartY = null;
  15750. if (!sample) { return }
  15751. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  15752. ++wheelSamples;
  15753. }, 200);
  15754. } else {
  15755. display.wheelDX += dx; display.wheelDY += dy;
  15756. }
  15757. }
  15758. }
  15759. // Selection objects are immutable. A new one is created every time
  15760. // the selection changes. A selection is one or more non-overlapping
  15761. // (and non-touching) ranges, sorted, and an integer that indicates
  15762. // which one is the primary selection (the one that's scrolled into
  15763. // view, that getCursor returns, etc).
  15764. var Selection = function(ranges, primIndex) {
  15765. this.ranges = ranges;
  15766. this.primIndex = primIndex;
  15767. };
  15768. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  15769. Selection.prototype.equals = function (other) {
  15770. var this$1 = this;
  15771. if (other == this) { return true }
  15772. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  15773. for (var i = 0; i < this.ranges.length; i++) {
  15774. var here = this$1.ranges[i], there = other.ranges[i];
  15775. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  15776. }
  15777. return true
  15778. };
  15779. Selection.prototype.deepCopy = function () {
  15780. var this$1 = this;
  15781. var out = [];
  15782. for (var i = 0; i < this.ranges.length; i++)
  15783. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
  15784. return new Selection(out, this.primIndex)
  15785. };
  15786. Selection.prototype.somethingSelected = function () {
  15787. var this$1 = this;
  15788. for (var i = 0; i < this.ranges.length; i++)
  15789. { if (!this$1.ranges[i].empty()) { return true } }
  15790. return false
  15791. };
  15792. Selection.prototype.contains = function (pos, end) {
  15793. var this$1 = this;
  15794. if (!end) { end = pos; }
  15795. for (var i = 0; i < this.ranges.length; i++) {
  15796. var range = this$1.ranges[i];
  15797. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  15798. { return i }
  15799. }
  15800. return -1
  15801. };
  15802. var Range = function(anchor, head) {
  15803. this.anchor = anchor; this.head = head;
  15804. };
  15805. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  15806. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  15807. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  15808. // Take an unsorted, potentially overlapping set of ranges, and
  15809. // build a selection out of it. 'Consumes' ranges array (modifying
  15810. // it).
  15811. function normalizeSelection(cm, ranges, primIndex) {
  15812. var mayTouch = cm && cm.options.selectionsMayTouch;
  15813. var prim = ranges[primIndex];
  15814. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  15815. primIndex = indexOf(ranges, prim);
  15816. for (var i = 1; i < ranges.length; i++) {
  15817. var cur = ranges[i], prev = ranges[i - 1];
  15818. var diff = cmp(prev.to(), cur.from());
  15819. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  15820. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  15821. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  15822. if (i <= primIndex) { --primIndex; }
  15823. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  15824. }
  15825. }
  15826. return new Selection(ranges, primIndex)
  15827. }
  15828. function simpleSelection(anchor, head) {
  15829. return new Selection([new Range(anchor, head || anchor)], 0)
  15830. }
  15831. // Compute the position of the end of a change (its 'to' property
  15832. // refers to the pre-change end).
  15833. function changeEnd(change) {
  15834. if (!change.text) { return change.to }
  15835. return Pos(change.from.line + change.text.length - 1,
  15836. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  15837. }
  15838. // Adjust a position to refer to the post-change position of the
  15839. // same text, or the end of the change if the change covers it.
  15840. function adjustForChange(pos, change) {
  15841. if (cmp(pos, change.from) < 0) { return pos }
  15842. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  15843. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  15844. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  15845. return Pos(line, ch)
  15846. }
  15847. function computeSelAfterChange(doc, change) {
  15848. var out = [];
  15849. for (var i = 0; i < doc.sel.ranges.length; i++) {
  15850. var range = doc.sel.ranges[i];
  15851. out.push(new Range(adjustForChange(range.anchor, change),
  15852. adjustForChange(range.head, change)));
  15853. }
  15854. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  15855. }
  15856. function offsetPos(pos, old, nw) {
  15857. if (pos.line == old.line)
  15858. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  15859. else
  15860. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  15861. }
  15862. // Used by replaceSelections to allow moving the selection to the
  15863. // start or around the replaced test. Hint may be "start" or "around".
  15864. function computeReplacedSel(doc, changes, hint) {
  15865. var out = [];
  15866. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  15867. for (var i = 0; i < changes.length; i++) {
  15868. var change = changes[i];
  15869. var from = offsetPos(change.from, oldPrev, newPrev);
  15870. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  15871. oldPrev = change.to;
  15872. newPrev = to;
  15873. if (hint == "around") {
  15874. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  15875. out[i] = new Range(inv ? to : from, inv ? from : to);
  15876. } else {
  15877. out[i] = new Range(from, from);
  15878. }
  15879. }
  15880. return new Selection(out, doc.sel.primIndex)
  15881. }
  15882. // Used to get the editor into a consistent state again when options change.
  15883. function loadMode(cm) {
  15884. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  15885. resetModeState(cm);
  15886. }
  15887. function resetModeState(cm) {
  15888. cm.doc.iter(function (line) {
  15889. if (line.stateAfter) { line.stateAfter = null; }
  15890. if (line.styles) { line.styles = null; }
  15891. });
  15892. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  15893. startWorker(cm, 100);
  15894. cm.state.modeGen++;
  15895. if (cm.curOp) { regChange(cm); }
  15896. }
  15897. // DOCUMENT DATA STRUCTURE
  15898. // By default, updates that start and end at the beginning of a line
  15899. // are treated specially, in order to make the association of line
  15900. // widgets and marker elements with the text behave more intuitive.
  15901. function isWholeLineUpdate(doc, change) {
  15902. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  15903. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  15904. }
  15905. // Perform a change on the document data structure.
  15906. function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  15907. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  15908. function update(line, text, spans) {
  15909. updateLine(line, text, spans, estimateHeight$$1);
  15910. signalLater(line, "change", line, change);
  15911. }
  15912. function linesFor(start, end) {
  15913. var result = [];
  15914. for (var i = start; i < end; ++i)
  15915. { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
  15916. return result
  15917. }
  15918. var from = change.from, to = change.to, text = change.text;
  15919. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  15920. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  15921. // Adjust the line structure
  15922. if (change.full) {
  15923. doc.insert(0, linesFor(0, text.length));
  15924. doc.remove(text.length, doc.size - text.length);
  15925. } else if (isWholeLineUpdate(doc, change)) {
  15926. // This is a whole-line replace. Treated specially to make
  15927. // sure line objects move the way they are supposed to.
  15928. var added = linesFor(0, text.length - 1);
  15929. update(lastLine, lastLine.text, lastSpans);
  15930. if (nlines) { doc.remove(from.line, nlines); }
  15931. if (added.length) { doc.insert(from.line, added); }
  15932. } else if (firstLine == lastLine) {
  15933. if (text.length == 1) {
  15934. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  15935. } else {
  15936. var added$1 = linesFor(1, text.length - 1);
  15937. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
  15938. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  15939. doc.insert(from.line + 1, added$1);
  15940. }
  15941. } else if (text.length == 1) {
  15942. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  15943. doc.remove(from.line + 1, nlines);
  15944. } else {
  15945. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  15946. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  15947. var added$2 = linesFor(1, text.length - 1);
  15948. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  15949. doc.insert(from.line + 1, added$2);
  15950. }
  15951. signalLater(doc, "change", doc, change);
  15952. }
  15953. // Call f for all linked documents.
  15954. function linkedDocs(doc, f, sharedHistOnly) {
  15955. function propagate(doc, skip, sharedHist) {
  15956. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  15957. var rel = doc.linked[i];
  15958. if (rel.doc == skip) { continue }
  15959. var shared = sharedHist && rel.sharedHist;
  15960. if (sharedHistOnly && !shared) { continue }
  15961. f(rel.doc, shared);
  15962. propagate(rel.doc, doc, shared);
  15963. } }
  15964. }
  15965. propagate(doc, null, true);
  15966. }
  15967. // Attach a document to an editor.
  15968. function attachDoc(cm, doc) {
  15969. if (doc.cm) { throw new Error("This document is already in use.") }
  15970. cm.doc = doc;
  15971. doc.cm = cm;
  15972. estimateLineHeights(cm);
  15973. loadMode(cm);
  15974. setDirectionClass(cm);
  15975. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  15976. cm.options.mode = doc.modeOption;
  15977. regChange(cm);
  15978. }
  15979. function setDirectionClass(cm) {
  15980. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  15981. }
  15982. function directionChanged(cm) {
  15983. runInOp(cm, function () {
  15984. setDirectionClass(cm);
  15985. regChange(cm);
  15986. });
  15987. }
  15988. function History(startGen) {
  15989. // Arrays of change events and selections. Doing something adds an
  15990. // event to done and clears undo. Undoing moves events from done
  15991. // to undone, redoing moves them in the other direction.
  15992. this.done = []; this.undone = [];
  15993. this.undoDepth = Infinity;
  15994. // Used to track when changes can be merged into a single undo
  15995. // event
  15996. this.lastModTime = this.lastSelTime = 0;
  15997. this.lastOp = this.lastSelOp = null;
  15998. this.lastOrigin = this.lastSelOrigin = null;
  15999. // Used by the isClean() method
  16000. this.generation = this.maxGeneration = startGen || 1;
  16001. }
  16002. // Create a history change event from an updateDoc-style change
  16003. // object.
  16004. function historyChangeFromChange(doc, change) {
  16005. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  16006. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  16007. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  16008. return histChange
  16009. }
  16010. // Pop all selection events off the end of a history array. Stop at
  16011. // a change event.
  16012. function clearSelectionEvents(array) {
  16013. while (array.length) {
  16014. var last = lst(array);
  16015. if (last.ranges) { array.pop(); }
  16016. else { break }
  16017. }
  16018. }
  16019. // Find the top change event in the history. Pop off selection
  16020. // events that are in the way.
  16021. function lastChangeEvent(hist, force) {
  16022. if (force) {
  16023. clearSelectionEvents(hist.done);
  16024. return lst(hist.done)
  16025. } else if (hist.done.length && !lst(hist.done).ranges) {
  16026. return lst(hist.done)
  16027. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  16028. hist.done.pop();
  16029. return lst(hist.done)
  16030. }
  16031. }
  16032. // Register a change in the history. Merges changes that are within
  16033. // a single operation, or are close together with an origin that
  16034. // allows merging (starting with "+") into a single event.
  16035. function addChangeToHistory(doc, change, selAfter, opId) {
  16036. var hist = doc.history;
  16037. hist.undone.length = 0;
  16038. var time = +new Date, cur;
  16039. var last;
  16040. if ((hist.lastOp == opId ||
  16041. hist.lastOrigin == change.origin && change.origin &&
  16042. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  16043. change.origin.charAt(0) == "*")) &&
  16044. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  16045. // Merge this change into the last event
  16046. last = lst(cur.changes);
  16047. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  16048. // Optimized case for simple insertion -- don't want to add
  16049. // new changesets for every character typed
  16050. last.to = changeEnd(change);
  16051. } else {
  16052. // Add new sub-event
  16053. cur.changes.push(historyChangeFromChange(doc, change));
  16054. }
  16055. } else {
  16056. // Can not be merged, start a new event.
  16057. var before = lst(hist.done);
  16058. if (!before || !before.ranges)
  16059. { pushSelectionToHistory(doc.sel, hist.done); }
  16060. cur = {changes: [historyChangeFromChange(doc, change)],
  16061. generation: hist.generation};
  16062. hist.done.push(cur);
  16063. while (hist.done.length > hist.undoDepth) {
  16064. hist.done.shift();
  16065. if (!hist.done[0].ranges) { hist.done.shift(); }
  16066. }
  16067. }
  16068. hist.done.push(selAfter);
  16069. hist.generation = ++hist.maxGeneration;
  16070. hist.lastModTime = hist.lastSelTime = time;
  16071. hist.lastOp = hist.lastSelOp = opId;
  16072. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  16073. if (!last) { signal(doc, "historyAdded"); }
  16074. }
  16075. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  16076. var ch = origin.charAt(0);
  16077. return ch == "*" ||
  16078. ch == "+" &&
  16079. prev.ranges.length == sel.ranges.length &&
  16080. prev.somethingSelected() == sel.somethingSelected() &&
  16081. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  16082. }
  16083. // Called whenever the selection changes, sets the new selection as
  16084. // the pending selection in the history, and pushes the old pending
  16085. // selection into the 'done' array when it was significantly
  16086. // different (in number of selected ranges, emptiness, or time).
  16087. function addSelectionToHistory(doc, sel, opId, options) {
  16088. var hist = doc.history, origin = options && options.origin;
  16089. // A new event is started when the previous origin does not match
  16090. // the current, or the origins don't allow matching. Origins
  16091. // starting with * are always merged, those starting with + are
  16092. // merged when similar and close together in time.
  16093. if (opId == hist.lastSelOp ||
  16094. (origin && hist.lastSelOrigin == origin &&
  16095. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  16096. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  16097. { hist.done[hist.done.length - 1] = sel; }
  16098. else
  16099. { pushSelectionToHistory(sel, hist.done); }
  16100. hist.lastSelTime = +new Date;
  16101. hist.lastSelOrigin = origin;
  16102. hist.lastSelOp = opId;
  16103. if (options && options.clearRedo !== false)
  16104. { clearSelectionEvents(hist.undone); }
  16105. }
  16106. function pushSelectionToHistory(sel, dest) {
  16107. var top = lst(dest);
  16108. if (!(top && top.ranges && top.equals(sel)))
  16109. { dest.push(sel); }
  16110. }
  16111. // Used to store marked span information in the history.
  16112. function attachLocalSpans(doc, change, from, to) {
  16113. var existing = change["spans_" + doc.id], n = 0;
  16114. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  16115. if (line.markedSpans)
  16116. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  16117. ++n;
  16118. });
  16119. }
  16120. // When un/re-doing restores text containing marked spans, those
  16121. // that have been explicitly cleared should not be restored.
  16122. function removeClearedSpans(spans) {
  16123. if (!spans) { return null }
  16124. var out;
  16125. for (var i = 0; i < spans.length; ++i) {
  16126. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  16127. else if (out) { out.push(spans[i]); }
  16128. }
  16129. return !out ? spans : out.length ? out : null
  16130. }
  16131. // Retrieve and filter the old marked spans stored in a change event.
  16132. function getOldSpans(doc, change) {
  16133. var found = change["spans_" + doc.id];
  16134. if (!found) { return null }
  16135. var nw = [];
  16136. for (var i = 0; i < change.text.length; ++i)
  16137. { nw.push(removeClearedSpans(found[i])); }
  16138. return nw
  16139. }
  16140. // Used for un/re-doing changes from the history. Combines the
  16141. // result of computing the existing spans with the set of spans that
  16142. // existed in the history (so that deleting around a span and then
  16143. // undoing brings back the span).
  16144. function mergeOldSpans(doc, change) {
  16145. var old = getOldSpans(doc, change);
  16146. var stretched = stretchSpansOverChange(doc, change);
  16147. if (!old) { return stretched }
  16148. if (!stretched) { return old }
  16149. for (var i = 0; i < old.length; ++i) {
  16150. var oldCur = old[i], stretchCur = stretched[i];
  16151. if (oldCur && stretchCur) {
  16152. spans: for (var j = 0; j < stretchCur.length; ++j) {
  16153. var span = stretchCur[j];
  16154. for (var k = 0; k < oldCur.length; ++k)
  16155. { if (oldCur[k].marker == span.marker) { continue spans } }
  16156. oldCur.push(span);
  16157. }
  16158. } else if (stretchCur) {
  16159. old[i] = stretchCur;
  16160. }
  16161. }
  16162. return old
  16163. }
  16164. // Used both to provide a JSON-safe object in .getHistory, and, when
  16165. // detaching a document, to split the history in two
  16166. function copyHistoryArray(events, newGroup, instantiateSel) {
  16167. var copy = [];
  16168. for (var i = 0; i < events.length; ++i) {
  16169. var event = events[i];
  16170. if (event.ranges) {
  16171. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  16172. continue
  16173. }
  16174. var changes = event.changes, newChanges = [];
  16175. copy.push({changes: newChanges});
  16176. for (var j = 0; j < changes.length; ++j) {
  16177. var change = changes[j], m = (void 0);
  16178. newChanges.push({from: change.from, to: change.to, text: change.text});
  16179. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  16180. if (indexOf(newGroup, Number(m[1])) > -1) {
  16181. lst(newChanges)[prop] = change[prop];
  16182. delete change[prop];
  16183. }
  16184. } } }
  16185. }
  16186. }
  16187. return copy
  16188. }
  16189. // The 'scroll' parameter given to many of these indicated whether
  16190. // the new cursor position should be scrolled into view after
  16191. // modifying the selection.
  16192. // If shift is held or the extend flag is set, extends a range to
  16193. // include a given position (and optionally a second position).
  16194. // Otherwise, simply returns the range between the given positions.
  16195. // Used for cursor motion and such.
  16196. function extendRange(range, head, other, extend) {
  16197. if (extend) {
  16198. var anchor = range.anchor;
  16199. if (other) {
  16200. var posBefore = cmp(head, anchor) < 0;
  16201. if (posBefore != (cmp(other, anchor) < 0)) {
  16202. anchor = head;
  16203. head = other;
  16204. } else if (posBefore != (cmp(head, other) < 0)) {
  16205. head = other;
  16206. }
  16207. }
  16208. return new Range(anchor, head)
  16209. } else {
  16210. return new Range(other || head, head)
  16211. }
  16212. }
  16213. // Extend the primary selection range, discard the rest.
  16214. function extendSelection(doc, head, other, options, extend) {
  16215. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  16216. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  16217. }
  16218. // Extend all selections (pos is an array of selections with length
  16219. // equal the number of selections)
  16220. function extendSelections(doc, heads, options) {
  16221. var out = [];
  16222. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  16223. for (var i = 0; i < doc.sel.ranges.length; i++)
  16224. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  16225. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  16226. setSelection(doc, newSel, options);
  16227. }
  16228. // Updates a single range in the selection.
  16229. function replaceOneSelection(doc, i, range, options) {
  16230. var ranges = doc.sel.ranges.slice(0);
  16231. ranges[i] = range;
  16232. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  16233. }
  16234. // Reset the selection to a single range.
  16235. function setSimpleSelection(doc, anchor, head, options) {
  16236. setSelection(doc, simpleSelection(anchor, head), options);
  16237. }
  16238. // Give beforeSelectionChange handlers a change to influence a
  16239. // selection update.
  16240. function filterSelectionChange(doc, sel, options) {
  16241. var obj = {
  16242. ranges: sel.ranges,
  16243. update: function(ranges) {
  16244. var this$1 = this;
  16245. this.ranges = [];
  16246. for (var i = 0; i < ranges.length; i++)
  16247. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  16248. clipPos(doc, ranges[i].head)); }
  16249. },
  16250. origin: options && options.origin
  16251. };
  16252. signal(doc, "beforeSelectionChange", doc, obj);
  16253. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  16254. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  16255. else { return sel }
  16256. }
  16257. function setSelectionReplaceHistory(doc, sel, options) {
  16258. var done = doc.history.done, last = lst(done);
  16259. if (last && last.ranges) {
  16260. done[done.length - 1] = sel;
  16261. setSelectionNoUndo(doc, sel, options);
  16262. } else {
  16263. setSelection(doc, sel, options);
  16264. }
  16265. }
  16266. // Set a new selection.
  16267. function setSelection(doc, sel, options) {
  16268. setSelectionNoUndo(doc, sel, options);
  16269. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  16270. }
  16271. function setSelectionNoUndo(doc, sel, options) {
  16272. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  16273. { sel = filterSelectionChange(doc, sel, options); }
  16274. var bias = options && options.bias ||
  16275. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  16276. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  16277. if (!(options && options.scroll === false) && doc.cm)
  16278. { ensureCursorVisible(doc.cm); }
  16279. }
  16280. function setSelectionInner(doc, sel) {
  16281. if (sel.equals(doc.sel)) { return }
  16282. doc.sel = sel;
  16283. if (doc.cm) {
  16284. doc.cm.curOp.updateInput = 1;
  16285. doc.cm.curOp.selectionChanged = true;
  16286. signalCursorActivity(doc.cm);
  16287. }
  16288. signalLater(doc, "cursorActivity", doc);
  16289. }
  16290. // Verify that the selection does not partially select any atomic
  16291. // marked ranges.
  16292. function reCheckSelection(doc) {
  16293. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  16294. }
  16295. // Return a selection that does not partially select any atomic
  16296. // ranges.
  16297. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  16298. var out;
  16299. for (var i = 0; i < sel.ranges.length; i++) {
  16300. var range = sel.ranges[i];
  16301. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  16302. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  16303. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  16304. if (out || newAnchor != range.anchor || newHead != range.head) {
  16305. if (!out) { out = sel.ranges.slice(0, i); }
  16306. out[i] = new Range(newAnchor, newHead);
  16307. }
  16308. }
  16309. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  16310. }
  16311. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  16312. var line = getLine(doc, pos.line);
  16313. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  16314. var sp = line.markedSpans[i], m = sp.marker;
  16315. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  16316. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  16317. // is with selectLeft/Right
  16318. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  16319. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  16320. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  16321. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  16322. if (mayClear) {
  16323. signal(m, "beforeCursorEnter");
  16324. if (m.explicitlyCleared) {
  16325. if (!line.markedSpans) { break }
  16326. else {--i; continue}
  16327. }
  16328. }
  16329. if (!m.atomic) { continue }
  16330. if (oldPos) {
  16331. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  16332. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  16333. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  16334. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  16335. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  16336. }
  16337. var far = m.find(dir < 0 ? -1 : 1);
  16338. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  16339. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  16340. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  16341. }
  16342. } }
  16343. return pos
  16344. }
  16345. // Ensure a given position is not inside an atomic range.
  16346. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  16347. var dir = bias || 1;
  16348. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  16349. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  16350. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  16351. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  16352. if (!found) {
  16353. doc.cantEdit = true;
  16354. return Pos(doc.first, 0)
  16355. }
  16356. return found
  16357. }
  16358. function movePos(doc, pos, dir, line) {
  16359. if (dir < 0 && pos.ch == 0) {
  16360. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  16361. else { return null }
  16362. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  16363. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  16364. else { return null }
  16365. } else {
  16366. return new Pos(pos.line, pos.ch + dir)
  16367. }
  16368. }
  16369. function selectAll(cm) {
  16370. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  16371. }
  16372. // UPDATING
  16373. // Allow "beforeChange" event handlers to influence a change
  16374. function filterChange(doc, change, update) {
  16375. var obj = {
  16376. canceled: false,
  16377. from: change.from,
  16378. to: change.to,
  16379. text: change.text,
  16380. origin: change.origin,
  16381. cancel: function () { return obj.canceled = true; }
  16382. };
  16383. if (update) { obj.update = function (from, to, text, origin) {
  16384. if (from) { obj.from = clipPos(doc, from); }
  16385. if (to) { obj.to = clipPos(doc, to); }
  16386. if (text) { obj.text = text; }
  16387. if (origin !== undefined) { obj.origin = origin; }
  16388. }; }
  16389. signal(doc, "beforeChange", doc, obj);
  16390. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  16391. if (obj.canceled) {
  16392. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  16393. return null
  16394. }
  16395. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  16396. }
  16397. // Apply a change to a document, and add it to the document's
  16398. // history, and propagating it to all linked documents.
  16399. function makeChange(doc, change, ignoreReadOnly) {
  16400. if (doc.cm) {
  16401. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  16402. if (doc.cm.state.suppressEdits) { return }
  16403. }
  16404. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  16405. change = filterChange(doc, change, true);
  16406. if (!change) { return }
  16407. }
  16408. // Possibly split or suppress the update based on the presence
  16409. // of read-only spans in its range.
  16410. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  16411. if (split) {
  16412. for (var i = split.length - 1; i >= 0; --i)
  16413. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  16414. } else {
  16415. makeChangeInner(doc, change);
  16416. }
  16417. }
  16418. function makeChangeInner(doc, change) {
  16419. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  16420. var selAfter = computeSelAfterChange(doc, change);
  16421. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  16422. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  16423. var rebased = [];
  16424. linkedDocs(doc, function (doc, sharedHist) {
  16425. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  16426. rebaseHist(doc.history, change);
  16427. rebased.push(doc.history);
  16428. }
  16429. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  16430. });
  16431. }
  16432. // Revert a change stored in a document's history.
  16433. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  16434. var suppress = doc.cm && doc.cm.state.suppressEdits;
  16435. if (suppress && !allowSelectionOnly) { return }
  16436. var hist = doc.history, event, selAfter = doc.sel;
  16437. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  16438. // Verify that there is a useable event (so that ctrl-z won't
  16439. // needlessly clear selection events)
  16440. var i = 0;
  16441. for (; i < source.length; i++) {
  16442. event = source[i];
  16443. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  16444. { break }
  16445. }
  16446. if (i == source.length) { return }
  16447. hist.lastOrigin = hist.lastSelOrigin = null;
  16448. for (;;) {
  16449. event = source.pop();
  16450. if (event.ranges) {
  16451. pushSelectionToHistory(event, dest);
  16452. if (allowSelectionOnly && !event.equals(doc.sel)) {
  16453. setSelection(doc, event, {clearRedo: false});
  16454. return
  16455. }
  16456. selAfter = event;
  16457. } else if (suppress) {
  16458. source.push(event);
  16459. return
  16460. } else { break }
  16461. }
  16462. // Build up a reverse change object to add to the opposite history
  16463. // stack (redo when undoing, and vice versa).
  16464. var antiChanges = [];
  16465. pushSelectionToHistory(selAfter, dest);
  16466. dest.push({changes: antiChanges, generation: hist.generation});
  16467. hist.generation = event.generation || ++hist.maxGeneration;
  16468. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  16469. var loop = function ( i ) {
  16470. var change = event.changes[i];
  16471. change.origin = type;
  16472. if (filter && !filterChange(doc, change, false)) {
  16473. source.length = 0;
  16474. return {}
  16475. }
  16476. antiChanges.push(historyChangeFromChange(doc, change));
  16477. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  16478. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  16479. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  16480. var rebased = [];
  16481. // Propagate to the linked documents
  16482. linkedDocs(doc, function (doc, sharedHist) {
  16483. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  16484. rebaseHist(doc.history, change);
  16485. rebased.push(doc.history);
  16486. }
  16487. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  16488. });
  16489. };
  16490. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  16491. var returned = loop( i$1 );
  16492. if ( returned ) return returned.v;
  16493. }
  16494. }
  16495. // Sub-views need their line numbers shifted when text is added
  16496. // above or below them in the parent document.
  16497. function shiftDoc(doc, distance) {
  16498. if (distance == 0) { return }
  16499. doc.first += distance;
  16500. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  16501. Pos(range.anchor.line + distance, range.anchor.ch),
  16502. Pos(range.head.line + distance, range.head.ch)
  16503. ); }), doc.sel.primIndex);
  16504. if (doc.cm) {
  16505. regChange(doc.cm, doc.first, doc.first - distance, distance);
  16506. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  16507. { regLineChange(doc.cm, l, "gutter"); }
  16508. }
  16509. }
  16510. // More lower-level change function, handling only a single document
  16511. // (not linked ones).
  16512. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  16513. if (doc.cm && !doc.cm.curOp)
  16514. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  16515. if (change.to.line < doc.first) {
  16516. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  16517. return
  16518. }
  16519. if (change.from.line > doc.lastLine()) { return }
  16520. // Clip the change to the size of this doc
  16521. if (change.from.line < doc.first) {
  16522. var shift = change.text.length - 1 - (doc.first - change.from.line);
  16523. shiftDoc(doc, shift);
  16524. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  16525. text: [lst(change.text)], origin: change.origin};
  16526. }
  16527. var last = doc.lastLine();
  16528. if (change.to.line > last) {
  16529. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  16530. text: [change.text[0]], origin: change.origin};
  16531. }
  16532. change.removed = getBetween(doc, change.from, change.to);
  16533. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  16534. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  16535. else { updateDoc(doc, change, spans); }
  16536. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  16537. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  16538. { doc.cantEdit = false; }
  16539. }
  16540. // Handle the interaction of a change to a document with the editor
  16541. // that this document is part of.
  16542. function makeChangeSingleDocInEditor(cm, change, spans) {
  16543. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  16544. var recomputeMaxLength = false, checkWidthStart = from.line;
  16545. if (!cm.options.lineWrapping) {
  16546. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  16547. doc.iter(checkWidthStart, to.line + 1, function (line) {
  16548. if (line == display.maxLine) {
  16549. recomputeMaxLength = true;
  16550. return true
  16551. }
  16552. });
  16553. }
  16554. if (doc.sel.contains(change.from, change.to) > -1)
  16555. { signalCursorActivity(cm); }
  16556. updateDoc(doc, change, spans, estimateHeight(cm));
  16557. if (!cm.options.lineWrapping) {
  16558. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  16559. var len = lineLength(line);
  16560. if (len > display.maxLineLength) {
  16561. display.maxLine = line;
  16562. display.maxLineLength = len;
  16563. display.maxLineChanged = true;
  16564. recomputeMaxLength = false;
  16565. }
  16566. });
  16567. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  16568. }
  16569. retreatFrontier(doc, from.line);
  16570. startWorker(cm, 400);
  16571. var lendiff = change.text.length - (to.line - from.line) - 1;
  16572. // Remember that these lines changed, for updating the display
  16573. if (change.full)
  16574. { regChange(cm); }
  16575. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  16576. { regLineChange(cm, from.line, "text"); }
  16577. else
  16578. { regChange(cm, from.line, to.line + 1, lendiff); }
  16579. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  16580. if (changeHandler || changesHandler) {
  16581. var obj = {
  16582. from: from, to: to,
  16583. text: change.text,
  16584. removed: change.removed,
  16585. origin: change.origin
  16586. };
  16587. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  16588. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  16589. }
  16590. cm.display.selForContextMenu = null;
  16591. }
  16592. function replaceRange(doc, code, from, to, origin) {
  16593. var assign;
  16594. if (!to) { to = from; }
  16595. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  16596. if (typeof code == "string") { code = doc.splitLines(code); }
  16597. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  16598. }
  16599. // Rebasing/resetting history to deal with externally-sourced changes
  16600. function rebaseHistSelSingle(pos, from, to, diff) {
  16601. if (to < pos.line) {
  16602. pos.line += diff;
  16603. } else if (from < pos.line) {
  16604. pos.line = from;
  16605. pos.ch = 0;
  16606. }
  16607. }
  16608. // Tries to rebase an array of history events given a change in the
  16609. // document. If the change touches the same lines as the event, the
  16610. // event, and everything 'behind' it, is discarded. If the change is
  16611. // before the event, the event's positions are updated. Uses a
  16612. // copy-on-write scheme for the positions, to avoid having to
  16613. // reallocate them all on every rebase, but also avoid problems with
  16614. // shared position objects being unsafely updated.
  16615. function rebaseHistArray(array, from, to, diff) {
  16616. for (var i = 0; i < array.length; ++i) {
  16617. var sub = array[i], ok = true;
  16618. if (sub.ranges) {
  16619. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  16620. for (var j = 0; j < sub.ranges.length; j++) {
  16621. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  16622. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  16623. }
  16624. continue
  16625. }
  16626. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  16627. var cur = sub.changes[j$1];
  16628. if (to < cur.from.line) {
  16629. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  16630. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  16631. } else if (from <= cur.to.line) {
  16632. ok = false;
  16633. break
  16634. }
  16635. }
  16636. if (!ok) {
  16637. array.splice(0, i + 1);
  16638. i = 0;
  16639. }
  16640. }
  16641. }
  16642. function rebaseHist(hist, change) {
  16643. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  16644. rebaseHistArray(hist.done, from, to, diff);
  16645. rebaseHistArray(hist.undone, from, to, diff);
  16646. }
  16647. // Utility for applying a change to a line by handle or number,
  16648. // returning the number and optionally registering the line as
  16649. // changed.
  16650. function changeLine(doc, handle, changeType, op) {
  16651. var no = handle, line = handle;
  16652. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  16653. else { no = lineNo(handle); }
  16654. if (no == null) { return null }
  16655. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  16656. return line
  16657. }
  16658. // The document is represented as a BTree consisting of leaves, with
  16659. // chunk of lines in them, and branches, with up to ten leaves or
  16660. // other branch nodes below them. The top node is always a branch
  16661. // node, and is the document object itself (meaning it has
  16662. // additional methods and properties).
  16663. //
  16664. // All nodes have parent links. The tree is used both to go from
  16665. // line numbers to line objects, and to go from objects to numbers.
  16666. // It also indexes by height, and is used to convert between height
  16667. // and line object, and to find the total height of the document.
  16668. //
  16669. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  16670. function LeafChunk(lines) {
  16671. var this$1 = this;
  16672. this.lines = lines;
  16673. this.parent = null;
  16674. var height = 0;
  16675. for (var i = 0; i < lines.length; ++i) {
  16676. lines[i].parent = this$1;
  16677. height += lines[i].height;
  16678. }
  16679. this.height = height;
  16680. }
  16681. LeafChunk.prototype = {
  16682. chunkSize: function() { return this.lines.length },
  16683. // Remove the n lines at offset 'at'.
  16684. removeInner: function(at, n) {
  16685. var this$1 = this;
  16686. for (var i = at, e = at + n; i < e; ++i) {
  16687. var line = this$1.lines[i];
  16688. this$1.height -= line.height;
  16689. cleanUpLine(line);
  16690. signalLater(line, "delete");
  16691. }
  16692. this.lines.splice(at, n);
  16693. },
  16694. // Helper used to collapse a small branch into a single leaf.
  16695. collapse: function(lines) {
  16696. lines.push.apply(lines, this.lines);
  16697. },
  16698. // Insert the given array of lines at offset 'at', count them as
  16699. // having the given height.
  16700. insertInner: function(at, lines, height) {
  16701. var this$1 = this;
  16702. this.height += height;
  16703. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  16704. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
  16705. },
  16706. // Used to iterate over a part of the tree.
  16707. iterN: function(at, n, op) {
  16708. var this$1 = this;
  16709. for (var e = at + n; at < e; ++at)
  16710. { if (op(this$1.lines[at])) { return true } }
  16711. }
  16712. };
  16713. function BranchChunk(children) {
  16714. var this$1 = this;
  16715. this.children = children;
  16716. var size = 0, height = 0;
  16717. for (var i = 0; i < children.length; ++i) {
  16718. var ch = children[i];
  16719. size += ch.chunkSize(); height += ch.height;
  16720. ch.parent = this$1;
  16721. }
  16722. this.size = size;
  16723. this.height = height;
  16724. this.parent = null;
  16725. }
  16726. BranchChunk.prototype = {
  16727. chunkSize: function() { return this.size },
  16728. removeInner: function(at, n) {
  16729. var this$1 = this;
  16730. this.size -= n;
  16731. for (var i = 0; i < this.children.length; ++i) {
  16732. var child = this$1.children[i], sz = child.chunkSize();
  16733. if (at < sz) {
  16734. var rm = Math.min(n, sz - at), oldHeight = child.height;
  16735. child.removeInner(at, rm);
  16736. this$1.height -= oldHeight - child.height;
  16737. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
  16738. if ((n -= rm) == 0) { break }
  16739. at = 0;
  16740. } else { at -= sz; }
  16741. }
  16742. // If the result is smaller than 25 lines, ensure that it is a
  16743. // single leaf node.
  16744. if (this.size - n < 25 &&
  16745. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  16746. var lines = [];
  16747. this.collapse(lines);
  16748. this.children = [new LeafChunk(lines)];
  16749. this.children[0].parent = this;
  16750. }
  16751. },
  16752. collapse: function(lines) {
  16753. var this$1 = this;
  16754. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
  16755. },
  16756. insertInner: function(at, lines, height) {
  16757. var this$1 = this;
  16758. this.size += lines.length;
  16759. this.height += height;
  16760. for (var i = 0; i < this.children.length; ++i) {
  16761. var child = this$1.children[i], sz = child.chunkSize();
  16762. if (at <= sz) {
  16763. child.insertInner(at, lines, height);
  16764. if (child.lines && child.lines.length > 50) {
  16765. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  16766. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  16767. var remaining = child.lines.length % 25 + 25;
  16768. for (var pos = remaining; pos < child.lines.length;) {
  16769. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  16770. child.height -= leaf.height;
  16771. this$1.children.splice(++i, 0, leaf);
  16772. leaf.parent = this$1;
  16773. }
  16774. child.lines = child.lines.slice(0, remaining);
  16775. this$1.maybeSpill();
  16776. }
  16777. break
  16778. }
  16779. at -= sz;
  16780. }
  16781. },
  16782. // When a node has grown, check whether it should be split.
  16783. maybeSpill: function() {
  16784. if (this.children.length <= 10) { return }
  16785. var me = this;
  16786. do {
  16787. var spilled = me.children.splice(me.children.length - 5, 5);
  16788. var sibling = new BranchChunk(spilled);
  16789. if (!me.parent) { // Become the parent node
  16790. var copy = new BranchChunk(me.children);
  16791. copy.parent = me;
  16792. me.children = [copy, sibling];
  16793. me = copy;
  16794. } else {
  16795. me.size -= sibling.size;
  16796. me.height -= sibling.height;
  16797. var myIndex = indexOf(me.parent.children, me);
  16798. me.parent.children.splice(myIndex + 1, 0, sibling);
  16799. }
  16800. sibling.parent = me.parent;
  16801. } while (me.children.length > 10)
  16802. me.parent.maybeSpill();
  16803. },
  16804. iterN: function(at, n, op) {
  16805. var this$1 = this;
  16806. for (var i = 0; i < this.children.length; ++i) {
  16807. var child = this$1.children[i], sz = child.chunkSize();
  16808. if (at < sz) {
  16809. var used = Math.min(n, sz - at);
  16810. if (child.iterN(at, used, op)) { return true }
  16811. if ((n -= used) == 0) { break }
  16812. at = 0;
  16813. } else { at -= sz; }
  16814. }
  16815. }
  16816. };
  16817. // Line widgets are block elements displayed above or below a line.
  16818. var LineWidget = function(doc, node, options) {
  16819. var this$1 = this;
  16820. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  16821. { this$1[opt] = options[opt]; } } }
  16822. this.doc = doc;
  16823. this.node = node;
  16824. };
  16825. LineWidget.prototype.clear = function () {
  16826. var this$1 = this;
  16827. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  16828. if (no == null || !ws) { return }
  16829. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
  16830. if (!ws.length) { line.widgets = null; }
  16831. var height = widgetHeight(this);
  16832. updateLineHeight(line, Math.max(0, line.height - height));
  16833. if (cm) {
  16834. runInOp(cm, function () {
  16835. adjustScrollWhenAboveVisible(cm, line, -height);
  16836. regLineChange(cm, no, "widget");
  16837. });
  16838. signalLater(cm, "lineWidgetCleared", cm, this, no);
  16839. }
  16840. };
  16841. LineWidget.prototype.changed = function () {
  16842. var this$1 = this;
  16843. var oldH = this.height, cm = this.doc.cm, line = this.line;
  16844. this.height = null;
  16845. var diff = widgetHeight(this) - oldH;
  16846. if (!diff) { return }
  16847. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  16848. if (cm) {
  16849. runInOp(cm, function () {
  16850. cm.curOp.forceUpdate = true;
  16851. adjustScrollWhenAboveVisible(cm, line, diff);
  16852. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  16853. });
  16854. }
  16855. };
  16856. eventMixin(LineWidget);
  16857. function adjustScrollWhenAboveVisible(cm, line, diff) {
  16858. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  16859. { addToScrollTop(cm, diff); }
  16860. }
  16861. function addLineWidget(doc, handle, node, options) {
  16862. var widget = new LineWidget(doc, node, options);
  16863. var cm = doc.cm;
  16864. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  16865. changeLine(doc, handle, "widget", function (line) {
  16866. var widgets = line.widgets || (line.widgets = []);
  16867. if (widget.insertAt == null) { widgets.push(widget); }
  16868. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  16869. widget.line = line;
  16870. if (cm && !lineIsHidden(doc, line)) {
  16871. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  16872. updateLineHeight(line, line.height + widgetHeight(widget));
  16873. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  16874. cm.curOp.forceUpdate = true;
  16875. }
  16876. return true
  16877. });
  16878. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  16879. return widget
  16880. }
  16881. // TEXTMARKERS
  16882. // Created with markText and setBookmark methods. A TextMarker is a
  16883. // handle that can be used to clear or find a marked position in the
  16884. // document. Line objects hold arrays (markedSpans) containing
  16885. // {from, to, marker} object pointing to such marker objects, and
  16886. // indicating that such a marker is present on that line. Multiple
  16887. // lines may point to the same marker when it spans across lines.
  16888. // The spans will have null for their from/to properties when the
  16889. // marker continues beyond the start/end of the line. Markers have
  16890. // links back to the lines they currently touch.
  16891. // Collapsed markers have unique ids, in order to be able to order
  16892. // them, which is needed for uniquely determining an outer marker
  16893. // when they overlap (they may nest, but not partially overlap).
  16894. var nextMarkerId = 0;
  16895. var TextMarker = function(doc, type) {
  16896. this.lines = [];
  16897. this.type = type;
  16898. this.doc = doc;
  16899. this.id = ++nextMarkerId;
  16900. };
  16901. // Clear the marker.
  16902. TextMarker.prototype.clear = function () {
  16903. var this$1 = this;
  16904. if (this.explicitlyCleared) { return }
  16905. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  16906. if (withOp) { startOperation(cm); }
  16907. if (hasHandler(this, "clear")) {
  16908. var found = this.find();
  16909. if (found) { signalLater(this, "clear", found.from, found.to); }
  16910. }
  16911. var min = null, max = null;
  16912. for (var i = 0; i < this.lines.length; ++i) {
  16913. var line = this$1.lines[i];
  16914. var span = getMarkedSpanFor(line.markedSpans, this$1);
  16915. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  16916. else if (cm) {
  16917. if (span.to != null) { max = lineNo(line); }
  16918. if (span.from != null) { min = lineNo(line); }
  16919. }
  16920. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  16921. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  16922. { updateLineHeight(line, textHeight(cm.display)); }
  16923. }
  16924. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  16925. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
  16926. if (len > cm.display.maxLineLength) {
  16927. cm.display.maxLine = visual;
  16928. cm.display.maxLineLength = len;
  16929. cm.display.maxLineChanged = true;
  16930. }
  16931. } }
  16932. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  16933. this.lines.length = 0;
  16934. this.explicitlyCleared = true;
  16935. if (this.atomic && this.doc.cantEdit) {
  16936. this.doc.cantEdit = false;
  16937. if (cm) { reCheckSelection(cm.doc); }
  16938. }
  16939. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  16940. if (withOp) { endOperation(cm); }
  16941. if (this.parent) { this.parent.clear(); }
  16942. };
  16943. // Find the position of the marker in the document. Returns a {from,
  16944. // to} object by default. Side can be passed to get a specific side
  16945. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  16946. // Pos objects returned contain a line object, rather than a line
  16947. // number (used to prevent looking up the same line twice).
  16948. TextMarker.prototype.find = function (side, lineObj) {
  16949. var this$1 = this;
  16950. if (side == null && this.type == "bookmark") { side = 1; }
  16951. var from, to;
  16952. for (var i = 0; i < this.lines.length; ++i) {
  16953. var line = this$1.lines[i];
  16954. var span = getMarkedSpanFor(line.markedSpans, this$1);
  16955. if (span.from != null) {
  16956. from = Pos(lineObj ? line : lineNo(line), span.from);
  16957. if (side == -1) { return from }
  16958. }
  16959. if (span.to != null) {
  16960. to = Pos(lineObj ? line : lineNo(line), span.to);
  16961. if (side == 1) { return to }
  16962. }
  16963. }
  16964. return from && {from: from, to: to}
  16965. };
  16966. // Signals that the marker's widget changed, and surrounding layout
  16967. // should be recomputed.
  16968. TextMarker.prototype.changed = function () {
  16969. var this$1 = this;
  16970. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  16971. if (!pos || !cm) { return }
  16972. runInOp(cm, function () {
  16973. var line = pos.line, lineN = lineNo(pos.line);
  16974. var view = findViewForLine(cm, lineN);
  16975. if (view) {
  16976. clearLineMeasurementCacheFor(view);
  16977. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  16978. }
  16979. cm.curOp.updateMaxLine = true;
  16980. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  16981. var oldHeight = widget.height;
  16982. widget.height = null;
  16983. var dHeight = widgetHeight(widget) - oldHeight;
  16984. if (dHeight)
  16985. { updateLineHeight(line, line.height + dHeight); }
  16986. }
  16987. signalLater(cm, "markerChanged", cm, this$1);
  16988. });
  16989. };
  16990. TextMarker.prototype.attachLine = function (line) {
  16991. if (!this.lines.length && this.doc.cm) {
  16992. var op = this.doc.cm.curOp;
  16993. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  16994. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  16995. }
  16996. this.lines.push(line);
  16997. };
  16998. TextMarker.prototype.detachLine = function (line) {
  16999. this.lines.splice(indexOf(this.lines, line), 1);
  17000. if (!this.lines.length && this.doc.cm) {
  17001. var op = this.doc.cm.curOp
  17002. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  17003. }
  17004. };
  17005. eventMixin(TextMarker);
  17006. // Create a marker, wire it up to the right lines, and
  17007. function markText(doc, from, to, options, type) {
  17008. // Shared markers (across linked documents) are handled separately
  17009. // (markTextShared will call out to this again, once per
  17010. // document).
  17011. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  17012. // Ensure we are in an operation.
  17013. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  17014. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  17015. if (options) { copyObj(options, marker, false); }
  17016. // Don't connect empty markers unless clearWhenEmpty is false
  17017. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  17018. { return marker }
  17019. if (marker.replacedWith) {
  17020. // Showing up as a widget implies collapsed (widget replaces text)
  17021. marker.collapsed = true;
  17022. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  17023. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  17024. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  17025. }
  17026. if (marker.collapsed) {
  17027. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  17028. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  17029. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  17030. seeCollapsedSpans();
  17031. }
  17032. if (marker.addToHistory)
  17033. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  17034. var curLine = from.line, cm = doc.cm, updateMaxLine;
  17035. doc.iter(curLine, to.line + 1, function (line) {
  17036. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  17037. { updateMaxLine = true; }
  17038. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  17039. addMarkedSpan(line, new MarkedSpan(marker,
  17040. curLine == from.line ? from.ch : null,
  17041. curLine == to.line ? to.ch : null));
  17042. ++curLine;
  17043. });
  17044. // lineIsHidden depends on the presence of the spans, so needs a second pass
  17045. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  17046. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  17047. }); }
  17048. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  17049. if (marker.readOnly) {
  17050. seeReadOnlySpans();
  17051. if (doc.history.done.length || doc.history.undone.length)
  17052. { doc.clearHistory(); }
  17053. }
  17054. if (marker.collapsed) {
  17055. marker.id = ++nextMarkerId;
  17056. marker.atomic = true;
  17057. }
  17058. if (cm) {
  17059. // Sync editor state
  17060. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  17061. if (marker.collapsed)
  17062. { regChange(cm, from.line, to.line + 1); }
  17063. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  17064. marker.attributes || marker.title)
  17065. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  17066. if (marker.atomic) { reCheckSelection(cm.doc); }
  17067. signalLater(cm, "markerAdded", cm, marker);
  17068. }
  17069. return marker
  17070. }
  17071. // SHARED TEXTMARKERS
  17072. // A shared marker spans multiple linked documents. It is
  17073. // implemented as a meta-marker-object controlling multiple normal
  17074. // markers.
  17075. var SharedTextMarker = function(markers, primary) {
  17076. var this$1 = this;
  17077. this.markers = markers;
  17078. this.primary = primary;
  17079. for (var i = 0; i < markers.length; ++i)
  17080. { markers[i].parent = this$1; }
  17081. };
  17082. SharedTextMarker.prototype.clear = function () {
  17083. var this$1 = this;
  17084. if (this.explicitlyCleared) { return }
  17085. this.explicitlyCleared = true;
  17086. for (var i = 0; i < this.markers.length; ++i)
  17087. { this$1.markers[i].clear(); }
  17088. signalLater(this, "clear");
  17089. };
  17090. SharedTextMarker.prototype.find = function (side, lineObj) {
  17091. return this.primary.find(side, lineObj)
  17092. };
  17093. eventMixin(SharedTextMarker);
  17094. function markTextShared(doc, from, to, options, type) {
  17095. options = copyObj(options);
  17096. options.shared = false;
  17097. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  17098. var widget = options.widgetNode;
  17099. linkedDocs(doc, function (doc) {
  17100. if (widget) { options.widgetNode = widget.cloneNode(true); }
  17101. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  17102. for (var i = 0; i < doc.linked.length; ++i)
  17103. { if (doc.linked[i].isParent) { return } }
  17104. primary = lst(markers);
  17105. });
  17106. return new SharedTextMarker(markers, primary)
  17107. }
  17108. function findSharedMarkers(doc) {
  17109. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  17110. }
  17111. function copySharedMarkers(doc, markers) {
  17112. for (var i = 0; i < markers.length; i++) {
  17113. var marker = markers[i], pos = marker.find();
  17114. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  17115. if (cmp(mFrom, mTo)) {
  17116. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  17117. marker.markers.push(subMark);
  17118. subMark.parent = marker;
  17119. }
  17120. }
  17121. }
  17122. function detachSharedMarkers(markers) {
  17123. var loop = function ( i ) {
  17124. var marker = markers[i], linked = [marker.primary.doc];
  17125. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  17126. for (var j = 0; j < marker.markers.length; j++) {
  17127. var subMarker = marker.markers[j];
  17128. if (indexOf(linked, subMarker.doc) == -1) {
  17129. subMarker.parent = null;
  17130. marker.markers.splice(j--, 1);
  17131. }
  17132. }
  17133. };
  17134. for (var i = 0; i < markers.length; i++) loop( i );
  17135. }
  17136. var nextDocId = 0;
  17137. var Doc = function(text, mode, firstLine, lineSep, direction) {
  17138. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  17139. if (firstLine == null) { firstLine = 0; }
  17140. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  17141. this.first = firstLine;
  17142. this.scrollTop = this.scrollLeft = 0;
  17143. this.cantEdit = false;
  17144. this.cleanGeneration = 1;
  17145. this.modeFrontier = this.highlightFrontier = firstLine;
  17146. var start = Pos(firstLine, 0);
  17147. this.sel = simpleSelection(start);
  17148. this.history = new History(null);
  17149. this.id = ++nextDocId;
  17150. this.modeOption = mode;
  17151. this.lineSep = lineSep;
  17152. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  17153. this.extend = false;
  17154. if (typeof text == "string") { text = this.splitLines(text); }
  17155. updateDoc(this, {from: start, to: start, text: text});
  17156. setSelection(this, simpleSelection(start), sel_dontScroll);
  17157. };
  17158. Doc.prototype = createObj(BranchChunk.prototype, {
  17159. constructor: Doc,
  17160. // Iterate over the document. Supports two forms -- with only one
  17161. // argument, it calls that for each line in the document. With
  17162. // three, it iterates over the range given by the first two (with
  17163. // the second being non-inclusive).
  17164. iter: function(from, to, op) {
  17165. if (op) { this.iterN(from - this.first, to - from, op); }
  17166. else { this.iterN(this.first, this.first + this.size, from); }
  17167. },
  17168. // Non-public interface for adding and removing lines.
  17169. insert: function(at, lines) {
  17170. var height = 0;
  17171. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  17172. this.insertInner(at - this.first, lines, height);
  17173. },
  17174. remove: function(at, n) { this.removeInner(at - this.first, n); },
  17175. // From here, the methods are part of the public interface. Most
  17176. // are also available from CodeMirror (editor) instances.
  17177. getValue: function(lineSep) {
  17178. var lines = getLines(this, this.first, this.first + this.size);
  17179. if (lineSep === false) { return lines }
  17180. return lines.join(lineSep || this.lineSeparator())
  17181. },
  17182. setValue: docMethodOp(function(code) {
  17183. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  17184. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  17185. text: this.splitLines(code), origin: "setValue", full: true}, true);
  17186. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  17187. setSelection(this, simpleSelection(top), sel_dontScroll);
  17188. }),
  17189. replaceRange: function(code, from, to, origin) {
  17190. from = clipPos(this, from);
  17191. to = to ? clipPos(this, to) : from;
  17192. replaceRange(this, code, from, to, origin);
  17193. },
  17194. getRange: function(from, to, lineSep) {
  17195. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  17196. if (lineSep === false) { return lines }
  17197. return lines.join(lineSep || this.lineSeparator())
  17198. },
  17199. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  17200. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  17201. getLineNumber: function(line) {return lineNo(line)},
  17202. getLineHandleVisualStart: function(line) {
  17203. if (typeof line == "number") { line = getLine(this, line); }
  17204. return visualLine(line)
  17205. },
  17206. lineCount: function() {return this.size},
  17207. firstLine: function() {return this.first},
  17208. lastLine: function() {return this.first + this.size - 1},
  17209. clipPos: function(pos) {return clipPos(this, pos)},
  17210. getCursor: function(start) {
  17211. var range$$1 = this.sel.primary(), pos;
  17212. if (start == null || start == "head") { pos = range$$1.head; }
  17213. else if (start == "anchor") { pos = range$$1.anchor; }
  17214. else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
  17215. else { pos = range$$1.from(); }
  17216. return pos
  17217. },
  17218. listSelections: function() { return this.sel.ranges },
  17219. somethingSelected: function() {return this.sel.somethingSelected()},
  17220. setCursor: docMethodOp(function(line, ch, options) {
  17221. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  17222. }),
  17223. setSelection: docMethodOp(function(anchor, head, options) {
  17224. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  17225. }),
  17226. extendSelection: docMethodOp(function(head, other, options) {
  17227. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  17228. }),
  17229. extendSelections: docMethodOp(function(heads, options) {
  17230. extendSelections(this, clipPosArray(this, heads), options);
  17231. }),
  17232. extendSelectionsBy: docMethodOp(function(f, options) {
  17233. var heads = map(this.sel.ranges, f);
  17234. extendSelections(this, clipPosArray(this, heads), options);
  17235. }),
  17236. setSelections: docMethodOp(function(ranges, primary, options) {
  17237. var this$1 = this;
  17238. if (!ranges.length) { return }
  17239. var out = [];
  17240. for (var i = 0; i < ranges.length; i++)
  17241. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  17242. clipPos(this$1, ranges[i].head)); }
  17243. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  17244. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  17245. }),
  17246. addSelection: docMethodOp(function(anchor, head, options) {
  17247. var ranges = this.sel.ranges.slice(0);
  17248. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  17249. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  17250. }),
  17251. getSelection: function(lineSep) {
  17252. var this$1 = this;
  17253. var ranges = this.sel.ranges, lines;
  17254. for (var i = 0; i < ranges.length; i++) {
  17255. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  17256. lines = lines ? lines.concat(sel) : sel;
  17257. }
  17258. if (lineSep === false) { return lines }
  17259. else { return lines.join(lineSep || this.lineSeparator()) }
  17260. },
  17261. getSelections: function(lineSep) {
  17262. var this$1 = this;
  17263. var parts = [], ranges = this.sel.ranges;
  17264. for (var i = 0; i < ranges.length; i++) {
  17265. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  17266. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
  17267. parts[i] = sel;
  17268. }
  17269. return parts
  17270. },
  17271. replaceSelection: function(code, collapse, origin) {
  17272. var dup = [];
  17273. for (var i = 0; i < this.sel.ranges.length; i++)
  17274. { dup[i] = code; }
  17275. this.replaceSelections(dup, collapse, origin || "+input");
  17276. },
  17277. replaceSelections: docMethodOp(function(code, collapse, origin) {
  17278. var this$1 = this;
  17279. var changes = [], sel = this.sel;
  17280. for (var i = 0; i < sel.ranges.length; i++) {
  17281. var range$$1 = sel.ranges[i];
  17282. changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
  17283. }
  17284. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  17285. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  17286. { makeChange(this$1, changes[i$1]); }
  17287. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  17288. else if (this.cm) { ensureCursorVisible(this.cm); }
  17289. }),
  17290. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  17291. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  17292. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  17293. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  17294. setExtending: function(val) {this.extend = val;},
  17295. getExtending: function() {return this.extend},
  17296. historySize: function() {
  17297. var hist = this.history, done = 0, undone = 0;
  17298. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  17299. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  17300. return {undo: done, redo: undone}
  17301. },
  17302. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  17303. markClean: function() {
  17304. this.cleanGeneration = this.changeGeneration(true);
  17305. },
  17306. changeGeneration: function(forceSplit) {
  17307. if (forceSplit)
  17308. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  17309. return this.history.generation
  17310. },
  17311. isClean: function (gen) {
  17312. return this.history.generation == (gen || this.cleanGeneration)
  17313. },
  17314. getHistory: function() {
  17315. return {done: copyHistoryArray(this.history.done),
  17316. undone: copyHistoryArray(this.history.undone)}
  17317. },
  17318. setHistory: function(histData) {
  17319. var hist = this.history = new History(this.history.maxGeneration);
  17320. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  17321. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  17322. },
  17323. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  17324. return changeLine(this, line, "gutter", function (line) {
  17325. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  17326. markers[gutterID] = value;
  17327. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  17328. return true
  17329. })
  17330. }),
  17331. clearGutter: docMethodOp(function(gutterID) {
  17332. var this$1 = this;
  17333. this.iter(function (line) {
  17334. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  17335. changeLine(this$1, line, "gutter", function () {
  17336. line.gutterMarkers[gutterID] = null;
  17337. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  17338. return true
  17339. });
  17340. }
  17341. });
  17342. }),
  17343. lineInfo: function(line) {
  17344. var n;
  17345. if (typeof line == "number") {
  17346. if (!isLine(this, line)) { return null }
  17347. n = line;
  17348. line = getLine(this, line);
  17349. if (!line) { return null }
  17350. } else {
  17351. n = lineNo(line);
  17352. if (n == null) { return null }
  17353. }
  17354. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  17355. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  17356. widgets: line.widgets}
  17357. },
  17358. addLineClass: docMethodOp(function(handle, where, cls) {
  17359. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  17360. var prop = where == "text" ? "textClass"
  17361. : where == "background" ? "bgClass"
  17362. : where == "gutter" ? "gutterClass" : "wrapClass";
  17363. if (!line[prop]) { line[prop] = cls; }
  17364. else if (classTest(cls).test(line[prop])) { return false }
  17365. else { line[prop] += " " + cls; }
  17366. return true
  17367. })
  17368. }),
  17369. removeLineClass: docMethodOp(function(handle, where, cls) {
  17370. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  17371. var prop = where == "text" ? "textClass"
  17372. : where == "background" ? "bgClass"
  17373. : where == "gutter" ? "gutterClass" : "wrapClass";
  17374. var cur = line[prop];
  17375. if (!cur) { return false }
  17376. else if (cls == null) { line[prop] = null; }
  17377. else {
  17378. var found = cur.match(classTest(cls));
  17379. if (!found) { return false }
  17380. var end = found.index + found[0].length;
  17381. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  17382. }
  17383. return true
  17384. })
  17385. }),
  17386. addLineWidget: docMethodOp(function(handle, node, options) {
  17387. return addLineWidget(this, handle, node, options)
  17388. }),
  17389. removeLineWidget: function(widget) { widget.clear(); },
  17390. markText: function(from, to, options) {
  17391. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  17392. },
  17393. setBookmark: function(pos, options) {
  17394. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  17395. insertLeft: options && options.insertLeft,
  17396. clearWhenEmpty: false, shared: options && options.shared,
  17397. handleMouseEvents: options && options.handleMouseEvents};
  17398. pos = clipPos(this, pos);
  17399. return markText(this, pos, pos, realOpts, "bookmark")
  17400. },
  17401. findMarksAt: function(pos) {
  17402. pos = clipPos(this, pos);
  17403. var markers = [], spans = getLine(this, pos.line).markedSpans;
  17404. if (spans) { for (var i = 0; i < spans.length; ++i) {
  17405. var span = spans[i];
  17406. if ((span.from == null || span.from <= pos.ch) &&
  17407. (span.to == null || span.to >= pos.ch))
  17408. { markers.push(span.marker.parent || span.marker); }
  17409. } }
  17410. return markers
  17411. },
  17412. findMarks: function(from, to, filter) {
  17413. from = clipPos(this, from); to = clipPos(this, to);
  17414. var found = [], lineNo$$1 = from.line;
  17415. this.iter(from.line, to.line + 1, function (line) {
  17416. var spans = line.markedSpans;
  17417. if (spans) { for (var i = 0; i < spans.length; i++) {
  17418. var span = spans[i];
  17419. if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
  17420. span.from == null && lineNo$$1 != from.line ||
  17421. span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
  17422. (!filter || filter(span.marker)))
  17423. { found.push(span.marker.parent || span.marker); }
  17424. } }
  17425. ++lineNo$$1;
  17426. });
  17427. return found
  17428. },
  17429. getAllMarks: function() {
  17430. var markers = [];
  17431. this.iter(function (line) {
  17432. var sps = line.markedSpans;
  17433. if (sps) { for (var i = 0; i < sps.length; ++i)
  17434. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  17435. });
  17436. return markers
  17437. },
  17438. posFromIndex: function(off) {
  17439. var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
  17440. this.iter(function (line) {
  17441. var sz = line.text.length + sepSize;
  17442. if (sz > off) { ch = off; return true }
  17443. off -= sz;
  17444. ++lineNo$$1;
  17445. });
  17446. return clipPos(this, Pos(lineNo$$1, ch))
  17447. },
  17448. indexFromPos: function (coords) {
  17449. coords = clipPos(this, coords);
  17450. var index = coords.ch;
  17451. if (coords.line < this.first || coords.ch < 0) { return 0 }
  17452. var sepSize = this.lineSeparator().length;
  17453. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  17454. index += line.text.length + sepSize;
  17455. });
  17456. return index
  17457. },
  17458. copy: function(copyHistory) {
  17459. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  17460. this.modeOption, this.first, this.lineSep, this.direction);
  17461. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  17462. doc.sel = this.sel;
  17463. doc.extend = false;
  17464. if (copyHistory) {
  17465. doc.history.undoDepth = this.history.undoDepth;
  17466. doc.setHistory(this.getHistory());
  17467. }
  17468. return doc
  17469. },
  17470. linkedDoc: function(options) {
  17471. if (!options) { options = {}; }
  17472. var from = this.first, to = this.first + this.size;
  17473. if (options.from != null && options.from > from) { from = options.from; }
  17474. if (options.to != null && options.to < to) { to = options.to; }
  17475. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  17476. if (options.sharedHist) { copy.history = this.history
  17477. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  17478. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  17479. copySharedMarkers(copy, findSharedMarkers(this));
  17480. return copy
  17481. },
  17482. unlinkDoc: function(other) {
  17483. var this$1 = this;
  17484. if (other instanceof CodeMirror) { other = other.doc; }
  17485. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  17486. var link = this$1.linked[i];
  17487. if (link.doc != other) { continue }
  17488. this$1.linked.splice(i, 1);
  17489. other.unlinkDoc(this$1);
  17490. detachSharedMarkers(findSharedMarkers(this$1));
  17491. break
  17492. } }
  17493. // If the histories were shared, split them again
  17494. if (other.history == this.history) {
  17495. var splitIds = [other.id];
  17496. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  17497. other.history = new History(null);
  17498. other.history.done = copyHistoryArray(this.history.done, splitIds);
  17499. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  17500. }
  17501. },
  17502. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  17503. getMode: function() {return this.mode},
  17504. getEditor: function() {return this.cm},
  17505. splitLines: function(str) {
  17506. if (this.lineSep) { return str.split(this.lineSep) }
  17507. return splitLinesAuto(str)
  17508. },
  17509. lineSeparator: function() { return this.lineSep || "\n" },
  17510. setDirection: docMethodOp(function (dir) {
  17511. if (dir != "rtl") { dir = "ltr"; }
  17512. if (dir == this.direction) { return }
  17513. this.direction = dir;
  17514. this.iter(function (line) { return line.order = null; });
  17515. if (this.cm) { directionChanged(this.cm); }
  17516. })
  17517. });
  17518. // Public alias.
  17519. Doc.prototype.eachLine = Doc.prototype.iter;
  17520. // Kludge to work around strange IE behavior where it'll sometimes
  17521. // re-fire a series of drag-related events right after the drop (#1551)
  17522. var lastDrop = 0;
  17523. function onDrop(e) {
  17524. var cm = this;
  17525. clearDragCursor(cm);
  17526. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  17527. { return }
  17528. e_preventDefault(e);
  17529. if (ie) { lastDrop = +new Date; }
  17530. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  17531. if (!pos || cm.isReadOnly()) { return }
  17532. // Might be a file drop, in which case we simply extract the text
  17533. // and insert it.
  17534. if (files && files.length && window.FileReader && window.File) {
  17535. var n = files.length, text = Array(n), read = 0;
  17536. var loadFile = function (file, i) {
  17537. if (cm.options.allowDropFileTypes &&
  17538. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  17539. { return }
  17540. var reader = new FileReader;
  17541. reader.onload = operation(cm, function () {
  17542. var content = reader.result;
  17543. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
  17544. text[i] = content;
  17545. if (++read == n) {
  17546. pos = clipPos(cm.doc, pos);
  17547. var change = {from: pos, to: pos,
  17548. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  17549. origin: "paste"};
  17550. makeChange(cm.doc, change);
  17551. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  17552. }
  17553. });
  17554. reader.readAsText(file);
  17555. };
  17556. for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
  17557. } else { // Normal drop
  17558. // Don't do a replace if the drop happened inside of the selected text.
  17559. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  17560. cm.state.draggingText(e);
  17561. // Ensure the editor is re-focused
  17562. setTimeout(function () { return cm.display.input.focus(); }, 20);
  17563. return
  17564. }
  17565. try {
  17566. var text$1 = e.dataTransfer.getData("Text");
  17567. if (text$1) {
  17568. var selected;
  17569. if (cm.state.draggingText && !cm.state.draggingText.copy)
  17570. { selected = cm.listSelections(); }
  17571. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  17572. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  17573. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  17574. cm.replaceSelection(text$1, "around", "paste");
  17575. cm.display.input.focus();
  17576. }
  17577. }
  17578. catch(e){}
  17579. }
  17580. }
  17581. function onDragStart(cm, e) {
  17582. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  17583. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  17584. e.dataTransfer.setData("Text", cm.getSelection());
  17585. e.dataTransfer.effectAllowed = "copyMove";
  17586. // Use dummy image instead of default browsers image.
  17587. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  17588. if (e.dataTransfer.setDragImage && !safari) {
  17589. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  17590. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  17591. if (presto) {
  17592. img.width = img.height = 1;
  17593. cm.display.wrapper.appendChild(img);
  17594. // Force a relayout, or Opera won't use our image for some obscure reason
  17595. img._top = img.offsetTop;
  17596. }
  17597. e.dataTransfer.setDragImage(img, 0, 0);
  17598. if (presto) { img.parentNode.removeChild(img); }
  17599. }
  17600. }
  17601. function onDragOver(cm, e) {
  17602. var pos = posFromMouse(cm, e);
  17603. if (!pos) { return }
  17604. var frag = document.createDocumentFragment();
  17605. drawSelectionCursor(cm, pos, frag);
  17606. if (!cm.display.dragCursor) {
  17607. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  17608. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  17609. }
  17610. removeChildrenAndAdd(cm.display.dragCursor, frag);
  17611. }
  17612. function clearDragCursor(cm) {
  17613. if (cm.display.dragCursor) {
  17614. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  17615. cm.display.dragCursor = null;
  17616. }
  17617. }
  17618. // These must be handled carefully, because naively registering a
  17619. // handler for each editor will cause the editors to never be
  17620. // garbage collected.
  17621. function forEachCodeMirror(f) {
  17622. if (!document.getElementsByClassName) { return }
  17623. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  17624. for (var i = 0; i < byClass.length; i++) {
  17625. var cm = byClass[i].CodeMirror;
  17626. if (cm) { editors.push(cm); }
  17627. }
  17628. if (editors.length) { editors[0].operation(function () {
  17629. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  17630. }); }
  17631. }
  17632. var globalsRegistered = false;
  17633. function ensureGlobalHandlers() {
  17634. if (globalsRegistered) { return }
  17635. registerGlobalHandlers();
  17636. globalsRegistered = true;
  17637. }
  17638. function registerGlobalHandlers() {
  17639. // When the window resizes, we need to refresh active editors.
  17640. var resizeTimer;
  17641. on(window, "resize", function () {
  17642. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  17643. resizeTimer = null;
  17644. forEachCodeMirror(onResize);
  17645. }, 100); }
  17646. });
  17647. // When the window loses focus, we want to show the editor as blurred
  17648. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  17649. }
  17650. // Called when the window resizes
  17651. function onResize(cm) {
  17652. var d = cm.display;
  17653. // Might be a text scaling operation, clear size caches.
  17654. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  17655. d.scrollbarsClipped = false;
  17656. cm.setSize();
  17657. }
  17658. var keyNames = {
  17659. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  17660. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  17661. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  17662. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  17663. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  17664. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  17665. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  17666. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  17667. };
  17668. // Number keys
  17669. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  17670. // Alphabetic keys
  17671. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  17672. // Function keys
  17673. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  17674. var keyMap = {};
  17675. keyMap.basic = {
  17676. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  17677. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  17678. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  17679. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  17680. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  17681. "Esc": "singleSelection"
  17682. };
  17683. // Note that the save and find-related commands aren't defined by
  17684. // default. User code or addons can define them. Unknown commands
  17685. // are simply ignored.
  17686. keyMap.pcDefault = {
  17687. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  17688. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  17689. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  17690. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  17691. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  17692. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  17693. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  17694. "fallthrough": "basic"
  17695. };
  17696. // Very basic readline/emacs-style bindings, which are standard on Mac.
  17697. keyMap.emacsy = {
  17698. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  17699. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  17700. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  17701. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  17702. "Ctrl-O": "openLine"
  17703. };
  17704. keyMap.macDefault = {
  17705. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  17706. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  17707. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  17708. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  17709. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  17710. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  17711. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  17712. "fallthrough": ["basic", "emacsy"]
  17713. };
  17714. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  17715. // KEYMAP DISPATCH
  17716. function normalizeKeyName(name) {
  17717. var parts = name.split(/-(?!$)/);
  17718. name = parts[parts.length - 1];
  17719. var alt, ctrl, shift, cmd;
  17720. for (var i = 0; i < parts.length - 1; i++) {
  17721. var mod = parts[i];
  17722. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  17723. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  17724. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  17725. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  17726. else { throw new Error("Unrecognized modifier name: " + mod) }
  17727. }
  17728. if (alt) { name = "Alt-" + name; }
  17729. if (ctrl) { name = "Ctrl-" + name; }
  17730. if (cmd) { name = "Cmd-" + name; }
  17731. if (shift) { name = "Shift-" + name; }
  17732. return name
  17733. }
  17734. // This is a kludge to keep keymaps mostly working as raw objects
  17735. // (backwards compatibility) while at the same time support features
  17736. // like normalization and multi-stroke key bindings. It compiles a
  17737. // new normalized keymap, and then updates the old object to reflect
  17738. // this.
  17739. function normalizeKeyMap(keymap) {
  17740. var copy = {};
  17741. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  17742. var value = keymap[keyname];
  17743. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  17744. if (value == "...") { delete keymap[keyname]; continue }
  17745. var keys = map(keyname.split(" "), normalizeKeyName);
  17746. for (var i = 0; i < keys.length; i++) {
  17747. var val = (void 0), name = (void 0);
  17748. if (i == keys.length - 1) {
  17749. name = keys.join(" ");
  17750. val = value;
  17751. } else {
  17752. name = keys.slice(0, i + 1).join(" ");
  17753. val = "...";
  17754. }
  17755. var prev = copy[name];
  17756. if (!prev) { copy[name] = val; }
  17757. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  17758. }
  17759. delete keymap[keyname];
  17760. } }
  17761. for (var prop in copy) { keymap[prop] = copy[prop]; }
  17762. return keymap
  17763. }
  17764. function lookupKey(key, map$$1, handle, context) {
  17765. map$$1 = getKeyMap(map$$1);
  17766. var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
  17767. if (found === false) { return "nothing" }
  17768. if (found === "...") { return "multi" }
  17769. if (found != null && handle(found)) { return "handled" }
  17770. if (map$$1.fallthrough) {
  17771. if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
  17772. { return lookupKey(key, map$$1.fallthrough, handle, context) }
  17773. for (var i = 0; i < map$$1.fallthrough.length; i++) {
  17774. var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
  17775. if (result) { return result }
  17776. }
  17777. }
  17778. }
  17779. // Modifier key presses don't count as 'real' key presses for the
  17780. // purpose of keymap fallthrough.
  17781. function isModifierKey(value) {
  17782. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  17783. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  17784. }
  17785. function addModifierNames(name, event, noShift) {
  17786. var base = name;
  17787. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  17788. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  17789. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  17790. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  17791. return name
  17792. }
  17793. // Look up the name of a key as indicated by an event object.
  17794. function keyName(event, noShift) {
  17795. if (presto && event.keyCode == 34 && event["char"]) { return false }
  17796. var name = keyNames[event.keyCode];
  17797. if (name == null || event.altGraphKey) { return false }
  17798. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  17799. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  17800. if (event.keyCode == 3 && event.code) { name = event.code; }
  17801. return addModifierNames(name, event, noShift)
  17802. }
  17803. function getKeyMap(val) {
  17804. return typeof val == "string" ? keyMap[val] : val
  17805. }
  17806. // Helper for deleting text near the selection(s), used to implement
  17807. // backspace, delete, and similar functionality.
  17808. function deleteNearSelection(cm, compute) {
  17809. var ranges = cm.doc.sel.ranges, kill = [];
  17810. // Build up a set of ranges to kill first, merging overlapping
  17811. // ranges.
  17812. for (var i = 0; i < ranges.length; i++) {
  17813. var toKill = compute(ranges[i]);
  17814. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  17815. var replaced = kill.pop();
  17816. if (cmp(replaced.from, toKill.from) < 0) {
  17817. toKill.from = replaced.from;
  17818. break
  17819. }
  17820. }
  17821. kill.push(toKill);
  17822. }
  17823. // Next, remove those actual ranges.
  17824. runInOp(cm, function () {
  17825. for (var i = kill.length - 1; i >= 0; i--)
  17826. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  17827. ensureCursorVisible(cm);
  17828. });
  17829. }
  17830. function moveCharLogically(line, ch, dir) {
  17831. var target = skipExtendingChars(line.text, ch + dir, dir);
  17832. return target < 0 || target > line.text.length ? null : target
  17833. }
  17834. function moveLogically(line, start, dir) {
  17835. var ch = moveCharLogically(line, start.ch, dir);
  17836. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  17837. }
  17838. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  17839. if (visually) {
  17840. var order = getOrder(lineObj, cm.doc.direction);
  17841. if (order) {
  17842. var part = dir < 0 ? lst(order) : order[0];
  17843. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  17844. var sticky = moveInStorageOrder ? "after" : "before";
  17845. var ch;
  17846. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  17847. // it could be that the last bidi part is not on the last visual line,
  17848. // since visual lines contain content order-consecutive chunks.
  17849. // Thus, in rtl, we are looking for the first (content-order) character
  17850. // in the rtl chunk that is on the last line (that is, the same line
  17851. // as the last (content-order) character).
  17852. if (part.level > 0 || cm.doc.direction == "rtl") {
  17853. var prep = prepareMeasureForLine(cm, lineObj);
  17854. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  17855. var targetTop = measureCharPrepared(cm, prep, ch).top;
  17856. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  17857. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  17858. } else { ch = dir < 0 ? part.to : part.from; }
  17859. return new Pos(lineNo, ch, sticky)
  17860. }
  17861. }
  17862. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  17863. }
  17864. function moveVisually(cm, line, start, dir) {
  17865. var bidi = getOrder(line, cm.doc.direction);
  17866. if (!bidi) { return moveLogically(line, start, dir) }
  17867. if (start.ch >= line.text.length) {
  17868. start.ch = line.text.length;
  17869. start.sticky = "before";
  17870. } else if (start.ch <= 0) {
  17871. start.ch = 0;
  17872. start.sticky = "after";
  17873. }
  17874. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  17875. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  17876. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  17877. // nothing interesting happens.
  17878. return moveLogically(line, start, dir)
  17879. }
  17880. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  17881. var prep;
  17882. var getWrappedLineExtent = function (ch) {
  17883. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  17884. prep = prep || prepareMeasureForLine(cm, line);
  17885. return wrappedLineExtentChar(cm, line, prep, ch)
  17886. };
  17887. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  17888. if (cm.doc.direction == "rtl" || part.level == 1) {
  17889. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  17890. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  17891. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  17892. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  17893. var sticky = moveInStorageOrder ? "before" : "after";
  17894. return new Pos(start.line, ch, sticky)
  17895. }
  17896. }
  17897. // Case 3: Could not move within this bidi part in this visual line, so leave
  17898. // the current bidi part
  17899. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  17900. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  17901. ? new Pos(start.line, mv(ch, 1), "before")
  17902. : new Pos(start.line, ch, "after"); };
  17903. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  17904. var part = bidi[partPos];
  17905. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  17906. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  17907. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  17908. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  17909. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  17910. }
  17911. };
  17912. // Case 3a: Look for other bidi parts on the same visual line
  17913. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  17914. if (res) { return res }
  17915. // Case 3b: Look for other bidi parts on the next visual line
  17916. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  17917. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  17918. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  17919. if (res) { return res }
  17920. }
  17921. // Case 4: Nowhere to move
  17922. return null
  17923. }
  17924. // Commands are parameter-less actions that can be performed on an
  17925. // editor, mostly used for keybindings.
  17926. var commands = {
  17927. selectAll: selectAll,
  17928. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  17929. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  17930. if (range.empty()) {
  17931. var len = getLine(cm.doc, range.head.line).text.length;
  17932. if (range.head.ch == len && range.head.line < cm.lastLine())
  17933. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  17934. else
  17935. { return {from: range.head, to: Pos(range.head.line, len)} }
  17936. } else {
  17937. return {from: range.from(), to: range.to()}
  17938. }
  17939. }); },
  17940. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  17941. from: Pos(range.from().line, 0),
  17942. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  17943. }); }); },
  17944. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  17945. from: Pos(range.from().line, 0), to: range.from()
  17946. }); }); },
  17947. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  17948. var top = cm.charCoords(range.head, "div").top + 5;
  17949. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  17950. return {from: leftPos, to: range.from()}
  17951. }); },
  17952. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  17953. var top = cm.charCoords(range.head, "div").top + 5;
  17954. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  17955. return {from: range.from(), to: rightPos }
  17956. }); },
  17957. undo: function (cm) { return cm.undo(); },
  17958. redo: function (cm) { return cm.redo(); },
  17959. undoSelection: function (cm) { return cm.undoSelection(); },
  17960. redoSelection: function (cm) { return cm.redoSelection(); },
  17961. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  17962. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  17963. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  17964. {origin: "+move", bias: 1}
  17965. ); },
  17966. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  17967. {origin: "+move", bias: 1}
  17968. ); },
  17969. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  17970. {origin: "+move", bias: -1}
  17971. ); },
  17972. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  17973. var top = cm.cursorCoords(range.head, "div").top + 5;
  17974. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  17975. }, sel_move); },
  17976. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  17977. var top = cm.cursorCoords(range.head, "div").top + 5;
  17978. return cm.coordsChar({left: 0, top: top}, "div")
  17979. }, sel_move); },
  17980. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  17981. var top = cm.cursorCoords(range.head, "div").top + 5;
  17982. var pos = cm.coordsChar({left: 0, top: top}, "div");
  17983. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  17984. return pos
  17985. }, sel_move); },
  17986. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  17987. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  17988. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  17989. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  17990. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  17991. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  17992. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  17993. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  17994. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  17995. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  17996. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  17997. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  17998. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  17999. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  18000. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  18001. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  18002. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  18003. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  18004. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  18005. indentMore: function (cm) { return cm.indentSelection("add"); },
  18006. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  18007. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  18008. insertSoftTab: function (cm) {
  18009. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  18010. for (var i = 0; i < ranges.length; i++) {
  18011. var pos = ranges[i].from();
  18012. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  18013. spaces.push(spaceStr(tabSize - col % tabSize));
  18014. }
  18015. cm.replaceSelections(spaces);
  18016. },
  18017. defaultTab: function (cm) {
  18018. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  18019. else { cm.execCommand("insertTab"); }
  18020. },
  18021. // Swap the two chars left and right of each selection's head.
  18022. // Move cursor behind the two swapped characters afterwards.
  18023. //
  18024. // Doesn't consider line feeds a character.
  18025. // Doesn't scan more than one line above to find a character.
  18026. // Doesn't do anything on an empty line.
  18027. // Doesn't do anything with non-empty selections.
  18028. transposeChars: function (cm) { return runInOp(cm, function () {
  18029. var ranges = cm.listSelections(), newSel = [];
  18030. for (var i = 0; i < ranges.length; i++) {
  18031. if (!ranges[i].empty()) { continue }
  18032. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  18033. if (line) {
  18034. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  18035. if (cur.ch > 0) {
  18036. cur = new Pos(cur.line, cur.ch + 1);
  18037. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  18038. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  18039. } else if (cur.line > cm.doc.first) {
  18040. var prev = getLine(cm.doc, cur.line - 1).text;
  18041. if (prev) {
  18042. cur = new Pos(cur.line, 1);
  18043. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  18044. prev.charAt(prev.length - 1),
  18045. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  18046. }
  18047. }
  18048. }
  18049. newSel.push(new Range(cur, cur));
  18050. }
  18051. cm.setSelections(newSel);
  18052. }); },
  18053. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  18054. var sels = cm.listSelections();
  18055. for (var i = sels.length - 1; i >= 0; i--)
  18056. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  18057. sels = cm.listSelections();
  18058. for (var i$1 = 0; i$1 < sels.length; i$1++)
  18059. { cm.indentLine(sels[i$1].from().line, null, true); }
  18060. ensureCursorVisible(cm);
  18061. }); },
  18062. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  18063. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  18064. };
  18065. function lineStart(cm, lineN) {
  18066. var line = getLine(cm.doc, lineN);
  18067. var visual = visualLine(line);
  18068. if (visual != line) { lineN = lineNo(visual); }
  18069. return endOfLine(true, cm, visual, lineN, 1)
  18070. }
  18071. function lineEnd(cm, lineN) {
  18072. var line = getLine(cm.doc, lineN);
  18073. var visual = visualLineEnd(line);
  18074. if (visual != line) { lineN = lineNo(visual); }
  18075. return endOfLine(true, cm, line, lineN, -1)
  18076. }
  18077. function lineStartSmart(cm, pos) {
  18078. var start = lineStart(cm, pos.line);
  18079. var line = getLine(cm.doc, start.line);
  18080. var order = getOrder(line, cm.doc.direction);
  18081. if (!order || order[0].level == 0) {
  18082. var firstNonWS = Math.max(0, line.text.search(/\S/));
  18083. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  18084. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  18085. }
  18086. return start
  18087. }
  18088. // Run a handler that was bound to a key.
  18089. function doHandleBinding(cm, bound, dropShift) {
  18090. if (typeof bound == "string") {
  18091. bound = commands[bound];
  18092. if (!bound) { return false }
  18093. }
  18094. // Ensure previous input has been read, so that the handler sees a
  18095. // consistent view of the document
  18096. cm.display.input.ensurePolled();
  18097. var prevShift = cm.display.shift, done = false;
  18098. try {
  18099. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  18100. if (dropShift) { cm.display.shift = false; }
  18101. done = bound(cm) != Pass;
  18102. } finally {
  18103. cm.display.shift = prevShift;
  18104. cm.state.suppressEdits = false;
  18105. }
  18106. return done
  18107. }
  18108. function lookupKeyForEditor(cm, name, handle) {
  18109. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  18110. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  18111. if (result) { return result }
  18112. }
  18113. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  18114. || lookupKey(name, cm.options.keyMap, handle, cm)
  18115. }
  18116. // Note that, despite the name, this function is also used to check
  18117. // for bound mouse clicks.
  18118. var stopSeq = new Delayed;
  18119. function dispatchKey(cm, name, e, handle) {
  18120. var seq = cm.state.keySeq;
  18121. if (seq) {
  18122. if (isModifierKey(name)) { return "handled" }
  18123. if (/\'$/.test(name))
  18124. { cm.state.keySeq = null; }
  18125. else
  18126. { stopSeq.set(50, function () {
  18127. if (cm.state.keySeq == seq) {
  18128. cm.state.keySeq = null;
  18129. cm.display.input.reset();
  18130. }
  18131. }); }
  18132. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  18133. }
  18134. return dispatchKeyInner(cm, name, e, handle)
  18135. }
  18136. function dispatchKeyInner(cm, name, e, handle) {
  18137. var result = lookupKeyForEditor(cm, name, handle);
  18138. if (result == "multi")
  18139. { cm.state.keySeq = name; }
  18140. if (result == "handled")
  18141. { signalLater(cm, "keyHandled", cm, name, e); }
  18142. if (result == "handled" || result == "multi") {
  18143. e_preventDefault(e);
  18144. restartBlink(cm);
  18145. }
  18146. return !!result
  18147. }
  18148. // Handle a key from the keydown event.
  18149. function handleKeyBinding(cm, e) {
  18150. var name = keyName(e, true);
  18151. if (!name) { return false }
  18152. if (e.shiftKey && !cm.state.keySeq) {
  18153. // First try to resolve full name (including 'Shift-'). Failing
  18154. // that, see if there is a cursor-motion command (starting with
  18155. // 'go') bound to the keyname without 'Shift-'.
  18156. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  18157. || dispatchKey(cm, name, e, function (b) {
  18158. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  18159. { return doHandleBinding(cm, b) }
  18160. })
  18161. } else {
  18162. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  18163. }
  18164. }
  18165. // Handle a key from the keypress event
  18166. function handleCharBinding(cm, e, ch) {
  18167. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  18168. }
  18169. var lastStoppedKey = null;
  18170. function onKeyDown(e) {
  18171. var cm = this;
  18172. cm.curOp.focus = activeElt();
  18173. if (signalDOMEvent(cm, e)) { return }
  18174. // IE does strange things with escape.
  18175. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  18176. var code = e.keyCode;
  18177. cm.display.shift = code == 16 || e.shiftKey;
  18178. var handled = handleKeyBinding(cm, e);
  18179. if (presto) {
  18180. lastStoppedKey = handled ? code : null;
  18181. // Opera has no cut event... we try to at least catch the key combo
  18182. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  18183. { cm.replaceSelection("", null, "cut"); }
  18184. }
  18185. // Turn mouse into crosshair when Alt is held on Mac.
  18186. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  18187. { showCrossHair(cm); }
  18188. }
  18189. function showCrossHair(cm) {
  18190. var lineDiv = cm.display.lineDiv;
  18191. addClass(lineDiv, "CodeMirror-crosshair");
  18192. function up(e) {
  18193. if (e.keyCode == 18 || !e.altKey) {
  18194. rmClass(lineDiv, "CodeMirror-crosshair");
  18195. off(document, "keyup", up);
  18196. off(document, "mouseover", up);
  18197. }
  18198. }
  18199. on(document, "keyup", up);
  18200. on(document, "mouseover", up);
  18201. }
  18202. function onKeyUp(e) {
  18203. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  18204. signalDOMEvent(this, e);
  18205. }
  18206. function onKeyPress(e) {
  18207. var cm = this;
  18208. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  18209. var keyCode = e.keyCode, charCode = e.charCode;
  18210. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  18211. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  18212. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  18213. // Some browsers fire keypress events for backspace
  18214. if (ch == "\x08") { return }
  18215. if (handleCharBinding(cm, e, ch)) { return }
  18216. cm.display.input.onKeyPress(e);
  18217. }
  18218. var DOUBLECLICK_DELAY = 400;
  18219. var PastClick = function(time, pos, button) {
  18220. this.time = time;
  18221. this.pos = pos;
  18222. this.button = button;
  18223. };
  18224. PastClick.prototype.compare = function (time, pos, button) {
  18225. return this.time + DOUBLECLICK_DELAY > time &&
  18226. cmp(pos, this.pos) == 0 && button == this.button
  18227. };
  18228. var lastClick, lastDoubleClick;
  18229. function clickRepeat(pos, button) {
  18230. var now = +new Date;
  18231. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  18232. lastClick = lastDoubleClick = null;
  18233. return "triple"
  18234. } else if (lastClick && lastClick.compare(now, pos, button)) {
  18235. lastDoubleClick = new PastClick(now, pos, button);
  18236. lastClick = null;
  18237. return "double"
  18238. } else {
  18239. lastClick = new PastClick(now, pos, button);
  18240. lastDoubleClick = null;
  18241. return "single"
  18242. }
  18243. }
  18244. // A mouse down can be a single click, double click, triple click,
  18245. // start of selection drag, start of text drag, new cursor
  18246. // (ctrl-click), rectangle drag (alt-drag), or xwin
  18247. // middle-click-paste. Or it might be a click on something we should
  18248. // not interfere with, such as a scrollbar or widget.
  18249. function onMouseDown(e) {
  18250. var cm = this, display = cm.display;
  18251. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  18252. display.input.ensurePolled();
  18253. display.shift = e.shiftKey;
  18254. if (eventInWidget(display, e)) {
  18255. if (!webkit) {
  18256. // Briefly turn off draggability, to allow widgets to do
  18257. // normal dragging things.
  18258. display.scroller.draggable = false;
  18259. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  18260. }
  18261. return
  18262. }
  18263. if (clickInGutter(cm, e)) { return }
  18264. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  18265. window.focus();
  18266. // #3261: make sure, that we're not starting a second selection
  18267. if (button == 1 && cm.state.selectingText)
  18268. { cm.state.selectingText(e); }
  18269. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  18270. if (button == 1) {
  18271. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  18272. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  18273. } else if (button == 2) {
  18274. if (pos) { extendSelection(cm.doc, pos); }
  18275. setTimeout(function () { return display.input.focus(); }, 20);
  18276. } else if (button == 3) {
  18277. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  18278. else { delayBlurEvent(cm); }
  18279. }
  18280. }
  18281. function handleMappedButton(cm, button, pos, repeat, event) {
  18282. var name = "Click";
  18283. if (repeat == "double") { name = "Double" + name; }
  18284. else if (repeat == "triple") { name = "Triple" + name; }
  18285. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  18286. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  18287. if (typeof bound == "string") { bound = commands[bound]; }
  18288. if (!bound) { return false }
  18289. var done = false;
  18290. try {
  18291. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  18292. done = bound(cm, pos) != Pass;
  18293. } finally {
  18294. cm.state.suppressEdits = false;
  18295. }
  18296. return done
  18297. })
  18298. }
  18299. function configureMouse(cm, repeat, event) {
  18300. var option = cm.getOption("configureMouse");
  18301. var value = option ? option(cm, repeat, event) : {};
  18302. if (value.unit == null) {
  18303. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  18304. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  18305. }
  18306. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  18307. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  18308. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  18309. return value
  18310. }
  18311. function leftButtonDown(cm, pos, repeat, event) {
  18312. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  18313. else { cm.curOp.focus = activeElt(); }
  18314. var behavior = configureMouse(cm, repeat, event);
  18315. var sel = cm.doc.sel, contained;
  18316. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  18317. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  18318. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  18319. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  18320. { leftButtonStartDrag(cm, event, pos, behavior); }
  18321. else
  18322. { leftButtonSelect(cm, event, pos, behavior); }
  18323. }
  18324. // Start a text drag. When it ends, see if any dragging actually
  18325. // happen, and treat as a click if it didn't.
  18326. function leftButtonStartDrag(cm, event, pos, behavior) {
  18327. var display = cm.display, moved = false;
  18328. var dragEnd = operation(cm, function (e) {
  18329. if (webkit) { display.scroller.draggable = false; }
  18330. cm.state.draggingText = false;
  18331. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  18332. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  18333. off(display.scroller, "dragstart", dragStart);
  18334. off(display.scroller, "drop", dragEnd);
  18335. if (!moved) {
  18336. e_preventDefault(e);
  18337. if (!behavior.addNew)
  18338. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  18339. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  18340. if (webkit || ie && ie_version == 9)
  18341. { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }
  18342. else
  18343. { display.input.focus(); }
  18344. }
  18345. });
  18346. var mouseMove = function(e2) {
  18347. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  18348. };
  18349. var dragStart = function () { return moved = true; };
  18350. // Let the drag handler handle this.
  18351. if (webkit) { display.scroller.draggable = true; }
  18352. cm.state.draggingText = dragEnd;
  18353. dragEnd.copy = !behavior.moveOnDrag;
  18354. // IE's approach to draggable
  18355. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  18356. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  18357. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  18358. on(display.scroller, "dragstart", dragStart);
  18359. on(display.scroller, "drop", dragEnd);
  18360. delayBlurEvent(cm);
  18361. setTimeout(function () { return display.input.focus(); }, 20);
  18362. }
  18363. function rangeForUnit(cm, pos, unit) {
  18364. if (unit == "char") { return new Range(pos, pos) }
  18365. if (unit == "word") { return cm.findWordAt(pos) }
  18366. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  18367. var result = unit(cm, pos);
  18368. return new Range(result.from, result.to)
  18369. }
  18370. // Normal selection, as opposed to text dragging.
  18371. function leftButtonSelect(cm, event, start, behavior) {
  18372. var display = cm.display, doc = cm.doc;
  18373. e_preventDefault(event);
  18374. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  18375. if (behavior.addNew && !behavior.extend) {
  18376. ourIndex = doc.sel.contains(start);
  18377. if (ourIndex > -1)
  18378. { ourRange = ranges[ourIndex]; }
  18379. else
  18380. { ourRange = new Range(start, start); }
  18381. } else {
  18382. ourRange = doc.sel.primary();
  18383. ourIndex = doc.sel.primIndex;
  18384. }
  18385. if (behavior.unit == "rectangle") {
  18386. if (!behavior.addNew) { ourRange = new Range(start, start); }
  18387. start = posFromMouse(cm, event, true, true);
  18388. ourIndex = -1;
  18389. } else {
  18390. var range$$1 = rangeForUnit(cm, start, behavior.unit);
  18391. if (behavior.extend)
  18392. { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
  18393. else
  18394. { ourRange = range$$1; }
  18395. }
  18396. if (!behavior.addNew) {
  18397. ourIndex = 0;
  18398. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  18399. startSel = doc.sel;
  18400. } else if (ourIndex == -1) {
  18401. ourIndex = ranges.length;
  18402. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  18403. {scroll: false, origin: "*mouse"});
  18404. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  18405. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  18406. {scroll: false, origin: "*mouse"});
  18407. startSel = doc.sel;
  18408. } else {
  18409. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  18410. }
  18411. var lastPos = start;
  18412. function extendTo(pos) {
  18413. if (cmp(lastPos, pos) == 0) { return }
  18414. lastPos = pos;
  18415. if (behavior.unit == "rectangle") {
  18416. var ranges = [], tabSize = cm.options.tabSize;
  18417. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  18418. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  18419. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  18420. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  18421. line <= end; line++) {
  18422. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  18423. if (left == right)
  18424. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  18425. else if (text.length > leftPos)
  18426. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  18427. }
  18428. if (!ranges.length) { ranges.push(new Range(start, start)); }
  18429. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  18430. {origin: "*mouse", scroll: false});
  18431. cm.scrollIntoView(pos);
  18432. } else {
  18433. var oldRange = ourRange;
  18434. var range$$1 = rangeForUnit(cm, pos, behavior.unit);
  18435. var anchor = oldRange.anchor, head;
  18436. if (cmp(range$$1.anchor, anchor) > 0) {
  18437. head = range$$1.head;
  18438. anchor = minPos(oldRange.from(), range$$1.anchor);
  18439. } else {
  18440. head = range$$1.anchor;
  18441. anchor = maxPos(oldRange.to(), range$$1.head);
  18442. }
  18443. var ranges$1 = startSel.ranges.slice(0);
  18444. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  18445. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  18446. }
  18447. }
  18448. var editorSize = display.wrapper.getBoundingClientRect();
  18449. // Used to ensure timeout re-tries don't fire when another extend
  18450. // happened in the meantime (clearTimeout isn't reliable -- at
  18451. // least on Chrome, the timeouts still happen even when cleared,
  18452. // if the clear happens after their scheduled firing time).
  18453. var counter = 0;
  18454. function extend(e) {
  18455. var curCount = ++counter;
  18456. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  18457. if (!cur) { return }
  18458. if (cmp(cur, lastPos) != 0) {
  18459. cm.curOp.focus = activeElt();
  18460. extendTo(cur);
  18461. var visible = visibleLines(display, doc);
  18462. if (cur.line >= visible.to || cur.line < visible.from)
  18463. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  18464. } else {
  18465. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  18466. if (outside) { setTimeout(operation(cm, function () {
  18467. if (counter != curCount) { return }
  18468. display.scroller.scrollTop += outside;
  18469. extend(e);
  18470. }), 50); }
  18471. }
  18472. }
  18473. function done(e) {
  18474. cm.state.selectingText = false;
  18475. counter = Infinity;
  18476. // If e is null or undefined we interpret this as someone trying
  18477. // to explicitly cancel the selection rather than the user
  18478. // letting go of the mouse button.
  18479. if (e) {
  18480. e_preventDefault(e);
  18481. display.input.focus();
  18482. }
  18483. off(display.wrapper.ownerDocument, "mousemove", move);
  18484. off(display.wrapper.ownerDocument, "mouseup", up);
  18485. doc.history.lastSelOrigin = null;
  18486. }
  18487. var move = operation(cm, function (e) {
  18488. if (e.buttons === 0 || !e_button(e)) { done(e); }
  18489. else { extend(e); }
  18490. });
  18491. var up = operation(cm, done);
  18492. cm.state.selectingText = up;
  18493. on(display.wrapper.ownerDocument, "mousemove", move);
  18494. on(display.wrapper.ownerDocument, "mouseup", up);
  18495. }
  18496. // Used when mouse-selecting to adjust the anchor to the proper side
  18497. // of a bidi jump depending on the visual position of the head.
  18498. function bidiSimplify(cm, range$$1) {
  18499. var anchor = range$$1.anchor;
  18500. var head = range$$1.head;
  18501. var anchorLine = getLine(cm.doc, anchor.line);
  18502. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
  18503. var order = getOrder(anchorLine);
  18504. if (!order) { return range$$1 }
  18505. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  18506. if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
  18507. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  18508. if (boundary == 0 || boundary == order.length) { return range$$1 }
  18509. // Compute the relative visual position of the head compared to the
  18510. // anchor (<0 is to the left, >0 to the right)
  18511. var leftSide;
  18512. if (head.line != anchor.line) {
  18513. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  18514. } else {
  18515. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  18516. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  18517. if (headIndex == boundary - 1 || headIndex == boundary)
  18518. { leftSide = dir < 0; }
  18519. else
  18520. { leftSide = dir > 0; }
  18521. }
  18522. var usePart = order[boundary + (leftSide ? -1 : 0)];
  18523. var from = leftSide == (usePart.level == 1);
  18524. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  18525. return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
  18526. }
  18527. // Determines whether an event happened in the gutter, and fires the
  18528. // handlers for the corresponding event.
  18529. function gutterEvent(cm, e, type, prevent) {
  18530. var mX, mY;
  18531. if (e.touches) {
  18532. mX = e.touches[0].clientX;
  18533. mY = e.touches[0].clientY;
  18534. } else {
  18535. try { mX = e.clientX; mY = e.clientY; }
  18536. catch(e) { return false }
  18537. }
  18538. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  18539. if (prevent) { e_preventDefault(e); }
  18540. var display = cm.display;
  18541. var lineBox = display.lineDiv.getBoundingClientRect();
  18542. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  18543. mY -= lineBox.top - display.viewOffset;
  18544. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  18545. var g = display.gutters.childNodes[i];
  18546. if (g && g.getBoundingClientRect().right >= mX) {
  18547. var line = lineAtHeight(cm.doc, mY);
  18548. var gutter = cm.display.gutterSpecs[i];
  18549. signal(cm, type, cm, line, gutter.className, e);
  18550. return e_defaultPrevented(e)
  18551. }
  18552. }
  18553. }
  18554. function clickInGutter(cm, e) {
  18555. return gutterEvent(cm, e, "gutterClick", true)
  18556. }
  18557. // CONTEXT MENU HANDLING
  18558. // To make the context menu work, we need to briefly unhide the
  18559. // textarea (making it as unobtrusive as possible) to let the
  18560. // right-click take effect on it.
  18561. function onContextMenu(cm, e) {
  18562. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  18563. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  18564. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  18565. }
  18566. function contextMenuInGutter(cm, e) {
  18567. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  18568. return gutterEvent(cm, e, "gutterContextMenu", false)
  18569. }
  18570. function themeChanged(cm) {
  18571. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  18572. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  18573. clearCaches(cm);
  18574. }
  18575. var Init = {toString: function(){return "CodeMirror.Init"}};
  18576. var defaults = {};
  18577. var optionHandlers = {};
  18578. function defineOptions(CodeMirror) {
  18579. var optionHandlers = CodeMirror.optionHandlers;
  18580. function option(name, deflt, handle, notOnInit) {
  18581. CodeMirror.defaults[name] = deflt;
  18582. if (handle) { optionHandlers[name] =
  18583. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  18584. }
  18585. CodeMirror.defineOption = option;
  18586. // Passed to option handlers when there is no old value.
  18587. CodeMirror.Init = Init;
  18588. // These two are, on init, called from the constructor because they
  18589. // have to be initialized before the editor can start at all.
  18590. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  18591. option("mode", null, function (cm, val) {
  18592. cm.doc.modeOption = val;
  18593. loadMode(cm);
  18594. }, true);
  18595. option("indentUnit", 2, loadMode, true);
  18596. option("indentWithTabs", false);
  18597. option("smartIndent", true);
  18598. option("tabSize", 4, function (cm) {
  18599. resetModeState(cm);
  18600. clearCaches(cm);
  18601. regChange(cm);
  18602. }, true);
  18603. option("lineSeparator", null, function (cm, val) {
  18604. cm.doc.lineSep = val;
  18605. if (!val) { return }
  18606. var newBreaks = [], lineNo = cm.doc.first;
  18607. cm.doc.iter(function (line) {
  18608. for (var pos = 0;;) {
  18609. var found = line.text.indexOf(val, pos);
  18610. if (found == -1) { break }
  18611. pos = found + val.length;
  18612. newBreaks.push(Pos(lineNo, found));
  18613. }
  18614. lineNo++;
  18615. });
  18616. for (var i = newBreaks.length - 1; i >= 0; i--)
  18617. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  18618. });
  18619. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  18620. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  18621. if (old != Init) { cm.refresh(); }
  18622. });
  18623. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  18624. option("electricChars", true);
  18625. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  18626. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  18627. }, true);
  18628. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  18629. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  18630. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  18631. option("rtlMoveVisually", !windows);
  18632. option("wholeLineUpdateBefore", true);
  18633. option("theme", "default", function (cm) {
  18634. themeChanged(cm);
  18635. updateGutters(cm);
  18636. }, true);
  18637. option("keyMap", "default", function (cm, val, old) {
  18638. var next = getKeyMap(val);
  18639. var prev = old != Init && getKeyMap(old);
  18640. if (prev && prev.detach) { prev.detach(cm, next); }
  18641. if (next.attach) { next.attach(cm, prev || null); }
  18642. });
  18643. option("extraKeys", null);
  18644. option("configureMouse", null);
  18645. option("lineWrapping", false, wrappingChanged, true);
  18646. option("gutters", [], function (cm, val) {
  18647. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  18648. updateGutters(cm);
  18649. }, true);
  18650. option("fixedGutter", true, function (cm, val) {
  18651. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  18652. cm.refresh();
  18653. }, true);
  18654. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  18655. option("scrollbarStyle", "native", function (cm) {
  18656. initScrollbars(cm);
  18657. updateScrollbars(cm);
  18658. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  18659. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  18660. }, true);
  18661. option("lineNumbers", false, function (cm, val) {
  18662. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  18663. updateGutters(cm);
  18664. }, true);
  18665. option("firstLineNumber", 1, updateGutters, true);
  18666. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  18667. option("showCursorWhenSelecting", false, updateSelection, true);
  18668. option("resetSelectionOnContextMenu", true);
  18669. option("lineWiseCopyCut", true);
  18670. option("pasteLinesPerSelection", true);
  18671. option("selectionsMayTouch", false);
  18672. option("readOnly", false, function (cm, val) {
  18673. if (val == "nocursor") {
  18674. onBlur(cm);
  18675. cm.display.input.blur();
  18676. }
  18677. cm.display.input.readOnlyChanged(val);
  18678. });
  18679. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  18680. option("dragDrop", true, dragDropChanged);
  18681. option("allowDropFileTypes", null);
  18682. option("cursorBlinkRate", 530);
  18683. option("cursorScrollMargin", 0);
  18684. option("cursorHeight", 1, updateSelection, true);
  18685. option("singleCursorHeightPerLine", true, updateSelection, true);
  18686. option("workTime", 100);
  18687. option("workDelay", 100);
  18688. option("flattenSpans", true, resetModeState, true);
  18689. option("addModeClass", false, resetModeState, true);
  18690. option("pollInterval", 100);
  18691. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  18692. option("historyEventDelay", 1250);
  18693. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  18694. option("maxHighlightLength", 10000, resetModeState, true);
  18695. option("moveInputWithCursor", true, function (cm, val) {
  18696. if (!val) { cm.display.input.resetPosition(); }
  18697. });
  18698. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  18699. option("autofocus", null);
  18700. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  18701. option("phrases", null);
  18702. }
  18703. function dragDropChanged(cm, value, old) {
  18704. var wasOn = old && old != Init;
  18705. if (!value != !wasOn) {
  18706. var funcs = cm.display.dragFunctions;
  18707. var toggle = value ? on : off;
  18708. toggle(cm.display.scroller, "dragstart", funcs.start);
  18709. toggle(cm.display.scroller, "dragenter", funcs.enter);
  18710. toggle(cm.display.scroller, "dragover", funcs.over);
  18711. toggle(cm.display.scroller, "dragleave", funcs.leave);
  18712. toggle(cm.display.scroller, "drop", funcs.drop);
  18713. }
  18714. }
  18715. function wrappingChanged(cm) {
  18716. if (cm.options.lineWrapping) {
  18717. addClass(cm.display.wrapper, "CodeMirror-wrap");
  18718. cm.display.sizer.style.minWidth = "";
  18719. cm.display.sizerWidth = null;
  18720. } else {
  18721. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  18722. findMaxLine(cm);
  18723. }
  18724. estimateLineHeights(cm);
  18725. regChange(cm);
  18726. clearCaches(cm);
  18727. setTimeout(function () { return updateScrollbars(cm); }, 100);
  18728. }
  18729. // A CodeMirror instance represents an editor. This is the object
  18730. // that user code is usually dealing with.
  18731. function CodeMirror(place, options) {
  18732. var this$1 = this;
  18733. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  18734. this.options = options = options ? copyObj(options) : {};
  18735. // Determine effective options based on given values and defaults.
  18736. copyObj(defaults, options, false);
  18737. var doc = options.value;
  18738. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  18739. else if (options.mode) { doc.modeOption = options.mode; }
  18740. this.doc = doc;
  18741. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  18742. var display = this.display = new Display(place, doc, input, options);
  18743. display.wrapper.CodeMirror = this;
  18744. themeChanged(this);
  18745. if (options.lineWrapping)
  18746. { this.display.wrapper.className += " CodeMirror-wrap"; }
  18747. initScrollbars(this);
  18748. this.state = {
  18749. keyMaps: [], // stores maps added by addKeyMap
  18750. overlays: [], // highlighting overlays, as added by addOverlay
  18751. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  18752. overwrite: false,
  18753. delayingBlurEvent: false,
  18754. focused: false,
  18755. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  18756. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  18757. selectingText: false,
  18758. draggingText: false,
  18759. highlight: new Delayed(), // stores highlight worker timeout
  18760. keySeq: null, // Unfinished key sequence
  18761. specialChars: null
  18762. };
  18763. if (options.autofocus && !mobile) { display.input.focus(); }
  18764. // Override magic textarea content restore that IE sometimes does
  18765. // on our hidden textarea on reload
  18766. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  18767. registerEventHandlers(this);
  18768. ensureGlobalHandlers();
  18769. startOperation(this);
  18770. this.curOp.forceUpdate = true;
  18771. attachDoc(this, doc);
  18772. if ((options.autofocus && !mobile) || this.hasFocus())
  18773. { setTimeout(bind(onFocus, this), 20); }
  18774. else
  18775. { onBlur(this); }
  18776. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  18777. { optionHandlers[opt](this$1, options[opt], Init); } }
  18778. maybeUpdateLineNumberWidth(this);
  18779. if (options.finishInit) { options.finishInit(this); }
  18780. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
  18781. endOperation(this);
  18782. // Suppress optimizelegibility in Webkit, since it breaks text
  18783. // measuring on line wrapping boundaries.
  18784. if (webkit && options.lineWrapping &&
  18785. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  18786. { display.lineDiv.style.textRendering = "auto"; }
  18787. }
  18788. // The default configuration options.
  18789. CodeMirror.defaults = defaults;
  18790. // Functions to run when options are changed.
  18791. CodeMirror.optionHandlers = optionHandlers;
  18792. // Attach the necessary event handlers when initializing the editor
  18793. function registerEventHandlers(cm) {
  18794. var d = cm.display;
  18795. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  18796. // Older IE's will not fire a second mousedown for a double click
  18797. if (ie && ie_version < 11)
  18798. { on(d.scroller, "dblclick", operation(cm, function (e) {
  18799. if (signalDOMEvent(cm, e)) { return }
  18800. var pos = posFromMouse(cm, e);
  18801. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  18802. e_preventDefault(e);
  18803. var word = cm.findWordAt(pos);
  18804. extendSelection(cm.doc, word.anchor, word.head);
  18805. })); }
  18806. else
  18807. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  18808. // Some browsers fire contextmenu *after* opening the menu, at
  18809. // which point we can't mess with it anymore. Context menu is
  18810. // handled in onMouseDown for these browsers.
  18811. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  18812. // Used to suppress mouse event handling when a touch happens
  18813. var touchFinished, prevTouch = {end: 0};
  18814. function finishTouch() {
  18815. if (d.activeTouch) {
  18816. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  18817. prevTouch = d.activeTouch;
  18818. prevTouch.end = +new Date;
  18819. }
  18820. }
  18821. function isMouseLikeTouchEvent(e) {
  18822. if (e.touches.length != 1) { return false }
  18823. var touch = e.touches[0];
  18824. return touch.radiusX <= 1 && touch.radiusY <= 1
  18825. }
  18826. function farAway(touch, other) {
  18827. if (other.left == null) { return true }
  18828. var dx = other.left - touch.left, dy = other.top - touch.top;
  18829. return dx * dx + dy * dy > 20 * 20
  18830. }
  18831. on(d.scroller, "touchstart", function (e) {
  18832. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  18833. d.input.ensurePolled();
  18834. clearTimeout(touchFinished);
  18835. var now = +new Date;
  18836. d.activeTouch = {start: now, moved: false,
  18837. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  18838. if (e.touches.length == 1) {
  18839. d.activeTouch.left = e.touches[0].pageX;
  18840. d.activeTouch.top = e.touches[0].pageY;
  18841. }
  18842. }
  18843. });
  18844. on(d.scroller, "touchmove", function () {
  18845. if (d.activeTouch) { d.activeTouch.moved = true; }
  18846. });
  18847. on(d.scroller, "touchend", function (e) {
  18848. var touch = d.activeTouch;
  18849. if (touch && !eventInWidget(d, e) && touch.left != null &&
  18850. !touch.moved && new Date - touch.start < 300) {
  18851. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  18852. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  18853. { range = new Range(pos, pos); }
  18854. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  18855. { range = cm.findWordAt(pos); }
  18856. else // Triple tap
  18857. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  18858. cm.setSelection(range.anchor, range.head);
  18859. cm.focus();
  18860. e_preventDefault(e);
  18861. }
  18862. finishTouch();
  18863. });
  18864. on(d.scroller, "touchcancel", finishTouch);
  18865. // Sync scrolling between fake scrollbars and real scrollable
  18866. // area, ensure viewport is updated when scrolling.
  18867. on(d.scroller, "scroll", function () {
  18868. if (d.scroller.clientHeight) {
  18869. updateScrollTop(cm, d.scroller.scrollTop);
  18870. setScrollLeft(cm, d.scroller.scrollLeft, true);
  18871. signal(cm, "scroll", cm);
  18872. }
  18873. });
  18874. // Listen to wheel events in order to try and update the viewport on time.
  18875. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  18876. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  18877. // Prevent wrapper from ever scrolling
  18878. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  18879. d.dragFunctions = {
  18880. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  18881. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  18882. start: function (e) { return onDragStart(cm, e); },
  18883. drop: operation(cm, onDrop),
  18884. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  18885. };
  18886. var inp = d.input.getField();
  18887. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  18888. on(inp, "keydown", operation(cm, onKeyDown));
  18889. on(inp, "keypress", operation(cm, onKeyPress));
  18890. on(inp, "focus", function (e) { return onFocus(cm, e); });
  18891. on(inp, "blur", function (e) { return onBlur(cm, e); });
  18892. }
  18893. var initHooks = [];
  18894. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  18895. // Indent the given line. The how parameter can be "smart",
  18896. // "add"/null, "subtract", or "prev". When aggressive is false
  18897. // (typically set to true for forced single-line indents), empty
  18898. // lines are not indented, and places where the mode returns Pass
  18899. // are left alone.
  18900. function indentLine(cm, n, how, aggressive) {
  18901. var doc = cm.doc, state;
  18902. if (how == null) { how = "add"; }
  18903. if (how == "smart") {
  18904. // Fall back to "prev" when the mode doesn't have an indentation
  18905. // method.
  18906. if (!doc.mode.indent) { how = "prev"; }
  18907. else { state = getContextBefore(cm, n).state; }
  18908. }
  18909. var tabSize = cm.options.tabSize;
  18910. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  18911. if (line.stateAfter) { line.stateAfter = null; }
  18912. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  18913. if (!aggressive && !/\S/.test(line.text)) {
  18914. indentation = 0;
  18915. how = "not";
  18916. } else if (how == "smart") {
  18917. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  18918. if (indentation == Pass || indentation > 150) {
  18919. if (!aggressive) { return }
  18920. how = "prev";
  18921. }
  18922. }
  18923. if (how == "prev") {
  18924. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  18925. else { indentation = 0; }
  18926. } else if (how == "add") {
  18927. indentation = curSpace + cm.options.indentUnit;
  18928. } else if (how == "subtract") {
  18929. indentation = curSpace - cm.options.indentUnit;
  18930. } else if (typeof how == "number") {
  18931. indentation = curSpace + how;
  18932. }
  18933. indentation = Math.max(0, indentation);
  18934. var indentString = "", pos = 0;
  18935. if (cm.options.indentWithTabs)
  18936. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  18937. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  18938. if (indentString != curSpaceString) {
  18939. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  18940. line.stateAfter = null;
  18941. return true
  18942. } else {
  18943. // Ensure that, if the cursor was in the whitespace at the start
  18944. // of the line, it is moved to the end of that space.
  18945. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  18946. var range = doc.sel.ranges[i$1];
  18947. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  18948. var pos$1 = Pos(n, curSpaceString.length);
  18949. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  18950. break
  18951. }
  18952. }
  18953. }
  18954. }
  18955. // This will be set to a {lineWise: bool, text: [string]} object, so
  18956. // that, when pasting, we know what kind of selections the copied
  18957. // text was made out of.
  18958. var lastCopied = null;
  18959. function setLastCopied(newLastCopied) {
  18960. lastCopied = newLastCopied;
  18961. }
  18962. function applyTextInput(cm, inserted, deleted, sel, origin) {
  18963. var doc = cm.doc;
  18964. cm.display.shift = false;
  18965. if (!sel) { sel = doc.sel; }
  18966. var recent = +new Date - 200;
  18967. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  18968. var textLines = splitLinesAuto(inserted), multiPaste = null;
  18969. // When pasting N lines into N selections, insert one line per selection
  18970. if (paste && sel.ranges.length > 1) {
  18971. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  18972. if (sel.ranges.length % lastCopied.text.length == 0) {
  18973. multiPaste = [];
  18974. for (var i = 0; i < lastCopied.text.length; i++)
  18975. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  18976. }
  18977. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  18978. multiPaste = map(textLines, function (l) { return [l]; });
  18979. }
  18980. }
  18981. var updateInput = cm.curOp.updateInput;
  18982. // Normal behavior is to insert the new text into every selection
  18983. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  18984. var range$$1 = sel.ranges[i$1];
  18985. var from = range$$1.from(), to = range$$1.to();
  18986. if (range$$1.empty()) {
  18987. if (deleted && deleted > 0) // Handle deletion
  18988. { from = Pos(from.line, from.ch - deleted); }
  18989. else if (cm.state.overwrite && !paste) // Handle overwrite
  18990. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  18991. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  18992. { from = to = Pos(from.line, 0); }
  18993. }
  18994. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  18995. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  18996. makeChange(cm.doc, changeEvent);
  18997. signalLater(cm, "inputRead", cm, changeEvent);
  18998. }
  18999. if (inserted && !paste)
  19000. { triggerElectric(cm, inserted); }
  19001. ensureCursorVisible(cm);
  19002. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  19003. cm.curOp.typing = true;
  19004. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  19005. }
  19006. function handlePaste(e, cm) {
  19007. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  19008. if (pasted) {
  19009. e.preventDefault();
  19010. if (!cm.isReadOnly() && !cm.options.disableInput)
  19011. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  19012. return true
  19013. }
  19014. }
  19015. function triggerElectric(cm, inserted) {
  19016. // When an 'electric' character is inserted, immediately trigger a reindent
  19017. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  19018. var sel = cm.doc.sel;
  19019. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  19020. var range$$1 = sel.ranges[i];
  19021. if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
  19022. var mode = cm.getModeAt(range$$1.head);
  19023. var indented = false;
  19024. if (mode.electricChars) {
  19025. for (var j = 0; j < mode.electricChars.length; j++)
  19026. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  19027. indented = indentLine(cm, range$$1.head.line, "smart");
  19028. break
  19029. } }
  19030. } else if (mode.electricInput) {
  19031. if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
  19032. { indented = indentLine(cm, range$$1.head.line, "smart"); }
  19033. }
  19034. if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
  19035. }
  19036. }
  19037. function copyableRanges(cm) {
  19038. var text = [], ranges = [];
  19039. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  19040. var line = cm.doc.sel.ranges[i].head.line;
  19041. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  19042. ranges.push(lineRange);
  19043. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  19044. }
  19045. return {text: text, ranges: ranges}
  19046. }
  19047. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  19048. field.setAttribute("autocorrect", autocorrect ? "" : "off");
  19049. field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  19050. field.setAttribute("spellcheck", !!spellcheck);
  19051. }
  19052. function hiddenTextarea() {
  19053. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  19054. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  19055. // The textarea is kept positioned near the cursor to prevent the
  19056. // fact that it'll be scrolled into view on input from scrolling
  19057. // our fake cursor out of view. On webkit, when wrap=off, paste is
  19058. // very slow. So make the area wide instead.
  19059. if (webkit) { te.style.width = "1000px"; }
  19060. else { te.setAttribute("wrap", "off"); }
  19061. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  19062. if (ios) { te.style.border = "1px solid black"; }
  19063. disableBrowserMagic(te);
  19064. return div
  19065. }
  19066. // The publicly visible API. Note that methodOp(f) means
  19067. // 'wrap f in an operation, performed on its `this` parameter'.
  19068. // This is not the complete set of editor methods. Most of the
  19069. // methods defined on the Doc type are also injected into
  19070. // CodeMirror.prototype, for backwards compatibility and
  19071. // convenience.
  19072. function addEditorMethods(CodeMirror) {
  19073. var optionHandlers = CodeMirror.optionHandlers;
  19074. var helpers = CodeMirror.helpers = {};
  19075. CodeMirror.prototype = {
  19076. constructor: CodeMirror,
  19077. focus: function(){window.focus(); this.display.input.focus();},
  19078. setOption: function(option, value) {
  19079. var options = this.options, old = options[option];
  19080. if (options[option] == value && option != "mode") { return }
  19081. options[option] = value;
  19082. if (optionHandlers.hasOwnProperty(option))
  19083. { operation(this, optionHandlers[option])(this, value, old); }
  19084. signal(this, "optionChange", this, option);
  19085. },
  19086. getOption: function(option) {return this.options[option]},
  19087. getDoc: function() {return this.doc},
  19088. addKeyMap: function(map$$1, bottom) {
  19089. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
  19090. },
  19091. removeKeyMap: function(map$$1) {
  19092. var maps = this.state.keyMaps;
  19093. for (var i = 0; i < maps.length; ++i)
  19094. { if (maps[i] == map$$1 || maps[i].name == map$$1) {
  19095. maps.splice(i, 1);
  19096. return true
  19097. } }
  19098. },
  19099. addOverlay: methodOp(function(spec, options) {
  19100. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  19101. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  19102. insertSorted(this.state.overlays,
  19103. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  19104. priority: (options && options.priority) || 0},
  19105. function (overlay) { return overlay.priority; });
  19106. this.state.modeGen++;
  19107. regChange(this);
  19108. }),
  19109. removeOverlay: methodOp(function(spec) {
  19110. var this$1 = this;
  19111. var overlays = this.state.overlays;
  19112. for (var i = 0; i < overlays.length; ++i) {
  19113. var cur = overlays[i].modeSpec;
  19114. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  19115. overlays.splice(i, 1);
  19116. this$1.state.modeGen++;
  19117. regChange(this$1);
  19118. return
  19119. }
  19120. }
  19121. }),
  19122. indentLine: methodOp(function(n, dir, aggressive) {
  19123. if (typeof dir != "string" && typeof dir != "number") {
  19124. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  19125. else { dir = dir ? "add" : "subtract"; }
  19126. }
  19127. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  19128. }),
  19129. indentSelection: methodOp(function(how) {
  19130. var this$1 = this;
  19131. var ranges = this.doc.sel.ranges, end = -1;
  19132. for (var i = 0; i < ranges.length; i++) {
  19133. var range$$1 = ranges[i];
  19134. if (!range$$1.empty()) {
  19135. var from = range$$1.from(), to = range$$1.to();
  19136. var start = Math.max(end, from.line);
  19137. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  19138. for (var j = start; j < end; ++j)
  19139. { indentLine(this$1, j, how); }
  19140. var newRanges = this$1.doc.sel.ranges;
  19141. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  19142. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  19143. } else if (range$$1.head.line > end) {
  19144. indentLine(this$1, range$$1.head.line, how, true);
  19145. end = range$$1.head.line;
  19146. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
  19147. }
  19148. }
  19149. }),
  19150. // Fetch the parser token for a given character. Useful for hacks
  19151. // that want to inspect the mode state (say, for completion).
  19152. getTokenAt: function(pos, precise) {
  19153. return takeToken(this, pos, precise)
  19154. },
  19155. getLineTokens: function(line, precise) {
  19156. return takeToken(this, Pos(line), precise, true)
  19157. },
  19158. getTokenTypeAt: function(pos) {
  19159. pos = clipPos(this.doc, pos);
  19160. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  19161. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  19162. var type;
  19163. if (ch == 0) { type = styles[2]; }
  19164. else { for (;;) {
  19165. var mid = (before + after) >> 1;
  19166. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  19167. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  19168. else { type = styles[mid * 2 + 2]; break }
  19169. } }
  19170. var cut = type ? type.indexOf("overlay ") : -1;
  19171. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  19172. },
  19173. getModeAt: function(pos) {
  19174. var mode = this.doc.mode;
  19175. if (!mode.innerMode) { return mode }
  19176. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  19177. },
  19178. getHelper: function(pos, type) {
  19179. return this.getHelpers(pos, type)[0]
  19180. },
  19181. getHelpers: function(pos, type) {
  19182. var this$1 = this;
  19183. var found = [];
  19184. if (!helpers.hasOwnProperty(type)) { return found }
  19185. var help = helpers[type], mode = this.getModeAt(pos);
  19186. if (typeof mode[type] == "string") {
  19187. if (help[mode[type]]) { found.push(help[mode[type]]); }
  19188. } else if (mode[type]) {
  19189. for (var i = 0; i < mode[type].length; i++) {
  19190. var val = help[mode[type][i]];
  19191. if (val) { found.push(val); }
  19192. }
  19193. } else if (mode.helperType && help[mode.helperType]) {
  19194. found.push(help[mode.helperType]);
  19195. } else if (help[mode.name]) {
  19196. found.push(help[mode.name]);
  19197. }
  19198. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  19199. var cur = help._global[i$1];
  19200. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  19201. { found.push(cur.val); }
  19202. }
  19203. return found
  19204. },
  19205. getStateAfter: function(line, precise) {
  19206. var doc = this.doc;
  19207. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  19208. return getContextBefore(this, line + 1, precise).state
  19209. },
  19210. cursorCoords: function(start, mode) {
  19211. var pos, range$$1 = this.doc.sel.primary();
  19212. if (start == null) { pos = range$$1.head; }
  19213. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  19214. else { pos = start ? range$$1.from() : range$$1.to(); }
  19215. return cursorCoords(this, pos, mode || "page")
  19216. },
  19217. charCoords: function(pos, mode) {
  19218. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  19219. },
  19220. coordsChar: function(coords, mode) {
  19221. coords = fromCoordSystem(this, coords, mode || "page");
  19222. return coordsChar(this, coords.left, coords.top)
  19223. },
  19224. lineAtHeight: function(height, mode) {
  19225. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  19226. return lineAtHeight(this.doc, height + this.display.viewOffset)
  19227. },
  19228. heightAtLine: function(line, mode, includeWidgets) {
  19229. var end = false, lineObj;
  19230. if (typeof line == "number") {
  19231. var last = this.doc.first + this.doc.size - 1;
  19232. if (line < this.doc.first) { line = this.doc.first; }
  19233. else if (line > last) { line = last; end = true; }
  19234. lineObj = getLine(this.doc, line);
  19235. } else {
  19236. lineObj = line;
  19237. }
  19238. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  19239. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  19240. },
  19241. defaultTextHeight: function() { return textHeight(this.display) },
  19242. defaultCharWidth: function() { return charWidth(this.display) },
  19243. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  19244. addWidget: function(pos, node, scroll, vert, horiz) {
  19245. var display = this.display;
  19246. pos = cursorCoords(this, clipPos(this.doc, pos));
  19247. var top = pos.bottom, left = pos.left;
  19248. node.style.position = "absolute";
  19249. node.setAttribute("cm-ignore-events", "true");
  19250. this.display.input.setUneditable(node);
  19251. display.sizer.appendChild(node);
  19252. if (vert == "over") {
  19253. top = pos.top;
  19254. } else if (vert == "above" || vert == "near") {
  19255. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  19256. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  19257. // Default to positioning above (if specified and possible); otherwise default to positioning below
  19258. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  19259. { top = pos.top - node.offsetHeight; }
  19260. else if (pos.bottom + node.offsetHeight <= vspace)
  19261. { top = pos.bottom; }
  19262. if (left + node.offsetWidth > hspace)
  19263. { left = hspace - node.offsetWidth; }
  19264. }
  19265. node.style.top = top + "px";
  19266. node.style.left = node.style.right = "";
  19267. if (horiz == "right") {
  19268. left = display.sizer.clientWidth - node.offsetWidth;
  19269. node.style.right = "0px";
  19270. } else {
  19271. if (horiz == "left") { left = 0; }
  19272. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  19273. node.style.left = left + "px";
  19274. }
  19275. if (scroll)
  19276. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  19277. },
  19278. triggerOnKeyDown: methodOp(onKeyDown),
  19279. triggerOnKeyPress: methodOp(onKeyPress),
  19280. triggerOnKeyUp: onKeyUp,
  19281. triggerOnMouseDown: methodOp(onMouseDown),
  19282. execCommand: function(cmd) {
  19283. if (commands.hasOwnProperty(cmd))
  19284. { return commands[cmd].call(null, this) }
  19285. },
  19286. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  19287. findPosH: function(from, amount, unit, visually) {
  19288. var this$1 = this;
  19289. var dir = 1;
  19290. if (amount < 0) { dir = -1; amount = -amount; }
  19291. var cur = clipPos(this.doc, from);
  19292. for (var i = 0; i < amount; ++i) {
  19293. cur = findPosH(this$1.doc, cur, dir, unit, visually);
  19294. if (cur.hitSide) { break }
  19295. }
  19296. return cur
  19297. },
  19298. moveH: methodOp(function(dir, unit) {
  19299. var this$1 = this;
  19300. this.extendSelectionsBy(function (range$$1) {
  19301. if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
  19302. { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
  19303. else
  19304. { return dir < 0 ? range$$1.from() : range$$1.to() }
  19305. }, sel_move);
  19306. }),
  19307. deleteH: methodOp(function(dir, unit) {
  19308. var sel = this.doc.sel, doc = this.doc;
  19309. if (sel.somethingSelected())
  19310. { doc.replaceSelection("", null, "+delete"); }
  19311. else
  19312. { deleteNearSelection(this, function (range$$1) {
  19313. var other = findPosH(doc, range$$1.head, dir, unit, false);
  19314. return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
  19315. }); }
  19316. }),
  19317. findPosV: function(from, amount, unit, goalColumn) {
  19318. var this$1 = this;
  19319. var dir = 1, x = goalColumn;
  19320. if (amount < 0) { dir = -1; amount = -amount; }
  19321. var cur = clipPos(this.doc, from);
  19322. for (var i = 0; i < amount; ++i) {
  19323. var coords = cursorCoords(this$1, cur, "div");
  19324. if (x == null) { x = coords.left; }
  19325. else { coords.left = x; }
  19326. cur = findPosV(this$1, coords, dir, unit);
  19327. if (cur.hitSide) { break }
  19328. }
  19329. return cur
  19330. },
  19331. moveV: methodOp(function(dir, unit) {
  19332. var this$1 = this;
  19333. var doc = this.doc, goals = [];
  19334. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  19335. doc.extendSelectionsBy(function (range$$1) {
  19336. if (collapse)
  19337. { return dir < 0 ? range$$1.from() : range$$1.to() }
  19338. var headPos = cursorCoords(this$1, range$$1.head, "div");
  19339. if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
  19340. goals.push(headPos.left);
  19341. var pos = findPosV(this$1, headPos, dir, unit);
  19342. if (unit == "page" && range$$1 == doc.sel.primary())
  19343. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  19344. return pos
  19345. }, sel_move);
  19346. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  19347. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  19348. }),
  19349. // Find the word at the given position (as returned by coordsChar).
  19350. findWordAt: function(pos) {
  19351. var doc = this.doc, line = getLine(doc, pos.line).text;
  19352. var start = pos.ch, end = pos.ch;
  19353. if (line) {
  19354. var helper = this.getHelper(pos, "wordChars");
  19355. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  19356. var startChar = line.charAt(start);
  19357. var check = isWordChar(startChar, helper)
  19358. ? function (ch) { return isWordChar(ch, helper); }
  19359. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  19360. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  19361. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  19362. while (end < line.length && check(line.charAt(end))) { ++end; }
  19363. }
  19364. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  19365. },
  19366. toggleOverwrite: function(value) {
  19367. if (value != null && value == this.state.overwrite) { return }
  19368. if (this.state.overwrite = !this.state.overwrite)
  19369. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  19370. else
  19371. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  19372. signal(this, "overwriteToggle", this, this.state.overwrite);
  19373. },
  19374. hasFocus: function() { return this.display.input.getField() == activeElt() },
  19375. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  19376. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  19377. getScrollInfo: function() {
  19378. var scroller = this.display.scroller;
  19379. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  19380. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  19381. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  19382. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  19383. },
  19384. scrollIntoView: methodOp(function(range$$1, margin) {
  19385. if (range$$1 == null) {
  19386. range$$1 = {from: this.doc.sel.primary().head, to: null};
  19387. if (margin == null) { margin = this.options.cursorScrollMargin; }
  19388. } else if (typeof range$$1 == "number") {
  19389. range$$1 = {from: Pos(range$$1, 0), to: null};
  19390. } else if (range$$1.from == null) {
  19391. range$$1 = {from: range$$1, to: null};
  19392. }
  19393. if (!range$$1.to) { range$$1.to = range$$1.from; }
  19394. range$$1.margin = margin || 0;
  19395. if (range$$1.from.line != null) {
  19396. scrollToRange(this, range$$1);
  19397. } else {
  19398. scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
  19399. }
  19400. }),
  19401. setSize: methodOp(function(width, height) {
  19402. var this$1 = this;
  19403. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  19404. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  19405. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  19406. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  19407. var lineNo$$1 = this.display.viewFrom;
  19408. this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
  19409. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  19410. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
  19411. ++lineNo$$1;
  19412. });
  19413. this.curOp.forceUpdate = true;
  19414. signal(this, "refresh", this);
  19415. }),
  19416. operation: function(f){return runInOp(this, f)},
  19417. startOperation: function(){return startOperation(this)},
  19418. endOperation: function(){return endOperation(this)},
  19419. refresh: methodOp(function() {
  19420. var oldHeight = this.display.cachedTextHeight;
  19421. regChange(this);
  19422. this.curOp.forceUpdate = true;
  19423. clearCaches(this);
  19424. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  19425. updateGutterSpace(this.display);
  19426. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  19427. { estimateLineHeights(this); }
  19428. signal(this, "refresh", this);
  19429. }),
  19430. swapDoc: methodOp(function(doc) {
  19431. var old = this.doc;
  19432. old.cm = null;
  19433. // Cancel the current text selection if any (#5821)
  19434. if (this.state.selectingText) { this.state.selectingText(); }
  19435. attachDoc(this, doc);
  19436. clearCaches(this);
  19437. this.display.input.reset();
  19438. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  19439. this.curOp.forceScroll = true;
  19440. signalLater(this, "swapDoc", this, old);
  19441. return old
  19442. }),
  19443. phrase: function(phraseText) {
  19444. var phrases = this.options.phrases;
  19445. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  19446. },
  19447. getInputField: function(){return this.display.input.getField()},
  19448. getWrapperElement: function(){return this.display.wrapper},
  19449. getScrollerElement: function(){return this.display.scroller},
  19450. getGutterElement: function(){return this.display.gutters}
  19451. };
  19452. eventMixin(CodeMirror);
  19453. CodeMirror.registerHelper = function(type, name, value) {
  19454. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  19455. helpers[type][name] = value;
  19456. };
  19457. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  19458. CodeMirror.registerHelper(type, name, value);
  19459. helpers[type]._global.push({pred: predicate, val: value});
  19460. };
  19461. }
  19462. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  19463. // right), unit can be "char", "column" (like char, but doesn't
  19464. // cross line boundaries), "word" (across next word), or "group" (to
  19465. // the start of next group of word or non-word-non-whitespace
  19466. // chars). The visually param controls whether, in right-to-left
  19467. // text, direction 1 means to move towards the next index in the
  19468. // string, or towards the character to the right of the current
  19469. // position. The resulting position will have a hitSide=true
  19470. // property if it reached the end of the document.
  19471. function findPosH(doc, pos, dir, unit, visually) {
  19472. var oldPos = pos;
  19473. var origDir = dir;
  19474. var lineObj = getLine(doc, pos.line);
  19475. function findNextLine() {
  19476. var l = pos.line + dir;
  19477. if (l < doc.first || l >= doc.first + doc.size) { return false }
  19478. pos = new Pos(l, pos.ch, pos.sticky);
  19479. return lineObj = getLine(doc, l)
  19480. }
  19481. function moveOnce(boundToLine) {
  19482. var next;
  19483. if (visually) {
  19484. next = moveVisually(doc.cm, lineObj, pos, dir);
  19485. } else {
  19486. next = moveLogically(lineObj, pos, dir);
  19487. }
  19488. if (next == null) {
  19489. if (!boundToLine && findNextLine())
  19490. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
  19491. else
  19492. { return false }
  19493. } else {
  19494. pos = next;
  19495. }
  19496. return true
  19497. }
  19498. if (unit == "char") {
  19499. moveOnce();
  19500. } else if (unit == "column") {
  19501. moveOnce(true);
  19502. } else if (unit == "word" || unit == "group") {
  19503. var sawType = null, group = unit == "group";
  19504. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  19505. for (var first = true;; first = false) {
  19506. if (dir < 0 && !moveOnce(!first)) { break }
  19507. var cur = lineObj.text.charAt(pos.ch) || "\n";
  19508. var type = isWordChar(cur, helper) ? "w"
  19509. : group && cur == "\n" ? "n"
  19510. : !group || /\s/.test(cur) ? null
  19511. : "p";
  19512. if (group && !first && !type) { type = "s"; }
  19513. if (sawType && sawType != type) {
  19514. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  19515. break
  19516. }
  19517. if (type) { sawType = type; }
  19518. if (dir > 0 && !moveOnce(!first)) { break }
  19519. }
  19520. }
  19521. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  19522. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  19523. return result
  19524. }
  19525. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  19526. // "page" or "line". The resulting position will have a hitSide=true
  19527. // property if it reached the end of the document.
  19528. function findPosV(cm, pos, dir, unit) {
  19529. var doc = cm.doc, x = pos.left, y;
  19530. if (unit == "page") {
  19531. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  19532. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  19533. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  19534. } else if (unit == "line") {
  19535. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  19536. }
  19537. var target;
  19538. for (;;) {
  19539. target = coordsChar(cm, x, y);
  19540. if (!target.outside) { break }
  19541. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  19542. y += dir * 5;
  19543. }
  19544. return target
  19545. }
  19546. // CONTENTEDITABLE INPUT STYLE
  19547. var ContentEditableInput = function(cm) {
  19548. this.cm = cm;
  19549. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  19550. this.polling = new Delayed();
  19551. this.composing = null;
  19552. this.gracePeriod = false;
  19553. this.readDOMTimeout = null;
  19554. };
  19555. ContentEditableInput.prototype.init = function (display) {
  19556. var this$1 = this;
  19557. var input = this, cm = input.cm;
  19558. var div = input.div = display.lineDiv;
  19559. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  19560. on(div, "paste", function (e) {
  19561. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  19562. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  19563. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  19564. });
  19565. on(div, "compositionstart", function (e) {
  19566. this$1.composing = {data: e.data, done: false};
  19567. });
  19568. on(div, "compositionupdate", function (e) {
  19569. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  19570. });
  19571. on(div, "compositionend", function (e) {
  19572. if (this$1.composing) {
  19573. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  19574. this$1.composing.done = true;
  19575. }
  19576. });
  19577. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  19578. on(div, "input", function () {
  19579. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  19580. });
  19581. function onCopyCut(e) {
  19582. if (signalDOMEvent(cm, e)) { return }
  19583. if (cm.somethingSelected()) {
  19584. setLastCopied({lineWise: false, text: cm.getSelections()});
  19585. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  19586. } else if (!cm.options.lineWiseCopyCut) {
  19587. return
  19588. } else {
  19589. var ranges = copyableRanges(cm);
  19590. setLastCopied({lineWise: true, text: ranges.text});
  19591. if (e.type == "cut") {
  19592. cm.operation(function () {
  19593. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  19594. cm.replaceSelection("", null, "cut");
  19595. });
  19596. }
  19597. }
  19598. if (e.clipboardData) {
  19599. e.clipboardData.clearData();
  19600. var content = lastCopied.text.join("\n");
  19601. // iOS exposes the clipboard API, but seems to discard content inserted into it
  19602. e.clipboardData.setData("Text", content);
  19603. if (e.clipboardData.getData("Text") == content) {
  19604. e.preventDefault();
  19605. return
  19606. }
  19607. }
  19608. // Old-fashioned briefly-focus-a-textarea hack
  19609. var kludge = hiddenTextarea(), te = kludge.firstChild;
  19610. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  19611. te.value = lastCopied.text.join("\n");
  19612. var hadFocus = document.activeElement;
  19613. selectInput(te);
  19614. setTimeout(function () {
  19615. cm.display.lineSpace.removeChild(kludge);
  19616. hadFocus.focus();
  19617. if (hadFocus == div) { input.showPrimarySelection(); }
  19618. }, 50);
  19619. }
  19620. on(div, "copy", onCopyCut);
  19621. on(div, "cut", onCopyCut);
  19622. };
  19623. ContentEditableInput.prototype.prepareSelection = function () {
  19624. var result = prepareSelection(this.cm, false);
  19625. result.focus = this.cm.state.focused;
  19626. return result
  19627. };
  19628. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  19629. if (!info || !this.cm.display.view.length) { return }
  19630. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  19631. this.showMultipleSelections(info);
  19632. };
  19633. ContentEditableInput.prototype.getSelection = function () {
  19634. return this.cm.display.wrapper.ownerDocument.getSelection()
  19635. };
  19636. ContentEditableInput.prototype.showPrimarySelection = function () {
  19637. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  19638. var from = prim.from(), to = prim.to();
  19639. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  19640. sel.removeAllRanges();
  19641. return
  19642. }
  19643. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  19644. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  19645. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  19646. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  19647. cmp(maxPos(curAnchor, curFocus), to) == 0)
  19648. { return }
  19649. var view = cm.display.view;
  19650. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  19651. {node: view[0].measure.map[2], offset: 0};
  19652. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  19653. if (!end) {
  19654. var measure = view[view.length - 1].measure;
  19655. var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  19656. end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
  19657. }
  19658. if (!start || !end) {
  19659. sel.removeAllRanges();
  19660. return
  19661. }
  19662. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  19663. try { rng = range(start.node, start.offset, end.offset, end.node); }
  19664. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  19665. if (rng) {
  19666. if (!gecko && cm.state.focused) {
  19667. sel.collapse(start.node, start.offset);
  19668. if (!rng.collapsed) {
  19669. sel.removeAllRanges();
  19670. sel.addRange(rng);
  19671. }
  19672. } else {
  19673. sel.removeAllRanges();
  19674. sel.addRange(rng);
  19675. }
  19676. if (old && sel.anchorNode == null) { sel.addRange(old); }
  19677. else if (gecko) { this.startGracePeriod(); }
  19678. }
  19679. this.rememberSelection();
  19680. };
  19681. ContentEditableInput.prototype.startGracePeriod = function () {
  19682. var this$1 = this;
  19683. clearTimeout(this.gracePeriod);
  19684. this.gracePeriod = setTimeout(function () {
  19685. this$1.gracePeriod = false;
  19686. if (this$1.selectionChanged())
  19687. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  19688. }, 20);
  19689. };
  19690. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  19691. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  19692. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  19693. };
  19694. ContentEditableInput.prototype.rememberSelection = function () {
  19695. var sel = this.getSelection();
  19696. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  19697. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  19698. };
  19699. ContentEditableInput.prototype.selectionInEditor = function () {
  19700. var sel = this.getSelection();
  19701. if (!sel.rangeCount) { return false }
  19702. var node = sel.getRangeAt(0).commonAncestorContainer;
  19703. return contains(this.div, node)
  19704. };
  19705. ContentEditableInput.prototype.focus = function () {
  19706. if (this.cm.options.readOnly != "nocursor") {
  19707. if (!this.selectionInEditor())
  19708. { this.showSelection(this.prepareSelection(), true); }
  19709. this.div.focus();
  19710. }
  19711. };
  19712. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  19713. ContentEditableInput.prototype.getField = function () { return this.div };
  19714. ContentEditableInput.prototype.supportsTouch = function () { return true };
  19715. ContentEditableInput.prototype.receivedFocus = function () {
  19716. var input = this;
  19717. if (this.selectionInEditor())
  19718. { this.pollSelection(); }
  19719. else
  19720. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  19721. function poll() {
  19722. if (input.cm.state.focused) {
  19723. input.pollSelection();
  19724. input.polling.set(input.cm.options.pollInterval, poll);
  19725. }
  19726. }
  19727. this.polling.set(this.cm.options.pollInterval, poll);
  19728. };
  19729. ContentEditableInput.prototype.selectionChanged = function () {
  19730. var sel = this.getSelection();
  19731. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  19732. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  19733. };
  19734. ContentEditableInput.prototype.pollSelection = function () {
  19735. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  19736. var sel = this.getSelection(), cm = this.cm;
  19737. // On Android Chrome (version 56, at least), backspacing into an
  19738. // uneditable block element will put the cursor in that element,
  19739. // and then, because it's not editable, hide the virtual keyboard.
  19740. // Because Android doesn't allow us to actually detect backspace
  19741. // presses in a sane way, this code checks for when that happens
  19742. // and simulates a backspace press in this case.
  19743. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  19744. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  19745. this.blur();
  19746. this.focus();
  19747. return
  19748. }
  19749. if (this.composing) { return }
  19750. this.rememberSelection();
  19751. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  19752. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  19753. if (anchor && head) { runInOp(cm, function () {
  19754. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  19755. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  19756. }); }
  19757. };
  19758. ContentEditableInput.prototype.pollContent = function () {
  19759. if (this.readDOMTimeout != null) {
  19760. clearTimeout(this.readDOMTimeout);
  19761. this.readDOMTimeout = null;
  19762. }
  19763. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  19764. var from = sel.from(), to = sel.to();
  19765. if (from.ch == 0 && from.line > cm.firstLine())
  19766. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  19767. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  19768. { to = Pos(to.line + 1, 0); }
  19769. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  19770. var fromIndex, fromLine, fromNode;
  19771. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  19772. fromLine = lineNo(display.view[0].line);
  19773. fromNode = display.view[0].node;
  19774. } else {
  19775. fromLine = lineNo(display.view[fromIndex].line);
  19776. fromNode = display.view[fromIndex - 1].node.nextSibling;
  19777. }
  19778. var toIndex = findViewIndex(cm, to.line);
  19779. var toLine, toNode;
  19780. if (toIndex == display.view.length - 1) {
  19781. toLine = display.viewTo - 1;
  19782. toNode = display.lineDiv.lastChild;
  19783. } else {
  19784. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  19785. toNode = display.view[toIndex + 1].node.previousSibling;
  19786. }
  19787. if (!fromNode) { return false }
  19788. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  19789. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  19790. while (newText.length > 1 && oldText.length > 1) {
  19791. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  19792. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  19793. else { break }
  19794. }
  19795. var cutFront = 0, cutEnd = 0;
  19796. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  19797. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  19798. { ++cutFront; }
  19799. var newBot = lst(newText), oldBot = lst(oldText);
  19800. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  19801. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  19802. while (cutEnd < maxCutEnd &&
  19803. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  19804. { ++cutEnd; }
  19805. // Try to move start of change to start of selection if ambiguous
  19806. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  19807. while (cutFront && cutFront > from.ch &&
  19808. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  19809. cutFront--;
  19810. cutEnd++;
  19811. }
  19812. }
  19813. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  19814. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  19815. var chFrom = Pos(fromLine, cutFront);
  19816. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  19817. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  19818. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  19819. return true
  19820. }
  19821. };
  19822. ContentEditableInput.prototype.ensurePolled = function () {
  19823. this.forceCompositionEnd();
  19824. };
  19825. ContentEditableInput.prototype.reset = function () {
  19826. this.forceCompositionEnd();
  19827. };
  19828. ContentEditableInput.prototype.forceCompositionEnd = function () {
  19829. if (!this.composing) { return }
  19830. clearTimeout(this.readDOMTimeout);
  19831. this.composing = null;
  19832. this.updateFromDOM();
  19833. this.div.blur();
  19834. this.div.focus();
  19835. };
  19836. ContentEditableInput.prototype.readFromDOMSoon = function () {
  19837. var this$1 = this;
  19838. if (this.readDOMTimeout != null) { return }
  19839. this.readDOMTimeout = setTimeout(function () {
  19840. this$1.readDOMTimeout = null;
  19841. if (this$1.composing) {
  19842. if (this$1.composing.done) { this$1.composing = null; }
  19843. else { return }
  19844. }
  19845. this$1.updateFromDOM();
  19846. }, 80);
  19847. };
  19848. ContentEditableInput.prototype.updateFromDOM = function () {
  19849. var this$1 = this;
  19850. if (this.cm.isReadOnly() || !this.pollContent())
  19851. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  19852. };
  19853. ContentEditableInput.prototype.setUneditable = function (node) {
  19854. node.contentEditable = "false";
  19855. };
  19856. ContentEditableInput.prototype.onKeyPress = function (e) {
  19857. if (e.charCode == 0 || this.composing) { return }
  19858. e.preventDefault();
  19859. if (!this.cm.isReadOnly())
  19860. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  19861. };
  19862. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  19863. this.div.contentEditable = String(val != "nocursor");
  19864. };
  19865. ContentEditableInput.prototype.onContextMenu = function () {};
  19866. ContentEditableInput.prototype.resetPosition = function () {};
  19867. ContentEditableInput.prototype.needsContentAttribute = true;
  19868. function posToDOM(cm, pos) {
  19869. var view = findViewForLine(cm, pos.line);
  19870. if (!view || view.hidden) { return null }
  19871. var line = getLine(cm.doc, pos.line);
  19872. var info = mapFromLineView(view, line, pos.line);
  19873. var order = getOrder(line, cm.doc.direction), side = "left";
  19874. if (order) {
  19875. var partPos = getBidiPartAt(order, pos.ch);
  19876. side = partPos % 2 ? "right" : "left";
  19877. }
  19878. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  19879. result.offset = result.collapse == "right" ? result.end : result.start;
  19880. return result
  19881. }
  19882. function isInGutter(node) {
  19883. for (var scan = node; scan; scan = scan.parentNode)
  19884. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  19885. return false
  19886. }
  19887. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  19888. function domTextBetween(cm, from, to, fromLine, toLine) {
  19889. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  19890. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  19891. function close() {
  19892. if (closing) {
  19893. text += lineSep;
  19894. if (extraLinebreak) { text += lineSep; }
  19895. closing = extraLinebreak = false;
  19896. }
  19897. }
  19898. function addText(str) {
  19899. if (str) {
  19900. close();
  19901. text += str;
  19902. }
  19903. }
  19904. function walk(node) {
  19905. if (node.nodeType == 1) {
  19906. var cmText = node.getAttribute("cm-text");
  19907. if (cmText) {
  19908. addText(cmText);
  19909. return
  19910. }
  19911. var markerID = node.getAttribute("cm-marker"), range$$1;
  19912. if (markerID) {
  19913. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  19914. if (found.length && (range$$1 = found[0].find(0)))
  19915. { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
  19916. return
  19917. }
  19918. if (node.getAttribute("contenteditable") == "false") { return }
  19919. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  19920. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  19921. if (isBlock) { close(); }
  19922. for (var i = 0; i < node.childNodes.length; i++)
  19923. { walk(node.childNodes[i]); }
  19924. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  19925. if (isBlock) { closing = true; }
  19926. } else if (node.nodeType == 3) {
  19927. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  19928. }
  19929. }
  19930. for (;;) {
  19931. walk(from);
  19932. if (from == to) { break }
  19933. from = from.nextSibling;
  19934. extraLinebreak = false;
  19935. }
  19936. return text
  19937. }
  19938. function domToPos(cm, node, offset) {
  19939. var lineNode;
  19940. if (node == cm.display.lineDiv) {
  19941. lineNode = cm.display.lineDiv.childNodes[offset];
  19942. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  19943. node = null; offset = 0;
  19944. } else {
  19945. for (lineNode = node;; lineNode = lineNode.parentNode) {
  19946. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  19947. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  19948. }
  19949. }
  19950. for (var i = 0; i < cm.display.view.length; i++) {
  19951. var lineView = cm.display.view[i];
  19952. if (lineView.node == lineNode)
  19953. { return locateNodeInLineView(lineView, node, offset) }
  19954. }
  19955. }
  19956. function locateNodeInLineView(lineView, node, offset) {
  19957. var wrapper = lineView.text.firstChild, bad = false;
  19958. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  19959. if (node == wrapper) {
  19960. bad = true;
  19961. node = wrapper.childNodes[offset];
  19962. offset = 0;
  19963. if (!node) {
  19964. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  19965. return badPos(Pos(lineNo(line), line.text.length), bad)
  19966. }
  19967. }
  19968. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  19969. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  19970. textNode = node.firstChild;
  19971. if (offset) { offset = textNode.nodeValue.length; }
  19972. }
  19973. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  19974. var measure = lineView.measure, maps = measure.maps;
  19975. function find(textNode, topNode, offset) {
  19976. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  19977. var map$$1 = i < 0 ? measure.map : maps[i];
  19978. for (var j = 0; j < map$$1.length; j += 3) {
  19979. var curNode = map$$1[j + 2];
  19980. if (curNode == textNode || curNode == topNode) {
  19981. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  19982. var ch = map$$1[j] + offset;
  19983. if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
  19984. return Pos(line, ch)
  19985. }
  19986. }
  19987. }
  19988. }
  19989. var found = find(textNode, topNode, offset);
  19990. if (found) { return badPos(found, bad) }
  19991. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  19992. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  19993. found = find(after, after.firstChild, 0);
  19994. if (found)
  19995. { return badPos(Pos(found.line, found.ch - dist), bad) }
  19996. else
  19997. { dist += after.textContent.length; }
  19998. }
  19999. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  20000. found = find(before, before.firstChild, -1);
  20001. if (found)
  20002. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  20003. else
  20004. { dist$1 += before.textContent.length; }
  20005. }
  20006. }
  20007. // TEXTAREA INPUT STYLE
  20008. var TextareaInput = function(cm) {
  20009. this.cm = cm;
  20010. // See input.poll and input.reset
  20011. this.prevInput = "";
  20012. // Flag that indicates whether we expect input to appear real soon
  20013. // now (after some event like 'keypress' or 'input') and are
  20014. // polling intensively.
  20015. this.pollingFast = false;
  20016. // Self-resetting timeout for the poller
  20017. this.polling = new Delayed();
  20018. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  20019. this.hasSelection = false;
  20020. this.composing = null;
  20021. };
  20022. TextareaInput.prototype.init = function (display) {
  20023. var this$1 = this;
  20024. var input = this, cm = this.cm;
  20025. this.createField(display);
  20026. var te = this.textarea;
  20027. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  20028. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  20029. if (ios) { te.style.width = "0px"; }
  20030. on(te, "input", function () {
  20031. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  20032. input.poll();
  20033. });
  20034. on(te, "paste", function (e) {
  20035. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  20036. cm.state.pasteIncoming = +new Date;
  20037. input.fastPoll();
  20038. });
  20039. function prepareCopyCut(e) {
  20040. if (signalDOMEvent(cm, e)) { return }
  20041. if (cm.somethingSelected()) {
  20042. setLastCopied({lineWise: false, text: cm.getSelections()});
  20043. } else if (!cm.options.lineWiseCopyCut) {
  20044. return
  20045. } else {
  20046. var ranges = copyableRanges(cm);
  20047. setLastCopied({lineWise: true, text: ranges.text});
  20048. if (e.type == "cut") {
  20049. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  20050. } else {
  20051. input.prevInput = "";
  20052. te.value = ranges.text.join("\n");
  20053. selectInput(te);
  20054. }
  20055. }
  20056. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  20057. }
  20058. on(te, "cut", prepareCopyCut);
  20059. on(te, "copy", prepareCopyCut);
  20060. on(display.scroller, "paste", function (e) {
  20061. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  20062. if (!te.dispatchEvent) {
  20063. cm.state.pasteIncoming = +new Date;
  20064. input.focus();
  20065. return
  20066. }
  20067. // Pass the `paste` event to the textarea so it's handled by its event listener.
  20068. var event = new Event("paste");
  20069. event.clipboardData = e.clipboardData;
  20070. te.dispatchEvent(event);
  20071. });
  20072. // Prevent normal selection in the editor (we handle our own)
  20073. on(display.lineSpace, "selectstart", function (e) {
  20074. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  20075. });
  20076. on(te, "compositionstart", function () {
  20077. var start = cm.getCursor("from");
  20078. if (input.composing) { input.composing.range.clear(); }
  20079. input.composing = {
  20080. start: start,
  20081. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  20082. };
  20083. });
  20084. on(te, "compositionend", function () {
  20085. if (input.composing) {
  20086. input.poll();
  20087. input.composing.range.clear();
  20088. input.composing = null;
  20089. }
  20090. });
  20091. };
  20092. TextareaInput.prototype.createField = function (_display) {
  20093. // Wraps and hides input textarea
  20094. this.wrapper = hiddenTextarea();
  20095. // The semihidden textarea that is focused when the editor is
  20096. // focused, and receives input.
  20097. this.textarea = this.wrapper.firstChild;
  20098. };
  20099. TextareaInput.prototype.prepareSelection = function () {
  20100. // Redraw the selection and/or cursor
  20101. var cm = this.cm, display = cm.display, doc = cm.doc;
  20102. var result = prepareSelection(cm);
  20103. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  20104. if (cm.options.moveInputWithCursor) {
  20105. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  20106. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  20107. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  20108. headPos.top + lineOff.top - wrapOff.top));
  20109. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  20110. headPos.left + lineOff.left - wrapOff.left));
  20111. }
  20112. return result
  20113. };
  20114. TextareaInput.prototype.showSelection = function (drawn) {
  20115. var cm = this.cm, display = cm.display;
  20116. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  20117. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  20118. if (drawn.teTop != null) {
  20119. this.wrapper.style.top = drawn.teTop + "px";
  20120. this.wrapper.style.left = drawn.teLeft + "px";
  20121. }
  20122. };
  20123. // Reset the input to correspond to the selection (or to be empty,
  20124. // when not typing and nothing is selected)
  20125. TextareaInput.prototype.reset = function (typing) {
  20126. if (this.contextMenuPending || this.composing) { return }
  20127. var cm = this.cm;
  20128. if (cm.somethingSelected()) {
  20129. this.prevInput = "";
  20130. var content = cm.getSelection();
  20131. this.textarea.value = content;
  20132. if (cm.state.focused) { selectInput(this.textarea); }
  20133. if (ie && ie_version >= 9) { this.hasSelection = content; }
  20134. } else if (!typing) {
  20135. this.prevInput = this.textarea.value = "";
  20136. if (ie && ie_version >= 9) { this.hasSelection = null; }
  20137. }
  20138. };
  20139. TextareaInput.prototype.getField = function () { return this.textarea };
  20140. TextareaInput.prototype.supportsTouch = function () { return false };
  20141. TextareaInput.prototype.focus = function () {
  20142. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  20143. try { this.textarea.focus(); }
  20144. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  20145. }
  20146. };
  20147. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  20148. TextareaInput.prototype.resetPosition = function () {
  20149. this.wrapper.style.top = this.wrapper.style.left = 0;
  20150. };
  20151. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  20152. // Poll for input changes, using the normal rate of polling. This
  20153. // runs as long as the editor is focused.
  20154. TextareaInput.prototype.slowPoll = function () {
  20155. var this$1 = this;
  20156. if (this.pollingFast) { return }
  20157. this.polling.set(this.cm.options.pollInterval, function () {
  20158. this$1.poll();
  20159. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  20160. });
  20161. };
  20162. // When an event has just come in that is likely to add or change
  20163. // something in the input textarea, we poll faster, to ensure that
  20164. // the change appears on the screen quickly.
  20165. TextareaInput.prototype.fastPoll = function () {
  20166. var missed = false, input = this;
  20167. input.pollingFast = true;
  20168. function p() {
  20169. var changed = input.poll();
  20170. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  20171. else {input.pollingFast = false; input.slowPoll();}
  20172. }
  20173. input.polling.set(20, p);
  20174. };
  20175. // Read input from the textarea, and update the document to match.
  20176. // When something is selected, it is present in the textarea, and
  20177. // selected (unless it is huge, in which case a placeholder is
  20178. // used). When nothing is selected, the cursor sits after previously
  20179. // seen text (can be empty), which is stored in prevInput (we must
  20180. // not reset the textarea when typing, because that breaks IME).
  20181. TextareaInput.prototype.poll = function () {
  20182. var this$1 = this;
  20183. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  20184. // Since this is called a *lot*, try to bail out as cheaply as
  20185. // possible when it is clear that nothing happened. hasSelection
  20186. // will be the case when there is a lot of text in the textarea,
  20187. // in which case reading its value would be expensive.
  20188. if (this.contextMenuPending || !cm.state.focused ||
  20189. (hasSelection(input) && !prevInput && !this.composing) ||
  20190. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  20191. { return false }
  20192. var text = input.value;
  20193. // If nothing changed, bail.
  20194. if (text == prevInput && !cm.somethingSelected()) { return false }
  20195. // Work around nonsensical selection resetting in IE9/10, and
  20196. // inexplicable appearance of private area unicode characters on
  20197. // some key combos in Mac (#2689).
  20198. if (ie && ie_version >= 9 && this.hasSelection === text ||
  20199. mac && /[\uf700-\uf7ff]/.test(text)) {
  20200. cm.display.input.reset();
  20201. return false
  20202. }
  20203. if (cm.doc.sel == cm.display.selForContextMenu) {
  20204. var first = text.charCodeAt(0);
  20205. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  20206. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  20207. }
  20208. // Find the part of the input that is actually new
  20209. var same = 0, l = Math.min(prevInput.length, text.length);
  20210. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  20211. runInOp(cm, function () {
  20212. applyTextInput(cm, text.slice(same), prevInput.length - same,
  20213. null, this$1.composing ? "*compose" : null);
  20214. // Don't leave long text in the textarea, since it makes further polling slow
  20215. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  20216. else { this$1.prevInput = text; }
  20217. if (this$1.composing) {
  20218. this$1.composing.range.clear();
  20219. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  20220. {className: "CodeMirror-composing"});
  20221. }
  20222. });
  20223. return true
  20224. };
  20225. TextareaInput.prototype.ensurePolled = function () {
  20226. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  20227. };
  20228. TextareaInput.prototype.onKeyPress = function () {
  20229. if (ie && ie_version >= 9) { this.hasSelection = null; }
  20230. this.fastPoll();
  20231. };
  20232. TextareaInput.prototype.onContextMenu = function (e) {
  20233. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  20234. if (input.contextMenuPending) { input.contextMenuPending(); }
  20235. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  20236. if (!pos || presto) { return } // Opera is difficult.
  20237. // Reset the current text selection only if the click is done outside of the selection
  20238. // and 'resetSelectionOnContextMenu' option is true.
  20239. var reset = cm.options.resetSelectionOnContextMenu;
  20240. if (reset && cm.doc.sel.contains(pos) == -1)
  20241. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  20242. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  20243. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  20244. input.wrapper.style.cssText = "position: static";
  20245. te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  20246. var oldScrollY;
  20247. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  20248. display.input.focus();
  20249. if (webkit) { window.scrollTo(null, oldScrollY); }
  20250. display.input.reset();
  20251. // Adds "Select all" to context menu in FF
  20252. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  20253. input.contextMenuPending = rehide;
  20254. display.selForContextMenu = cm.doc.sel;
  20255. clearTimeout(display.detectingSelectAll);
  20256. // Select-all will be greyed out if there's nothing to select, so
  20257. // this adds a zero-width space so that we can later check whether
  20258. // it got selected.
  20259. function prepareSelectAllHack() {
  20260. if (te.selectionStart != null) {
  20261. var selected = cm.somethingSelected();
  20262. var extval = "\u200b" + (selected ? te.value : "");
  20263. te.value = "\u21da"; // Used to catch context-menu undo
  20264. te.value = extval;
  20265. input.prevInput = selected ? "" : "\u200b";
  20266. te.selectionStart = 1; te.selectionEnd = extval.length;
  20267. // Re-set this, in case some other handler touched the
  20268. // selection in the meantime.
  20269. display.selForContextMenu = cm.doc.sel;
  20270. }
  20271. }
  20272. function rehide() {
  20273. if (input.contextMenuPending != rehide) { return }
  20274. input.contextMenuPending = false;
  20275. input.wrapper.style.cssText = oldWrapperCSS;
  20276. te.style.cssText = oldCSS;
  20277. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  20278. // Try to detect the user choosing select-all
  20279. if (te.selectionStart != null) {
  20280. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  20281. var i = 0, poll = function () {
  20282. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  20283. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  20284. operation(cm, selectAll)(cm);
  20285. } else if (i++ < 10) {
  20286. display.detectingSelectAll = setTimeout(poll, 500);
  20287. } else {
  20288. display.selForContextMenu = null;
  20289. display.input.reset();
  20290. }
  20291. };
  20292. display.detectingSelectAll = setTimeout(poll, 200);
  20293. }
  20294. }
  20295. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  20296. if (captureRightClick) {
  20297. e_stop(e);
  20298. var mouseup = function () {
  20299. off(window, "mouseup", mouseup);
  20300. setTimeout(rehide, 20);
  20301. };
  20302. on(window, "mouseup", mouseup);
  20303. } else {
  20304. setTimeout(rehide, 50);
  20305. }
  20306. };
  20307. TextareaInput.prototype.readOnlyChanged = function (val) {
  20308. if (!val) { this.reset(); }
  20309. this.textarea.disabled = val == "nocursor";
  20310. };
  20311. TextareaInput.prototype.setUneditable = function () {};
  20312. TextareaInput.prototype.needsContentAttribute = false;
  20313. function fromTextArea(textarea, options) {
  20314. options = options ? copyObj(options) : {};
  20315. options.value = textarea.value;
  20316. if (!options.tabindex && textarea.tabIndex)
  20317. { options.tabindex = textarea.tabIndex; }
  20318. if (!options.placeholder && textarea.placeholder)
  20319. { options.placeholder = textarea.placeholder; }
  20320. // Set autofocus to true if this textarea is focused, or if it has
  20321. // autofocus and no other element is focused.
  20322. if (options.autofocus == null) {
  20323. var hasFocus = activeElt();
  20324. options.autofocus = hasFocus == textarea ||
  20325. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  20326. }
  20327. function save() {textarea.value = cm.getValue();}
  20328. var realSubmit;
  20329. if (textarea.form) {
  20330. on(textarea.form, "submit", save);
  20331. // Deplorable hack to make the submit method do the right thing.
  20332. if (!options.leaveSubmitMethodAlone) {
  20333. var form = textarea.form;
  20334. realSubmit = form.submit;
  20335. try {
  20336. var wrappedSubmit = form.submit = function () {
  20337. save();
  20338. form.submit = realSubmit;
  20339. form.submit();
  20340. form.submit = wrappedSubmit;
  20341. };
  20342. } catch(e) {}
  20343. }
  20344. }
  20345. options.finishInit = function (cm) {
  20346. cm.save = save;
  20347. cm.getTextArea = function () { return textarea; };
  20348. cm.toTextArea = function () {
  20349. cm.toTextArea = isNaN; // Prevent this from being ran twice
  20350. save();
  20351. textarea.parentNode.removeChild(cm.getWrapperElement());
  20352. textarea.style.display = "";
  20353. if (textarea.form) {
  20354. off(textarea.form, "submit", save);
  20355. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  20356. { textarea.form.submit = realSubmit; }
  20357. }
  20358. };
  20359. };
  20360. textarea.style.display = "none";
  20361. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  20362. options);
  20363. return cm
  20364. }
  20365. function addLegacyProps(CodeMirror) {
  20366. CodeMirror.off = off;
  20367. CodeMirror.on = on;
  20368. CodeMirror.wheelEventPixels = wheelEventPixels;
  20369. CodeMirror.Doc = Doc;
  20370. CodeMirror.splitLines = splitLinesAuto;
  20371. CodeMirror.countColumn = countColumn;
  20372. CodeMirror.findColumn = findColumn;
  20373. CodeMirror.isWordChar = isWordCharBasic;
  20374. CodeMirror.Pass = Pass;
  20375. CodeMirror.signal = signal;
  20376. CodeMirror.Line = Line;
  20377. CodeMirror.changeEnd = changeEnd;
  20378. CodeMirror.scrollbarModel = scrollbarModel;
  20379. CodeMirror.Pos = Pos;
  20380. CodeMirror.cmpPos = cmp;
  20381. CodeMirror.modes = modes;
  20382. CodeMirror.mimeModes = mimeModes;
  20383. CodeMirror.resolveMode = resolveMode;
  20384. CodeMirror.getMode = getMode;
  20385. CodeMirror.modeExtensions = modeExtensions;
  20386. CodeMirror.extendMode = extendMode;
  20387. CodeMirror.copyState = copyState;
  20388. CodeMirror.startState = startState;
  20389. CodeMirror.innerMode = innerMode;
  20390. CodeMirror.commands = commands;
  20391. CodeMirror.keyMap = keyMap;
  20392. CodeMirror.keyName = keyName;
  20393. CodeMirror.isModifierKey = isModifierKey;
  20394. CodeMirror.lookupKey = lookupKey;
  20395. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  20396. CodeMirror.StringStream = StringStream;
  20397. CodeMirror.SharedTextMarker = SharedTextMarker;
  20398. CodeMirror.TextMarker = TextMarker;
  20399. CodeMirror.LineWidget = LineWidget;
  20400. CodeMirror.e_preventDefault = e_preventDefault;
  20401. CodeMirror.e_stopPropagation = e_stopPropagation;
  20402. CodeMirror.e_stop = e_stop;
  20403. CodeMirror.addClass = addClass;
  20404. CodeMirror.contains = contains;
  20405. CodeMirror.rmClass = rmClass;
  20406. CodeMirror.keyNames = keyNames;
  20407. }
  20408. // EDITOR CONSTRUCTOR
  20409. defineOptions(CodeMirror);
  20410. addEditorMethods(CodeMirror);
  20411. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  20412. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  20413. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  20414. { CodeMirror.prototype[prop] = (function(method) {
  20415. return function() {return method.apply(this.doc, arguments)}
  20416. })(Doc.prototype[prop]); } }
  20417. eventMixin(Doc);
  20418. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  20419. // Extra arguments are stored as the mode's dependencies, which is
  20420. // used by (legacy) mechanisms like loadmode.js to automatically
  20421. // load a mode. (Preferred mechanism is the require/define calls.)
  20422. CodeMirror.defineMode = function(name/*, mode, …*/) {
  20423. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  20424. defineMode.apply(this, arguments);
  20425. };
  20426. CodeMirror.defineMIME = defineMIME;
  20427. // Minimal default mode.
  20428. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  20429. CodeMirror.defineMIME("text/plain", "null");
  20430. // EXTENSIONS
  20431. CodeMirror.defineExtension = function (name, func) {
  20432. CodeMirror.prototype[name] = func;
  20433. };
  20434. CodeMirror.defineDocExtension = function (name, func) {
  20435. Doc.prototype[name] = func;
  20436. };
  20437. CodeMirror.fromTextArea = fromTextArea;
  20438. addLegacyProps(CodeMirror);
  20439. CodeMirror.version = "5.49.0";
  20440. return CodeMirror;
  20441. })));
  20442. /***/ }),
  20443. /***/ "./node_modules/decimal.js/decimal.js":
  20444. /*!********************************************!*\
  20445. !*** ./node_modules/decimal.js/decimal.js ***!
  20446. \********************************************/
  20447. /*! no static exports found */
  20448. /***/ (function(module, exports, __webpack_require__) {
  20449. var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalScope) {
  20450. 'use strict';
  20451. /*
  20452. * decimal.js v10.2.0
  20453. * An arbitrary-precision Decimal type for JavaScript.
  20454. * https://github.com/MikeMcl/decimal.js
  20455. * Copyright (c) 2019 Michael Mclaughlin <M8ch88l@gmail.com>
  20456. * MIT Licence
  20457. */
  20458. // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
  20459. // The maximum exponent magnitude.
  20460. // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
  20461. var EXP_LIMIT = 9e15, // 0 to 9e15
  20462. // The limit on the value of `precision`, and on the value of the first argument to
  20463. // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
  20464. MAX_DIGITS = 1e9, // 0 to 1e9
  20465. // Base conversion alphabet.
  20466. NUMERALS = '0123456789abcdef',
  20467. // The natural logarithm of 10 (1025 digits).
  20468. LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
  20469. // Pi (1025 digits).
  20470. PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
  20471. // The initial configuration properties of the Decimal constructor.
  20472. DEFAULTS = {
  20473. // These values must be integers within the stated ranges (inclusive).
  20474. // Most of these values can be changed at run-time using the `Decimal.config` method.
  20475. // The maximum number of significant digits of the result of a calculation or base conversion.
  20476. // E.g. `Decimal.config({ precision: 20 });`
  20477. precision: 20, // 1 to MAX_DIGITS
  20478. // The rounding mode used when rounding to `precision`.
  20479. //
  20480. // ROUND_UP 0 Away from zero.
  20481. // ROUND_DOWN 1 Towards zero.
  20482. // ROUND_CEIL 2 Towards +Infinity.
  20483. // ROUND_FLOOR 3 Towards -Infinity.
  20484. // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
  20485. // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
  20486. // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
  20487. // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
  20488. // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  20489. //
  20490. // E.g.
  20491. // `Decimal.rounding = 4;`
  20492. // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
  20493. rounding: 4, // 0 to 8
  20494. // The modulo mode used when calculating the modulus: a mod n.
  20495. // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
  20496. // The remainder (r) is calculated as: r = a - n * q.
  20497. //
  20498. // UP 0 The remainder is positive if the dividend is negative, else is negative.
  20499. // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).
  20500. // FLOOR 3 The remainder has the same sign as the divisor (Python %).
  20501. // HALF_EVEN 6 The IEEE 754 remainder function.
  20502. // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
  20503. //
  20504. // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
  20505. // division (9) are commonly used for the modulus operation. The other rounding modes can also
  20506. // be used, but they may not give useful results.
  20507. modulo: 1, // 0 to 9
  20508. // The exponent value at and beneath which `toString` returns exponential notation.
  20509. // JavaScript numbers: -7
  20510. toExpNeg: -7, // 0 to -EXP_LIMIT
  20511. // The exponent value at and above which `toString` returns exponential notation.
  20512. // JavaScript numbers: 21
  20513. toExpPos: 21, // 0 to EXP_LIMIT
  20514. // The minimum exponent value, beneath which underflow to zero occurs.
  20515. // JavaScript numbers: -324 (5e-324)
  20516. minE: -EXP_LIMIT, // -1 to -EXP_LIMIT
  20517. // The maximum exponent value, above which overflow to Infinity occurs.
  20518. // JavaScript numbers: 308 (1.7976931348623157e+308)
  20519. maxE: EXP_LIMIT, // 1 to EXP_LIMIT
  20520. // Whether to use cryptographically-secure random number generation, if available.
  20521. crypto: false // true/false
  20522. },
  20523. // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
  20524. Decimal, inexact, noConflict, quadrant,
  20525. external = true,
  20526. decimalError = '[DecimalError] ',
  20527. invalidArgument = decimalError + 'Invalid argument: ',
  20528. precisionLimitExceeded = decimalError + 'Precision limit exceeded',
  20529. cryptoUnavailable = decimalError + 'crypto unavailable',
  20530. mathfloor = Math.floor,
  20531. mathpow = Math.pow,
  20532. isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
  20533. isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
  20534. isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
  20535. isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
  20536. BASE = 1e7,
  20537. LOG_BASE = 7,
  20538. MAX_SAFE_INTEGER = 9007199254740991,
  20539. LN10_PRECISION = LN10.length - 1,
  20540. PI_PRECISION = PI.length - 1,
  20541. // Decimal.prototype object
  20542. P = { name: '[object Decimal]' };
  20543. // Decimal prototype methods
  20544. /*
  20545. * absoluteValue abs
  20546. * ceil
  20547. * comparedTo cmp
  20548. * cosine cos
  20549. * cubeRoot cbrt
  20550. * decimalPlaces dp
  20551. * dividedBy div
  20552. * dividedToIntegerBy divToInt
  20553. * equals eq
  20554. * floor
  20555. * greaterThan gt
  20556. * greaterThanOrEqualTo gte
  20557. * hyperbolicCosine cosh
  20558. * hyperbolicSine sinh
  20559. * hyperbolicTangent tanh
  20560. * inverseCosine acos
  20561. * inverseHyperbolicCosine acosh
  20562. * inverseHyperbolicSine asinh
  20563. * inverseHyperbolicTangent atanh
  20564. * inverseSine asin
  20565. * inverseTangent atan
  20566. * isFinite
  20567. * isInteger isInt
  20568. * isNaN
  20569. * isNegative isNeg
  20570. * isPositive isPos
  20571. * isZero
  20572. * lessThan lt
  20573. * lessThanOrEqualTo lte
  20574. * logarithm log
  20575. * [maximum] [max]
  20576. * [minimum] [min]
  20577. * minus sub
  20578. * modulo mod
  20579. * naturalExponential exp
  20580. * naturalLogarithm ln
  20581. * negated neg
  20582. * plus add
  20583. * precision sd
  20584. * round
  20585. * sine sin
  20586. * squareRoot sqrt
  20587. * tangent tan
  20588. * times mul
  20589. * toBinary
  20590. * toDecimalPlaces toDP
  20591. * toExponential
  20592. * toFixed
  20593. * toFraction
  20594. * toHexadecimal toHex
  20595. * toNearest
  20596. * toNumber
  20597. * toOctal
  20598. * toPower pow
  20599. * toPrecision
  20600. * toSignificantDigits toSD
  20601. * toString
  20602. * truncated trunc
  20603. * valueOf toJSON
  20604. */
  20605. /*
  20606. * Return a new Decimal whose value is the absolute value of this Decimal.
  20607. *
  20608. */
  20609. P.absoluteValue = P.abs = function () {
  20610. var x = new this.constructor(this);
  20611. if (x.s < 0) x.s = 1;
  20612. return finalise(x);
  20613. };
  20614. /*
  20615. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  20616. * direction of positive Infinity.
  20617. *
  20618. */
  20619. P.ceil = function () {
  20620. return finalise(new this.constructor(this), this.e + 1, 2);
  20621. };
  20622. /*
  20623. * Return
  20624. * 1 if the value of this Decimal is greater than the value of `y`,
  20625. * -1 if the value of this Decimal is less than the value of `y`,
  20626. * 0 if they have the same value,
  20627. * NaN if the value of either Decimal is NaN.
  20628. *
  20629. */
  20630. P.comparedTo = P.cmp = function (y) {
  20631. var i, j, xdL, ydL,
  20632. x = this,
  20633. xd = x.d,
  20634. yd = (y = new x.constructor(y)).d,
  20635. xs = x.s,
  20636. ys = y.s;
  20637. // Either NaN or ±Infinity?
  20638. if (!xd || !yd) {
  20639. return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
  20640. }
  20641. // Either zero?
  20642. if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
  20643. // Signs differ?
  20644. if (xs !== ys) return xs;
  20645. // Compare exponents.
  20646. if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
  20647. xdL = xd.length;
  20648. ydL = yd.length;
  20649. // Compare digit by digit.
  20650. for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
  20651. if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
  20652. }
  20653. // Compare lengths.
  20654. return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
  20655. };
  20656. /*
  20657. * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
  20658. *
  20659. * Domain: [-Infinity, Infinity]
  20660. * Range: [-1, 1]
  20661. *
  20662. * cos(0) = 1
  20663. * cos(-0) = 1
  20664. * cos(Infinity) = NaN
  20665. * cos(-Infinity) = NaN
  20666. * cos(NaN) = NaN
  20667. *
  20668. */
  20669. P.cosine = P.cos = function () {
  20670. var pr, rm,
  20671. x = this,
  20672. Ctor = x.constructor;
  20673. if (!x.d) return new Ctor(NaN);
  20674. // cos(0) = cos(-0) = 1
  20675. if (!x.d[0]) return new Ctor(1);
  20676. pr = Ctor.precision;
  20677. rm = Ctor.rounding;
  20678. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  20679. Ctor.rounding = 1;
  20680. x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
  20681. Ctor.precision = pr;
  20682. Ctor.rounding = rm;
  20683. return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
  20684. };
  20685. /*
  20686. *
  20687. * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
  20688. * `precision` significant digits using rounding mode `rounding`.
  20689. *
  20690. * cbrt(0) = 0
  20691. * cbrt(-0) = -0
  20692. * cbrt(1) = 1
  20693. * cbrt(-1) = -1
  20694. * cbrt(N) = N
  20695. * cbrt(-I) = -I
  20696. * cbrt(I) = I
  20697. *
  20698. * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
  20699. *
  20700. */
  20701. P.cubeRoot = P.cbrt = function () {
  20702. var e, m, n, r, rep, s, sd, t, t3, t3plusx,
  20703. x = this,
  20704. Ctor = x.constructor;
  20705. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  20706. external = false;
  20707. // Initial estimate.
  20708. s = x.s * mathpow(x.s * x, 1 / 3);
  20709. // Math.cbrt underflow/overflow?
  20710. // Pass x to Math.pow as integer, then adjust the exponent of the result.
  20711. if (!s || Math.abs(s) == 1 / 0) {
  20712. n = digitsToString(x.d);
  20713. e = x.e;
  20714. // Adjust n exponent so it is a multiple of 3 away from x exponent.
  20715. if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
  20716. s = mathpow(n, 1 / 3);
  20717. // Rarely, e may be one less than the result exponent value.
  20718. e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
  20719. if (s == 1 / 0) {
  20720. n = '5e' + e;
  20721. } else {
  20722. n = s.toExponential();
  20723. n = n.slice(0, n.indexOf('e') + 1) + e;
  20724. }
  20725. r = new Ctor(n);
  20726. r.s = x.s;
  20727. } else {
  20728. r = new Ctor(s.toString());
  20729. }
  20730. sd = (e = Ctor.precision) + 3;
  20731. // Halley's method.
  20732. // TODO? Compare Newton's method.
  20733. for (;;) {
  20734. t = r;
  20735. t3 = t.times(t).times(t);
  20736. t3plusx = t3.plus(x);
  20737. r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
  20738. // TODO? Replace with for-loop and checkRoundingDigits.
  20739. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  20740. n = n.slice(sd - 3, sd + 1);
  20741. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
  20742. // , i.e. approaching a rounding boundary, continue the iteration.
  20743. if (n == '9999' || !rep && n == '4999') {
  20744. // On the first iteration only, check to see if rounding up gives the exact result as the
  20745. // nines may infinitely repeat.
  20746. if (!rep) {
  20747. finalise(t, e + 1, 0);
  20748. if (t.times(t).times(t).eq(x)) {
  20749. r = t;
  20750. break;
  20751. }
  20752. }
  20753. sd += 4;
  20754. rep = 1;
  20755. } else {
  20756. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  20757. // If not, then there are further digits and m will be truthy.
  20758. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  20759. // Truncate to the first rounding digit.
  20760. finalise(r, e + 1, 1);
  20761. m = !r.times(r).times(r).eq(x);
  20762. }
  20763. break;
  20764. }
  20765. }
  20766. }
  20767. external = true;
  20768. return finalise(r, e, Ctor.rounding, m);
  20769. };
  20770. /*
  20771. * Return the number of decimal places of the value of this Decimal.
  20772. *
  20773. */
  20774. P.decimalPlaces = P.dp = function () {
  20775. var w,
  20776. d = this.d,
  20777. n = NaN;
  20778. if (d) {
  20779. w = d.length - 1;
  20780. n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
  20781. // Subtract the number of trailing zeros of the last word.
  20782. w = d[w];
  20783. if (w) for (; w % 10 == 0; w /= 10) n--;
  20784. if (n < 0) n = 0;
  20785. }
  20786. return n;
  20787. };
  20788. /*
  20789. * n / 0 = I
  20790. * n / N = N
  20791. * n / I = 0
  20792. * 0 / n = 0
  20793. * 0 / 0 = N
  20794. * 0 / N = N
  20795. * 0 / I = 0
  20796. * N / n = N
  20797. * N / 0 = N
  20798. * N / N = N
  20799. * N / I = N
  20800. * I / n = I
  20801. * I / 0 = I
  20802. * I / N = N
  20803. * I / I = N
  20804. *
  20805. * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
  20806. * `precision` significant digits using rounding mode `rounding`.
  20807. *
  20808. */
  20809. P.dividedBy = P.div = function (y) {
  20810. return divide(this, new this.constructor(y));
  20811. };
  20812. /*
  20813. * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
  20814. * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
  20815. *
  20816. */
  20817. P.dividedToIntegerBy = P.divToInt = function (y) {
  20818. var x = this,
  20819. Ctor = x.constructor;
  20820. return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
  20821. };
  20822. /*
  20823. * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
  20824. *
  20825. */
  20826. P.equals = P.eq = function (y) {
  20827. return this.cmp(y) === 0;
  20828. };
  20829. /*
  20830. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  20831. * direction of negative Infinity.
  20832. *
  20833. */
  20834. P.floor = function () {
  20835. return finalise(new this.constructor(this), this.e + 1, 3);
  20836. };
  20837. /*
  20838. * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
  20839. * false.
  20840. *
  20841. */
  20842. P.greaterThan = P.gt = function (y) {
  20843. return this.cmp(y) > 0;
  20844. };
  20845. /*
  20846. * Return true if the value of this Decimal is greater than or equal to the value of `y`,
  20847. * otherwise return false.
  20848. *
  20849. */
  20850. P.greaterThanOrEqualTo = P.gte = function (y) {
  20851. var k = this.cmp(y);
  20852. return k == 1 || k === 0;
  20853. };
  20854. /*
  20855. * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
  20856. * Decimal.
  20857. *
  20858. * Domain: [-Infinity, Infinity]
  20859. * Range: [1, Infinity]
  20860. *
  20861. * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
  20862. *
  20863. * cosh(0) = 1
  20864. * cosh(-0) = 1
  20865. * cosh(Infinity) = Infinity
  20866. * cosh(-Infinity) = Infinity
  20867. * cosh(NaN) = NaN
  20868. *
  20869. * x time taken (ms) result
  20870. * 1000 9 9.8503555700852349694e+433
  20871. * 10000 25 4.4034091128314607936e+4342
  20872. * 100000 171 1.4033316802130615897e+43429
  20873. * 1000000 3817 1.5166076984010437725e+434294
  20874. * 10000000 abandoned after 2 minute wait
  20875. *
  20876. * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
  20877. *
  20878. */
  20879. P.hyperbolicCosine = P.cosh = function () {
  20880. var k, n, pr, rm, len,
  20881. x = this,
  20882. Ctor = x.constructor,
  20883. one = new Ctor(1);
  20884. if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
  20885. if (x.isZero()) return one;
  20886. pr = Ctor.precision;
  20887. rm = Ctor.rounding;
  20888. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  20889. Ctor.rounding = 1;
  20890. len = x.d.length;
  20891. // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
  20892. // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
  20893. // Estimate the optimum number of times to use the argument reduction.
  20894. // TODO? Estimation reused from cosine() and may not be optimal here.
  20895. if (len < 32) {
  20896. k = Math.ceil(len / 3);
  20897. n = (1 / tinyPow(4, k)).toString();
  20898. } else {
  20899. k = 16;
  20900. n = '2.3283064365386962890625e-10';
  20901. }
  20902. x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
  20903. // Reverse argument reduction
  20904. var cosh2_x,
  20905. i = k,
  20906. d8 = new Ctor(8);
  20907. for (; i--;) {
  20908. cosh2_x = x.times(x);
  20909. x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
  20910. }
  20911. return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
  20912. };
  20913. /*
  20914. * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
  20915. * Decimal.
  20916. *
  20917. * Domain: [-Infinity, Infinity]
  20918. * Range: [-Infinity, Infinity]
  20919. *
  20920. * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
  20921. *
  20922. * sinh(0) = 0
  20923. * sinh(-0) = -0
  20924. * sinh(Infinity) = Infinity
  20925. * sinh(-Infinity) = -Infinity
  20926. * sinh(NaN) = NaN
  20927. *
  20928. * x time taken (ms)
  20929. * 10 2 ms
  20930. * 100 5 ms
  20931. * 1000 14 ms
  20932. * 10000 82 ms
  20933. * 100000 886 ms 1.4033316802130615897e+43429
  20934. * 200000 2613 ms
  20935. * 300000 5407 ms
  20936. * 400000 8824 ms
  20937. * 500000 13026 ms 8.7080643612718084129e+217146
  20938. * 1000000 48543 ms
  20939. *
  20940. * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
  20941. *
  20942. */
  20943. P.hyperbolicSine = P.sinh = function () {
  20944. var k, pr, rm, len,
  20945. x = this,
  20946. Ctor = x.constructor;
  20947. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  20948. pr = Ctor.precision;
  20949. rm = Ctor.rounding;
  20950. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  20951. Ctor.rounding = 1;
  20952. len = x.d.length;
  20953. if (len < 3) {
  20954. x = taylorSeries(Ctor, 2, x, x, true);
  20955. } else {
  20956. // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
  20957. // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
  20958. // 3 multiplications and 1 addition
  20959. // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
  20960. // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
  20961. // 4 multiplications and 2 additions
  20962. // Estimate the optimum number of times to use the argument reduction.
  20963. k = 1.4 * Math.sqrt(len);
  20964. k = k > 16 ? 16 : k | 0;
  20965. x = x.times(1 / tinyPow(5, k));
  20966. x = taylorSeries(Ctor, 2, x, x, true);
  20967. // Reverse argument reduction
  20968. var sinh2_x,
  20969. d5 = new Ctor(5),
  20970. d16 = new Ctor(16),
  20971. d20 = new Ctor(20);
  20972. for (; k--;) {
  20973. sinh2_x = x.times(x);
  20974. x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
  20975. }
  20976. }
  20977. Ctor.precision = pr;
  20978. Ctor.rounding = rm;
  20979. return finalise(x, pr, rm, true);
  20980. };
  20981. /*
  20982. * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
  20983. * Decimal.
  20984. *
  20985. * Domain: [-Infinity, Infinity]
  20986. * Range: [-1, 1]
  20987. *
  20988. * tanh(x) = sinh(x) / cosh(x)
  20989. *
  20990. * tanh(0) = 0
  20991. * tanh(-0) = -0
  20992. * tanh(Infinity) = 1
  20993. * tanh(-Infinity) = -1
  20994. * tanh(NaN) = NaN
  20995. *
  20996. */
  20997. P.hyperbolicTangent = P.tanh = function () {
  20998. var pr, rm,
  20999. x = this,
  21000. Ctor = x.constructor;
  21001. if (!x.isFinite()) return new Ctor(x.s);
  21002. if (x.isZero()) return new Ctor(x);
  21003. pr = Ctor.precision;
  21004. rm = Ctor.rounding;
  21005. Ctor.precision = pr + 7;
  21006. Ctor.rounding = 1;
  21007. return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
  21008. };
  21009. /*
  21010. * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
  21011. * this Decimal.
  21012. *
  21013. * Domain: [-1, 1]
  21014. * Range: [0, pi]
  21015. *
  21016. * acos(x) = pi/2 - asin(x)
  21017. *
  21018. * acos(0) = pi/2
  21019. * acos(-0) = pi/2
  21020. * acos(1) = 0
  21021. * acos(-1) = pi
  21022. * acos(1/2) = pi/3
  21023. * acos(-1/2) = 2*pi/3
  21024. * acos(|x| > 1) = NaN
  21025. * acos(NaN) = NaN
  21026. *
  21027. */
  21028. P.inverseCosine = P.acos = function () {
  21029. var halfPi,
  21030. x = this,
  21031. Ctor = x.constructor,
  21032. k = x.abs().cmp(1),
  21033. pr = Ctor.precision,
  21034. rm = Ctor.rounding;
  21035. if (k !== -1) {
  21036. return k === 0
  21037. // |x| is 1
  21038. ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
  21039. // |x| > 1 or x is NaN
  21040. : new Ctor(NaN);
  21041. }
  21042. if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
  21043. // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
  21044. Ctor.precision = pr + 6;
  21045. Ctor.rounding = 1;
  21046. x = x.asin();
  21047. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  21048. Ctor.precision = pr;
  21049. Ctor.rounding = rm;
  21050. return halfPi.minus(x);
  21051. };
  21052. /*
  21053. * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
  21054. * value of this Decimal.
  21055. *
  21056. * Domain: [1, Infinity]
  21057. * Range: [0, Infinity]
  21058. *
  21059. * acosh(x) = ln(x + sqrt(x^2 - 1))
  21060. *
  21061. * acosh(x < 1) = NaN
  21062. * acosh(NaN) = NaN
  21063. * acosh(Infinity) = Infinity
  21064. * acosh(-Infinity) = NaN
  21065. * acosh(0) = NaN
  21066. * acosh(-0) = NaN
  21067. * acosh(1) = 0
  21068. * acosh(-1) = NaN
  21069. *
  21070. */
  21071. P.inverseHyperbolicCosine = P.acosh = function () {
  21072. var pr, rm,
  21073. x = this,
  21074. Ctor = x.constructor;
  21075. if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
  21076. if (!x.isFinite()) return new Ctor(x);
  21077. pr = Ctor.precision;
  21078. rm = Ctor.rounding;
  21079. Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
  21080. Ctor.rounding = 1;
  21081. external = false;
  21082. x = x.times(x).minus(1).sqrt().plus(x);
  21083. external = true;
  21084. Ctor.precision = pr;
  21085. Ctor.rounding = rm;
  21086. return x.ln();
  21087. };
  21088. /*
  21089. * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
  21090. * of this Decimal.
  21091. *
  21092. * Domain: [-Infinity, Infinity]
  21093. * Range: [-Infinity, Infinity]
  21094. *
  21095. * asinh(x) = ln(x + sqrt(x^2 + 1))
  21096. *
  21097. * asinh(NaN) = NaN
  21098. * asinh(Infinity) = Infinity
  21099. * asinh(-Infinity) = -Infinity
  21100. * asinh(0) = 0
  21101. * asinh(-0) = -0
  21102. *
  21103. */
  21104. P.inverseHyperbolicSine = P.asinh = function () {
  21105. var pr, rm,
  21106. x = this,
  21107. Ctor = x.constructor;
  21108. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  21109. pr = Ctor.precision;
  21110. rm = Ctor.rounding;
  21111. Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
  21112. Ctor.rounding = 1;
  21113. external = false;
  21114. x = x.times(x).plus(1).sqrt().plus(x);
  21115. external = true;
  21116. Ctor.precision = pr;
  21117. Ctor.rounding = rm;
  21118. return x.ln();
  21119. };
  21120. /*
  21121. * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
  21122. * value of this Decimal.
  21123. *
  21124. * Domain: [-1, 1]
  21125. * Range: [-Infinity, Infinity]
  21126. *
  21127. * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
  21128. *
  21129. * atanh(|x| > 1) = NaN
  21130. * atanh(NaN) = NaN
  21131. * atanh(Infinity) = NaN
  21132. * atanh(-Infinity) = NaN
  21133. * atanh(0) = 0
  21134. * atanh(-0) = -0
  21135. * atanh(1) = Infinity
  21136. * atanh(-1) = -Infinity
  21137. *
  21138. */
  21139. P.inverseHyperbolicTangent = P.atanh = function () {
  21140. var pr, rm, wpr, xsd,
  21141. x = this,
  21142. Ctor = x.constructor;
  21143. if (!x.isFinite()) return new Ctor(NaN);
  21144. if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
  21145. pr = Ctor.precision;
  21146. rm = Ctor.rounding;
  21147. xsd = x.sd();
  21148. if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
  21149. Ctor.precision = wpr = xsd - x.e;
  21150. x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
  21151. Ctor.precision = pr + 4;
  21152. Ctor.rounding = 1;
  21153. x = x.ln();
  21154. Ctor.precision = pr;
  21155. Ctor.rounding = rm;
  21156. return x.times(0.5);
  21157. };
  21158. /*
  21159. * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
  21160. * Decimal.
  21161. *
  21162. * Domain: [-Infinity, Infinity]
  21163. * Range: [-pi/2, pi/2]
  21164. *
  21165. * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
  21166. *
  21167. * asin(0) = 0
  21168. * asin(-0) = -0
  21169. * asin(1/2) = pi/6
  21170. * asin(-1/2) = -pi/6
  21171. * asin(1) = pi/2
  21172. * asin(-1) = -pi/2
  21173. * asin(|x| > 1) = NaN
  21174. * asin(NaN) = NaN
  21175. *
  21176. * TODO? Compare performance of Taylor series.
  21177. *
  21178. */
  21179. P.inverseSine = P.asin = function () {
  21180. var halfPi, k,
  21181. pr, rm,
  21182. x = this,
  21183. Ctor = x.constructor;
  21184. if (x.isZero()) return new Ctor(x);
  21185. k = x.abs().cmp(1);
  21186. pr = Ctor.precision;
  21187. rm = Ctor.rounding;
  21188. if (k !== -1) {
  21189. // |x| is 1
  21190. if (k === 0) {
  21191. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  21192. halfPi.s = x.s;
  21193. return halfPi;
  21194. }
  21195. // |x| > 1 or x is NaN
  21196. return new Ctor(NaN);
  21197. }
  21198. // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
  21199. Ctor.precision = pr + 6;
  21200. Ctor.rounding = 1;
  21201. x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
  21202. Ctor.precision = pr;
  21203. Ctor.rounding = rm;
  21204. return x.times(2);
  21205. };
  21206. /*
  21207. * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
  21208. * of this Decimal.
  21209. *
  21210. * Domain: [-Infinity, Infinity]
  21211. * Range: [-pi/2, pi/2]
  21212. *
  21213. * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  21214. *
  21215. * atan(0) = 0
  21216. * atan(-0) = -0
  21217. * atan(1) = pi/4
  21218. * atan(-1) = -pi/4
  21219. * atan(Infinity) = pi/2
  21220. * atan(-Infinity) = -pi/2
  21221. * atan(NaN) = NaN
  21222. *
  21223. */
  21224. P.inverseTangent = P.atan = function () {
  21225. var i, j, k, n, px, t, r, wpr, x2,
  21226. x = this,
  21227. Ctor = x.constructor,
  21228. pr = Ctor.precision,
  21229. rm = Ctor.rounding;
  21230. if (!x.isFinite()) {
  21231. if (!x.s) return new Ctor(NaN);
  21232. if (pr + 4 <= PI_PRECISION) {
  21233. r = getPi(Ctor, pr + 4, rm).times(0.5);
  21234. r.s = x.s;
  21235. return r;
  21236. }
  21237. } else if (x.isZero()) {
  21238. return new Ctor(x);
  21239. } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
  21240. r = getPi(Ctor, pr + 4, rm).times(0.25);
  21241. r.s = x.s;
  21242. return r;
  21243. }
  21244. Ctor.precision = wpr = pr + 10;
  21245. Ctor.rounding = 1;
  21246. // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
  21247. // Argument reduction
  21248. // Ensure |x| < 0.42
  21249. // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
  21250. k = Math.min(28, wpr / LOG_BASE + 2 | 0);
  21251. for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
  21252. external = false;
  21253. j = Math.ceil(wpr / LOG_BASE);
  21254. n = 1;
  21255. x2 = x.times(x);
  21256. r = new Ctor(x);
  21257. px = x;
  21258. // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  21259. for (; i !== -1;) {
  21260. px = px.times(x2);
  21261. t = r.minus(px.div(n += 2));
  21262. px = px.times(x2);
  21263. r = t.plus(px.div(n += 2));
  21264. if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
  21265. }
  21266. if (k) r = r.times(2 << (k - 1));
  21267. external = true;
  21268. return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
  21269. };
  21270. /*
  21271. * Return true if the value of this Decimal is a finite number, otherwise return false.
  21272. *
  21273. */
  21274. P.isFinite = function () {
  21275. return !!this.d;
  21276. };
  21277. /*
  21278. * Return true if the value of this Decimal is an integer, otherwise return false.
  21279. *
  21280. */
  21281. P.isInteger = P.isInt = function () {
  21282. return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
  21283. };
  21284. /*
  21285. * Return true if the value of this Decimal is NaN, otherwise return false.
  21286. *
  21287. */
  21288. P.isNaN = function () {
  21289. return !this.s;
  21290. };
  21291. /*
  21292. * Return true if the value of this Decimal is negative, otherwise return false.
  21293. *
  21294. */
  21295. P.isNegative = P.isNeg = function () {
  21296. return this.s < 0;
  21297. };
  21298. /*
  21299. * Return true if the value of this Decimal is positive, otherwise return false.
  21300. *
  21301. */
  21302. P.isPositive = P.isPos = function () {
  21303. return this.s > 0;
  21304. };
  21305. /*
  21306. * Return true if the value of this Decimal is 0 or -0, otherwise return false.
  21307. *
  21308. */
  21309. P.isZero = function () {
  21310. return !!this.d && this.d[0] === 0;
  21311. };
  21312. /*
  21313. * Return true if the value of this Decimal is less than `y`, otherwise return false.
  21314. *
  21315. */
  21316. P.lessThan = P.lt = function (y) {
  21317. return this.cmp(y) < 0;
  21318. };
  21319. /*
  21320. * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
  21321. *
  21322. */
  21323. P.lessThanOrEqualTo = P.lte = function (y) {
  21324. return this.cmp(y) < 1;
  21325. };
  21326. /*
  21327. * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
  21328. * significant digits using rounding mode `rounding`.
  21329. *
  21330. * If no base is specified, return log[10](arg).
  21331. *
  21332. * log[base](arg) = ln(arg) / ln(base)
  21333. *
  21334. * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
  21335. * otherwise:
  21336. *
  21337. * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
  21338. * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
  21339. * between the result and the correctly rounded result will be one ulp (unit in the last place).
  21340. *
  21341. * log[-b](a) = NaN
  21342. * log[0](a) = NaN
  21343. * log[1](a) = NaN
  21344. * log[NaN](a) = NaN
  21345. * log[Infinity](a) = NaN
  21346. * log[b](0) = -Infinity
  21347. * log[b](-0) = -Infinity
  21348. * log[b](-a) = NaN
  21349. * log[b](1) = 0
  21350. * log[b](Infinity) = Infinity
  21351. * log[b](NaN) = NaN
  21352. *
  21353. * [base] {number|string|Decimal} The base of the logarithm.
  21354. *
  21355. */
  21356. P.logarithm = P.log = function (base) {
  21357. var isBase10, d, denominator, k, inf, num, sd, r,
  21358. arg = this,
  21359. Ctor = arg.constructor,
  21360. pr = Ctor.precision,
  21361. rm = Ctor.rounding,
  21362. guard = 5;
  21363. // Default base is 10.
  21364. if (base == null) {
  21365. base = new Ctor(10);
  21366. isBase10 = true;
  21367. } else {
  21368. base = new Ctor(base);
  21369. d = base.d;
  21370. // Return NaN if base is negative, or non-finite, or is 0 or 1.
  21371. if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
  21372. isBase10 = base.eq(10);
  21373. }
  21374. d = arg.d;
  21375. // Is arg negative, non-finite, 0 or 1?
  21376. if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
  21377. return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
  21378. }
  21379. // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
  21380. // integer power of 10.
  21381. if (isBase10) {
  21382. if (d.length > 1) {
  21383. inf = true;
  21384. } else {
  21385. for (k = d[0]; k % 10 === 0;) k /= 10;
  21386. inf = k !== 1;
  21387. }
  21388. }
  21389. external = false;
  21390. sd = pr + guard;
  21391. num = naturalLogarithm(arg, sd);
  21392. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  21393. // The result will have 5 rounding digits.
  21394. r = divide(num, denominator, sd, 1);
  21395. // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
  21396. // calculate 10 further digits.
  21397. //
  21398. // If the result is known to have an infinite decimal expansion, repeat this until it is clear
  21399. // that the result is above or below the boundary. Otherwise, if after calculating the 10
  21400. // further digits, the last 14 are nines, round up and assume the result is exact.
  21401. // Also assume the result is exact if the last 14 are zero.
  21402. //
  21403. // Example of a result that will be incorrectly rounded:
  21404. // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
  21405. // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
  21406. // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
  21407. // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
  21408. // place is still 2.6.
  21409. if (checkRoundingDigits(r.d, k = pr, rm)) {
  21410. do {
  21411. sd += 10;
  21412. num = naturalLogarithm(arg, sd);
  21413. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  21414. r = divide(num, denominator, sd, 1);
  21415. if (!inf) {
  21416. // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
  21417. if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
  21418. r = finalise(r, pr + 1, 0);
  21419. }
  21420. break;
  21421. }
  21422. } while (checkRoundingDigits(r.d, k += 10, rm));
  21423. }
  21424. external = true;
  21425. return finalise(r, pr, rm);
  21426. };
  21427. /*
  21428. * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
  21429. *
  21430. * arguments {number|string|Decimal}
  21431. *
  21432. P.max = function () {
  21433. Array.prototype.push.call(arguments, this);
  21434. return maxOrMin(this.constructor, arguments, 'lt');
  21435. };
  21436. */
  21437. /*
  21438. * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
  21439. *
  21440. * arguments {number|string|Decimal}
  21441. *
  21442. P.min = function () {
  21443. Array.prototype.push.call(arguments, this);
  21444. return maxOrMin(this.constructor, arguments, 'gt');
  21445. };
  21446. */
  21447. /*
  21448. * n - 0 = n
  21449. * n - N = N
  21450. * n - I = -I
  21451. * 0 - n = -n
  21452. * 0 - 0 = 0
  21453. * 0 - N = N
  21454. * 0 - I = -I
  21455. * N - n = N
  21456. * N - 0 = N
  21457. * N - N = N
  21458. * N - I = N
  21459. * I - n = I
  21460. * I - 0 = I
  21461. * I - N = N
  21462. * I - I = N
  21463. *
  21464. * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
  21465. * significant digits using rounding mode `rounding`.
  21466. *
  21467. */
  21468. P.minus = P.sub = function (y) {
  21469. var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
  21470. x = this,
  21471. Ctor = x.constructor;
  21472. y = new Ctor(y);
  21473. // If either is not finite...
  21474. if (!x.d || !y.d) {
  21475. // Return NaN if either is NaN.
  21476. if (!x.s || !y.s) y = new Ctor(NaN);
  21477. // Return y negated if x is finite and y is ±Infinity.
  21478. else if (x.d) y.s = -y.s;
  21479. // Return x if y is finite and x is ±Infinity.
  21480. // Return x if both are ±Infinity with different signs.
  21481. // Return NaN if both are ±Infinity with the same sign.
  21482. else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
  21483. return y;
  21484. }
  21485. // If signs differ...
  21486. if (x.s != y.s) {
  21487. y.s = -y.s;
  21488. return x.plus(y);
  21489. }
  21490. xd = x.d;
  21491. yd = y.d;
  21492. pr = Ctor.precision;
  21493. rm = Ctor.rounding;
  21494. // If either is zero...
  21495. if (!xd[0] || !yd[0]) {
  21496. // Return y negated if x is zero and y is non-zero.
  21497. if (yd[0]) y.s = -y.s;
  21498. // Return x if y is zero and x is non-zero.
  21499. else if (xd[0]) y = new Ctor(x);
  21500. // Return zero if both are zero.
  21501. // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
  21502. else return new Ctor(rm === 3 ? -0 : 0);
  21503. return external ? finalise(y, pr, rm) : y;
  21504. }
  21505. // x and y are finite, non-zero numbers with the same sign.
  21506. // Calculate base 1e7 exponents.
  21507. e = mathfloor(y.e / LOG_BASE);
  21508. xe = mathfloor(x.e / LOG_BASE);
  21509. xd = xd.slice();
  21510. k = xe - e;
  21511. // If base 1e7 exponents differ...
  21512. if (k) {
  21513. xLTy = k < 0;
  21514. if (xLTy) {
  21515. d = xd;
  21516. k = -k;
  21517. len = yd.length;
  21518. } else {
  21519. d = yd;
  21520. e = xe;
  21521. len = xd.length;
  21522. }
  21523. // Numbers with massively different exponents would result in a very high number of
  21524. // zeros needing to be prepended, but this can be avoided while still ensuring correct
  21525. // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
  21526. i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
  21527. if (k > i) {
  21528. k = i;
  21529. d.length = 1;
  21530. }
  21531. // Prepend zeros to equalise exponents.
  21532. d.reverse();
  21533. for (i = k; i--;) d.push(0);
  21534. d.reverse();
  21535. // Base 1e7 exponents equal.
  21536. } else {
  21537. // Check digits to determine which is the bigger number.
  21538. i = xd.length;
  21539. len = yd.length;
  21540. xLTy = i < len;
  21541. if (xLTy) len = i;
  21542. for (i = 0; i < len; i++) {
  21543. if (xd[i] != yd[i]) {
  21544. xLTy = xd[i] < yd[i];
  21545. break;
  21546. }
  21547. }
  21548. k = 0;
  21549. }
  21550. if (xLTy) {
  21551. d = xd;
  21552. xd = yd;
  21553. yd = d;
  21554. y.s = -y.s;
  21555. }
  21556. len = xd.length;
  21557. // Append zeros to `xd` if shorter.
  21558. // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
  21559. for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
  21560. // Subtract yd from xd.
  21561. for (i = yd.length; i > k;) {
  21562. if (xd[--i] < yd[i]) {
  21563. for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
  21564. --xd[j];
  21565. xd[i] += BASE;
  21566. }
  21567. xd[i] -= yd[i];
  21568. }
  21569. // Remove trailing zeros.
  21570. for (; xd[--len] === 0;) xd.pop();
  21571. // Remove leading zeros and adjust exponent accordingly.
  21572. for (; xd[0] === 0; xd.shift()) --e;
  21573. // Zero?
  21574. if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
  21575. y.d = xd;
  21576. y.e = getBase10Exponent(xd, e);
  21577. return external ? finalise(y, pr, rm) : y;
  21578. };
  21579. /*
  21580. * n % 0 = N
  21581. * n % N = N
  21582. * n % I = n
  21583. * 0 % n = 0
  21584. * -0 % n = -0
  21585. * 0 % 0 = N
  21586. * 0 % N = N
  21587. * 0 % I = 0
  21588. * N % n = N
  21589. * N % 0 = N
  21590. * N % N = N
  21591. * N % I = N
  21592. * I % n = N
  21593. * I % 0 = N
  21594. * I % N = N
  21595. * I % I = N
  21596. *
  21597. * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
  21598. * `precision` significant digits using rounding mode `rounding`.
  21599. *
  21600. * The result depends on the modulo mode.
  21601. *
  21602. */
  21603. P.modulo = P.mod = function (y) {
  21604. var q,
  21605. x = this,
  21606. Ctor = x.constructor;
  21607. y = new Ctor(y);
  21608. // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
  21609. if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
  21610. // Return x if y is ±Infinity or x is ±0.
  21611. if (!y.d || x.d && !x.d[0]) {
  21612. return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
  21613. }
  21614. // Prevent rounding of intermediate calculations.
  21615. external = false;
  21616. if (Ctor.modulo == 9) {
  21617. // Euclidian division: q = sign(y) * floor(x / abs(y))
  21618. // result = x - q * y where 0 <= result < abs(y)
  21619. q = divide(x, y.abs(), 0, 3, 1);
  21620. q.s *= y.s;
  21621. } else {
  21622. q = divide(x, y, 0, Ctor.modulo, 1);
  21623. }
  21624. q = q.times(y);
  21625. external = true;
  21626. return x.minus(q);
  21627. };
  21628. /*
  21629. * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
  21630. * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
  21631. * significant digits using rounding mode `rounding`.
  21632. *
  21633. */
  21634. P.naturalExponential = P.exp = function () {
  21635. return naturalExponential(this);
  21636. };
  21637. /*
  21638. * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
  21639. * rounded to `precision` significant digits using rounding mode `rounding`.
  21640. *
  21641. */
  21642. P.naturalLogarithm = P.ln = function () {
  21643. return naturalLogarithm(this);
  21644. };
  21645. /*
  21646. * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
  21647. * -1.
  21648. *
  21649. */
  21650. P.negated = P.neg = function () {
  21651. var x = new this.constructor(this);
  21652. x.s = -x.s;
  21653. return finalise(x);
  21654. };
  21655. /*
  21656. * n + 0 = n
  21657. * n + N = N
  21658. * n + I = I
  21659. * 0 + n = n
  21660. * 0 + 0 = 0
  21661. * 0 + N = N
  21662. * 0 + I = I
  21663. * N + n = N
  21664. * N + 0 = N
  21665. * N + N = N
  21666. * N + I = N
  21667. * I + n = I
  21668. * I + 0 = I
  21669. * I + N = N
  21670. * I + I = I
  21671. *
  21672. * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
  21673. * significant digits using rounding mode `rounding`.
  21674. *
  21675. */
  21676. P.plus = P.add = function (y) {
  21677. var carry, d, e, i, k, len, pr, rm, xd, yd,
  21678. x = this,
  21679. Ctor = x.constructor;
  21680. y = new Ctor(y);
  21681. // If either is not finite...
  21682. if (!x.d || !y.d) {
  21683. // Return NaN if either is NaN.
  21684. if (!x.s || !y.s) y = new Ctor(NaN);
  21685. // Return x if y is finite and x is ±Infinity.
  21686. // Return x if both are ±Infinity with the same sign.
  21687. // Return NaN if both are ±Infinity with different signs.
  21688. // Return y if x is finite and y is ±Infinity.
  21689. else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
  21690. return y;
  21691. }
  21692. // If signs differ...
  21693. if (x.s != y.s) {
  21694. y.s = -y.s;
  21695. return x.minus(y);
  21696. }
  21697. xd = x.d;
  21698. yd = y.d;
  21699. pr = Ctor.precision;
  21700. rm = Ctor.rounding;
  21701. // If either is zero...
  21702. if (!xd[0] || !yd[0]) {
  21703. // Return x if y is zero.
  21704. // Return y if y is non-zero.
  21705. if (!yd[0]) y = new Ctor(x);
  21706. return external ? finalise(y, pr, rm) : y;
  21707. }
  21708. // x and y are finite, non-zero numbers with the same sign.
  21709. // Calculate base 1e7 exponents.
  21710. k = mathfloor(x.e / LOG_BASE);
  21711. e = mathfloor(y.e / LOG_BASE);
  21712. xd = xd.slice();
  21713. i = k - e;
  21714. // If base 1e7 exponents differ...
  21715. if (i) {
  21716. if (i < 0) {
  21717. d = xd;
  21718. i = -i;
  21719. len = yd.length;
  21720. } else {
  21721. d = yd;
  21722. e = k;
  21723. len = xd.length;
  21724. }
  21725. // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
  21726. k = Math.ceil(pr / LOG_BASE);
  21727. len = k > len ? k + 1 : len + 1;
  21728. if (i > len) {
  21729. i = len;
  21730. d.length = 1;
  21731. }
  21732. // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
  21733. d.reverse();
  21734. for (; i--;) d.push(0);
  21735. d.reverse();
  21736. }
  21737. len = xd.length;
  21738. i = yd.length;
  21739. // If yd is longer than xd, swap xd and yd so xd points to the longer array.
  21740. if (len - i < 0) {
  21741. i = len;
  21742. d = yd;
  21743. yd = xd;
  21744. xd = d;
  21745. }
  21746. // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
  21747. for (carry = 0; i;) {
  21748. carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
  21749. xd[i] %= BASE;
  21750. }
  21751. if (carry) {
  21752. xd.unshift(carry);
  21753. ++e;
  21754. }
  21755. // Remove trailing zeros.
  21756. // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  21757. for (len = xd.length; xd[--len] == 0;) xd.pop();
  21758. y.d = xd;
  21759. y.e = getBase10Exponent(xd, e);
  21760. return external ? finalise(y, pr, rm) : y;
  21761. };
  21762. /*
  21763. * Return the number of significant digits of the value of this Decimal.
  21764. *
  21765. * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
  21766. *
  21767. */
  21768. P.precision = P.sd = function (z) {
  21769. var k,
  21770. x = this;
  21771. if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
  21772. if (x.d) {
  21773. k = getPrecision(x.d);
  21774. if (z && x.e + 1 > k) k = x.e + 1;
  21775. } else {
  21776. k = NaN;
  21777. }
  21778. return k;
  21779. };
  21780. /*
  21781. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
  21782. * rounding mode `rounding`.
  21783. *
  21784. */
  21785. P.round = function () {
  21786. var x = this,
  21787. Ctor = x.constructor;
  21788. return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
  21789. };
  21790. /*
  21791. * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
  21792. *
  21793. * Domain: [-Infinity, Infinity]
  21794. * Range: [-1, 1]
  21795. *
  21796. * sin(x) = x - x^3/3! + x^5/5! - ...
  21797. *
  21798. * sin(0) = 0
  21799. * sin(-0) = -0
  21800. * sin(Infinity) = NaN
  21801. * sin(-Infinity) = NaN
  21802. * sin(NaN) = NaN
  21803. *
  21804. */
  21805. P.sine = P.sin = function () {
  21806. var pr, rm,
  21807. x = this,
  21808. Ctor = x.constructor;
  21809. if (!x.isFinite()) return new Ctor(NaN);
  21810. if (x.isZero()) return new Ctor(x);
  21811. pr = Ctor.precision;
  21812. rm = Ctor.rounding;
  21813. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  21814. Ctor.rounding = 1;
  21815. x = sine(Ctor, toLessThanHalfPi(Ctor, x));
  21816. Ctor.precision = pr;
  21817. Ctor.rounding = rm;
  21818. return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
  21819. };
  21820. /*
  21821. * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
  21822. * significant digits using rounding mode `rounding`.
  21823. *
  21824. * sqrt(-n) = N
  21825. * sqrt(N) = N
  21826. * sqrt(-I) = N
  21827. * sqrt(I) = I
  21828. * sqrt(0) = 0
  21829. * sqrt(-0) = -0
  21830. *
  21831. */
  21832. P.squareRoot = P.sqrt = function () {
  21833. var m, n, sd, r, rep, t,
  21834. x = this,
  21835. d = x.d,
  21836. e = x.e,
  21837. s = x.s,
  21838. Ctor = x.constructor;
  21839. // Negative/NaN/Infinity/zero?
  21840. if (s !== 1 || !d || !d[0]) {
  21841. return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
  21842. }
  21843. external = false;
  21844. // Initial estimate.
  21845. s = Math.sqrt(+x);
  21846. // Math.sqrt underflow/overflow?
  21847. // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  21848. if (s == 0 || s == 1 / 0) {
  21849. n = digitsToString(d);
  21850. if ((n.length + e) % 2 == 0) n += '0';
  21851. s = Math.sqrt(n);
  21852. e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
  21853. if (s == 1 / 0) {
  21854. n = '1e' + e;
  21855. } else {
  21856. n = s.toExponential();
  21857. n = n.slice(0, n.indexOf('e') + 1) + e;
  21858. }
  21859. r = new Ctor(n);
  21860. } else {
  21861. r = new Ctor(s.toString());
  21862. }
  21863. sd = (e = Ctor.precision) + 3;
  21864. // Newton-Raphson iteration.
  21865. for (;;) {
  21866. t = r;
  21867. r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
  21868. // TODO? Replace with for-loop and checkRoundingDigits.
  21869. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  21870. n = n.slice(sd - 3, sd + 1);
  21871. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
  21872. // 4999, i.e. approaching a rounding boundary, continue the iteration.
  21873. if (n == '9999' || !rep && n == '4999') {
  21874. // On the first iteration only, check to see if rounding up gives the exact result as the
  21875. // nines may infinitely repeat.
  21876. if (!rep) {
  21877. finalise(t, e + 1, 0);
  21878. if (t.times(t).eq(x)) {
  21879. r = t;
  21880. break;
  21881. }
  21882. }
  21883. sd += 4;
  21884. rep = 1;
  21885. } else {
  21886. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  21887. // If not, then there are further digits and m will be truthy.
  21888. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  21889. // Truncate to the first rounding digit.
  21890. finalise(r, e + 1, 1);
  21891. m = !r.times(r).eq(x);
  21892. }
  21893. break;
  21894. }
  21895. }
  21896. }
  21897. external = true;
  21898. return finalise(r, e, Ctor.rounding, m);
  21899. };
  21900. /*
  21901. * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
  21902. *
  21903. * Domain: [-Infinity, Infinity]
  21904. * Range: [-Infinity, Infinity]
  21905. *
  21906. * tan(0) = 0
  21907. * tan(-0) = -0
  21908. * tan(Infinity) = NaN
  21909. * tan(-Infinity) = NaN
  21910. * tan(NaN) = NaN
  21911. *
  21912. */
  21913. P.tangent = P.tan = function () {
  21914. var pr, rm,
  21915. x = this,
  21916. Ctor = x.constructor;
  21917. if (!x.isFinite()) return new Ctor(NaN);
  21918. if (x.isZero()) return new Ctor(x);
  21919. pr = Ctor.precision;
  21920. rm = Ctor.rounding;
  21921. Ctor.precision = pr + 10;
  21922. Ctor.rounding = 1;
  21923. x = x.sin();
  21924. x.s = 1;
  21925. x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
  21926. Ctor.precision = pr;
  21927. Ctor.rounding = rm;
  21928. return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
  21929. };
  21930. /*
  21931. * n * 0 = 0
  21932. * n * N = N
  21933. * n * I = I
  21934. * 0 * n = 0
  21935. * 0 * 0 = 0
  21936. * 0 * N = N
  21937. * 0 * I = N
  21938. * N * n = N
  21939. * N * 0 = N
  21940. * N * N = N
  21941. * N * I = N
  21942. * I * n = I
  21943. * I * 0 = N
  21944. * I * N = N
  21945. * I * I = I
  21946. *
  21947. * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
  21948. * digits using rounding mode `rounding`.
  21949. *
  21950. */
  21951. P.times = P.mul = function (y) {
  21952. var carry, e, i, k, r, rL, t, xdL, ydL,
  21953. x = this,
  21954. Ctor = x.constructor,
  21955. xd = x.d,
  21956. yd = (y = new Ctor(y)).d;
  21957. y.s *= x.s;
  21958. // If either is NaN, ±Infinity or ±0...
  21959. if (!xd || !xd[0] || !yd || !yd[0]) {
  21960. return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
  21961. // Return NaN if either is NaN.
  21962. // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
  21963. ? NaN
  21964. // Return ±Infinity if either is ±Infinity.
  21965. // Return ±0 if either is ±0.
  21966. : !xd || !yd ? y.s / 0 : y.s * 0);
  21967. }
  21968. e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
  21969. xdL = xd.length;
  21970. ydL = yd.length;
  21971. // Ensure xd points to the longer array.
  21972. if (xdL < ydL) {
  21973. r = xd;
  21974. xd = yd;
  21975. yd = r;
  21976. rL = xdL;
  21977. xdL = ydL;
  21978. ydL = rL;
  21979. }
  21980. // Initialise the result array with zeros.
  21981. r = [];
  21982. rL = xdL + ydL;
  21983. for (i = rL; i--;) r.push(0);
  21984. // Multiply!
  21985. for (i = ydL; --i >= 0;) {
  21986. carry = 0;
  21987. for (k = xdL + i; k > i;) {
  21988. t = r[k] + yd[i] * xd[k - i - 1] + carry;
  21989. r[k--] = t % BASE | 0;
  21990. carry = t / BASE | 0;
  21991. }
  21992. r[k] = (r[k] + carry) % BASE | 0;
  21993. }
  21994. // Remove trailing zeros.
  21995. for (; !r[--rL];) r.pop();
  21996. if (carry) ++e;
  21997. else r.shift();
  21998. y.d = r;
  21999. y.e = getBase10Exponent(r, e);
  22000. return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
  22001. };
  22002. /*
  22003. * Return a string representing the value of this Decimal in base 2, round to `sd` significant
  22004. * digits using rounding mode `rm`.
  22005. *
  22006. * If the optional `sd` argument is present then return binary exponential notation.
  22007. *
  22008. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22009. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22010. *
  22011. */
  22012. P.toBinary = function (sd, rm) {
  22013. return toStringBinary(this, 2, sd, rm);
  22014. };
  22015. /*
  22016. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
  22017. * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
  22018. *
  22019. * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
  22020. *
  22021. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  22022. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22023. *
  22024. */
  22025. P.toDecimalPlaces = P.toDP = function (dp, rm) {
  22026. var x = this,
  22027. Ctor = x.constructor;
  22028. x = new Ctor(x);
  22029. if (dp === void 0) return x;
  22030. checkInt32(dp, 0, MAX_DIGITS);
  22031. if (rm === void 0) rm = Ctor.rounding;
  22032. else checkInt32(rm, 0, 8);
  22033. return finalise(x, dp + x.e + 1, rm);
  22034. };
  22035. /*
  22036. * Return a string representing the value of this Decimal in exponential notation rounded to
  22037. * `dp` fixed decimal places using rounding mode `rounding`.
  22038. *
  22039. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  22040. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22041. *
  22042. */
  22043. P.toExponential = function (dp, rm) {
  22044. var str,
  22045. x = this,
  22046. Ctor = x.constructor;
  22047. if (dp === void 0) {
  22048. str = finiteToString(x, true);
  22049. } else {
  22050. checkInt32(dp, 0, MAX_DIGITS);
  22051. if (rm === void 0) rm = Ctor.rounding;
  22052. else checkInt32(rm, 0, 8);
  22053. x = finalise(new Ctor(x), dp + 1, rm);
  22054. str = finiteToString(x, true, dp + 1);
  22055. }
  22056. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22057. };
  22058. /*
  22059. * Return a string representing the value of this Decimal in normal (fixed-point) notation to
  22060. * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
  22061. * omitted.
  22062. *
  22063. * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
  22064. *
  22065. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  22066. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22067. *
  22068. * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
  22069. * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
  22070. * (-0).toFixed(3) is '0.000'.
  22071. * (-0.5).toFixed(0) is '-0'.
  22072. *
  22073. */
  22074. P.toFixed = function (dp, rm) {
  22075. var str, y,
  22076. x = this,
  22077. Ctor = x.constructor;
  22078. if (dp === void 0) {
  22079. str = finiteToString(x);
  22080. } else {
  22081. checkInt32(dp, 0, MAX_DIGITS);
  22082. if (rm === void 0) rm = Ctor.rounding;
  22083. else checkInt32(rm, 0, 8);
  22084. y = finalise(new Ctor(x), dp + x.e + 1, rm);
  22085. str = finiteToString(y, false, dp + y.e + 1);
  22086. }
  22087. // To determine whether to add the minus sign look at the value before it was rounded,
  22088. // i.e. look at `x` rather than `y`.
  22089. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22090. };
  22091. /*
  22092. * Return an array representing the value of this Decimal as a simple fraction with an integer
  22093. * numerator and an integer denominator.
  22094. *
  22095. * The denominator will be a positive non-zero value less than or equal to the specified maximum
  22096. * denominator. If a maximum denominator is not specified, the denominator will be the lowest
  22097. * value necessary to represent the number exactly.
  22098. *
  22099. * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
  22100. *
  22101. */
  22102. P.toFraction = function (maxD) {
  22103. var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
  22104. x = this,
  22105. xd = x.d,
  22106. Ctor = x.constructor;
  22107. if (!xd) return new Ctor(x);
  22108. n1 = d0 = new Ctor(1);
  22109. d1 = n0 = new Ctor(0);
  22110. d = new Ctor(d1);
  22111. e = d.e = getPrecision(xd) - x.e - 1;
  22112. k = e % LOG_BASE;
  22113. d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
  22114. if (maxD == null) {
  22115. // d is 10**e, the minimum max-denominator needed.
  22116. maxD = e > 0 ? d : n1;
  22117. } else {
  22118. n = new Ctor(maxD);
  22119. if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
  22120. maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
  22121. }
  22122. external = false;
  22123. n = new Ctor(digitsToString(xd));
  22124. pr = Ctor.precision;
  22125. Ctor.precision = e = xd.length * LOG_BASE * 2;
  22126. for (;;) {
  22127. q = divide(n, d, 0, 1, 1);
  22128. d2 = d0.plus(q.times(d1));
  22129. if (d2.cmp(maxD) == 1) break;
  22130. d0 = d1;
  22131. d1 = d2;
  22132. d2 = n1;
  22133. n1 = n0.plus(q.times(d2));
  22134. n0 = d2;
  22135. d2 = d;
  22136. d = n.minus(q.times(d2));
  22137. n = d2;
  22138. }
  22139. d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
  22140. n0 = n0.plus(d2.times(n1));
  22141. d0 = d0.plus(d2.times(d1));
  22142. n0.s = n1.s = x.s;
  22143. // Determine which fraction is closer to x, n0/d0 or n1/d1?
  22144. r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
  22145. ? [n1, d1] : [n0, d0];
  22146. Ctor.precision = pr;
  22147. external = true;
  22148. return r;
  22149. };
  22150. /*
  22151. * Return a string representing the value of this Decimal in base 16, round to `sd` significant
  22152. * digits using rounding mode `rm`.
  22153. *
  22154. * If the optional `sd` argument is present then return binary exponential notation.
  22155. *
  22156. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22157. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22158. *
  22159. */
  22160. P.toHexadecimal = P.toHex = function (sd, rm) {
  22161. return toStringBinary(this, 16, sd, rm);
  22162. };
  22163. /*
  22164. * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding
  22165. * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.
  22166. *
  22167. * The return value will always have the same sign as this Decimal, unless either this Decimal
  22168. * or `y` is NaN, in which case the return value will be also be NaN.
  22169. *
  22170. * The return value is not affected by the value of `precision`.
  22171. *
  22172. * y {number|string|Decimal} The magnitude to round to a multiple of.
  22173. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22174. *
  22175. * 'toNearest() rounding mode not an integer: {rm}'
  22176. * 'toNearest() rounding mode out of range: {rm}'
  22177. *
  22178. */
  22179. P.toNearest = function (y, rm) {
  22180. var x = this,
  22181. Ctor = x.constructor;
  22182. x = new Ctor(x);
  22183. if (y == null) {
  22184. // If x is not finite, return x.
  22185. if (!x.d) return x;
  22186. y = new Ctor(1);
  22187. rm = Ctor.rounding;
  22188. } else {
  22189. y = new Ctor(y);
  22190. if (rm === void 0) {
  22191. rm = Ctor.rounding;
  22192. } else {
  22193. checkInt32(rm, 0, 8);
  22194. }
  22195. // If x is not finite, return x if y is not NaN, else NaN.
  22196. if (!x.d) return y.s ? x : y;
  22197. // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
  22198. if (!y.d) {
  22199. if (y.s) y.s = x.s;
  22200. return y;
  22201. }
  22202. }
  22203. // If y is not zero, calculate the nearest multiple of y to x.
  22204. if (y.d[0]) {
  22205. external = false;
  22206. x = divide(x, y, 0, rm, 1).times(y);
  22207. external = true;
  22208. finalise(x);
  22209. // If y is zero, return zero with the sign of x.
  22210. } else {
  22211. y.s = x.s;
  22212. x = y;
  22213. }
  22214. return x;
  22215. };
  22216. /*
  22217. * Return the value of this Decimal converted to a number primitive.
  22218. * Zero keeps its sign.
  22219. *
  22220. */
  22221. P.toNumber = function () {
  22222. return +this;
  22223. };
  22224. /*
  22225. * Return a string representing the value of this Decimal in base 8, round to `sd` significant
  22226. * digits using rounding mode `rm`.
  22227. *
  22228. * If the optional `sd` argument is present then return binary exponential notation.
  22229. *
  22230. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22231. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22232. *
  22233. */
  22234. P.toOctal = function (sd, rm) {
  22235. return toStringBinary(this, 8, sd, rm);
  22236. };
  22237. /*
  22238. * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
  22239. * to `precision` significant digits using rounding mode `rounding`.
  22240. *
  22241. * ECMAScript compliant.
  22242. *
  22243. * pow(x, NaN) = NaN
  22244. * pow(x, ±0) = 1
  22245. * pow(NaN, non-zero) = NaN
  22246. * pow(abs(x) > 1, +Infinity) = +Infinity
  22247. * pow(abs(x) > 1, -Infinity) = +0
  22248. * pow(abs(x) == 1, ±Infinity) = NaN
  22249. * pow(abs(x) < 1, +Infinity) = +0
  22250. * pow(abs(x) < 1, -Infinity) = +Infinity
  22251. * pow(+Infinity, y > 0) = +Infinity
  22252. * pow(+Infinity, y < 0) = +0
  22253. * pow(-Infinity, odd integer > 0) = -Infinity
  22254. * pow(-Infinity, even integer > 0) = +Infinity
  22255. * pow(-Infinity, odd integer < 0) = -0
  22256. * pow(-Infinity, even integer < 0) = +0
  22257. * pow(+0, y > 0) = +0
  22258. * pow(+0, y < 0) = +Infinity
  22259. * pow(-0, odd integer > 0) = -0
  22260. * pow(-0, even integer > 0) = +0
  22261. * pow(-0, odd integer < 0) = -Infinity
  22262. * pow(-0, even integer < 0) = +Infinity
  22263. * pow(finite x < 0, finite non-integer) = NaN
  22264. *
  22265. * For non-integer or very large exponents pow(x, y) is calculated using
  22266. *
  22267. * x^y = exp(y*ln(x))
  22268. *
  22269. * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
  22270. * probability of an incorrectly rounded result
  22271. * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
  22272. * i.e. 1 in 250,000,000,000,000
  22273. *
  22274. * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
  22275. *
  22276. * y {number|string|Decimal} The power to which to raise this Decimal.
  22277. *
  22278. */
  22279. P.toPower = P.pow = function (y) {
  22280. var e, k, pr, r, rm, s,
  22281. x = this,
  22282. Ctor = x.constructor,
  22283. yn = +(y = new Ctor(y));
  22284. // Either ±Infinity, NaN or ±0?
  22285. if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
  22286. x = new Ctor(x);
  22287. if (x.eq(1)) return x;
  22288. pr = Ctor.precision;
  22289. rm = Ctor.rounding;
  22290. if (y.eq(1)) return finalise(x, pr, rm);
  22291. // y exponent
  22292. e = mathfloor(y.e / LOG_BASE);
  22293. // If y is a small integer use the 'exponentiation by squaring' algorithm.
  22294. if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
  22295. r = intPow(Ctor, x, k, pr);
  22296. return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
  22297. }
  22298. s = x.s;
  22299. // if x is negative
  22300. if (s < 0) {
  22301. // if y is not an integer
  22302. if (e < y.d.length - 1) return new Ctor(NaN);
  22303. // Result is positive if x is negative and the last digit of integer y is even.
  22304. if ((y.d[e] & 1) == 0) s = 1;
  22305. // if x.eq(-1)
  22306. if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
  22307. x.s = s;
  22308. return x;
  22309. }
  22310. }
  22311. // Estimate result exponent.
  22312. // x^y = 10^e, where e = y * log10(x)
  22313. // log10(x) = log10(x_significand) + x_exponent
  22314. // log10(x_significand) = ln(x_significand) / ln(10)
  22315. k = mathpow(+x, yn);
  22316. e = k == 0 || !isFinite(k)
  22317. ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
  22318. : new Ctor(k + '').e;
  22319. // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
  22320. // Overflow/underflow?
  22321. if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);
  22322. external = false;
  22323. Ctor.rounding = x.s = 1;
  22324. // Estimate the extra guard digits needed to ensure five correct rounding digits from
  22325. // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
  22326. // new Decimal(2.32456).pow('2087987436534566.46411')
  22327. // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
  22328. k = Math.min(12, (e + '').length);
  22329. // r = x^y = exp(y*ln(x))
  22330. r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
  22331. // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
  22332. if (r.d) {
  22333. // Truncate to the required precision plus five rounding digits.
  22334. r = finalise(r, pr + 5, 1);
  22335. // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
  22336. // the result.
  22337. if (checkRoundingDigits(r.d, pr, rm)) {
  22338. e = pr + 10;
  22339. // Truncate to the increased precision plus five rounding digits.
  22340. r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
  22341. // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
  22342. if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
  22343. r = finalise(r, pr + 1, 0);
  22344. }
  22345. }
  22346. }
  22347. r.s = s;
  22348. external = true;
  22349. Ctor.rounding = rm;
  22350. return finalise(r, pr, rm);
  22351. };
  22352. /*
  22353. * Return a string representing the value of this Decimal rounded to `sd` significant digits
  22354. * using rounding mode `rounding`.
  22355. *
  22356. * Return exponential notation if `sd` is less than the number of digits necessary to represent
  22357. * the integer part of the value in normal notation.
  22358. *
  22359. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22360. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22361. *
  22362. */
  22363. P.toPrecision = function (sd, rm) {
  22364. var str,
  22365. x = this,
  22366. Ctor = x.constructor;
  22367. if (sd === void 0) {
  22368. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  22369. } else {
  22370. checkInt32(sd, 1, MAX_DIGITS);
  22371. if (rm === void 0) rm = Ctor.rounding;
  22372. else checkInt32(rm, 0, 8);
  22373. x = finalise(new Ctor(x), sd, rm);
  22374. str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
  22375. }
  22376. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22377. };
  22378. /*
  22379. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
  22380. * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
  22381. * omitted.
  22382. *
  22383. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22384. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22385. *
  22386. * 'toSD() digits out of range: {sd}'
  22387. * 'toSD() digits not an integer: {sd}'
  22388. * 'toSD() rounding mode not an integer: {rm}'
  22389. * 'toSD() rounding mode out of range: {rm}'
  22390. *
  22391. */
  22392. P.toSignificantDigits = P.toSD = function (sd, rm) {
  22393. var x = this,
  22394. Ctor = x.constructor;
  22395. if (sd === void 0) {
  22396. sd = Ctor.precision;
  22397. rm = Ctor.rounding;
  22398. } else {
  22399. checkInt32(sd, 1, MAX_DIGITS);
  22400. if (rm === void 0) rm = Ctor.rounding;
  22401. else checkInt32(rm, 0, 8);
  22402. }
  22403. return finalise(new Ctor(x), sd, rm);
  22404. };
  22405. /*
  22406. * Return a string representing the value of this Decimal.
  22407. *
  22408. * Return exponential notation if this Decimal has a positive exponent equal to or greater than
  22409. * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
  22410. *
  22411. */
  22412. P.toString = function () {
  22413. var x = this,
  22414. Ctor = x.constructor,
  22415. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  22416. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22417. };
  22418. /*
  22419. * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
  22420. *
  22421. */
  22422. P.truncated = P.trunc = function () {
  22423. return finalise(new this.constructor(this), this.e + 1, 1);
  22424. };
  22425. /*
  22426. * Return a string representing the value of this Decimal.
  22427. * Unlike `toString`, negative zero will include the minus sign.
  22428. *
  22429. */
  22430. P.valueOf = P.toJSON = function () {
  22431. var x = this,
  22432. Ctor = x.constructor,
  22433. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  22434. return x.isNeg() ? '-' + str : str;
  22435. };
  22436. /*
  22437. // Add aliases to match BigDecimal method names.
  22438. // P.add = P.plus;
  22439. P.subtract = P.minus;
  22440. P.multiply = P.times;
  22441. P.divide = P.div;
  22442. P.remainder = P.mod;
  22443. P.compareTo = P.cmp;
  22444. P.negate = P.neg;
  22445. */
  22446. // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
  22447. /*
  22448. * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
  22449. * finiteToString, naturalExponential, naturalLogarithm
  22450. * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
  22451. * P.toPrecision, P.toSignificantDigits, toStringBinary, random
  22452. * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm
  22453. * convertBase toStringBinary, parseOther
  22454. * cos P.cos
  22455. * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
  22456. * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
  22457. * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
  22458. * taylorSeries, atan2, parseOther
  22459. * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
  22460. * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
  22461. * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
  22462. * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
  22463. * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
  22464. * P.truncated, divide, getLn10, getPi, naturalExponential,
  22465. * naturalLogarithm, ceil, floor, round, trunc
  22466. * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
  22467. * toStringBinary
  22468. * getBase10Exponent P.minus, P.plus, P.times, parseOther
  22469. * getLn10 P.logarithm, naturalLogarithm
  22470. * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
  22471. * getPrecision P.precision, P.toFraction
  22472. * getZeroString digitsToString, finiteToString
  22473. * intPow P.toPower, parseOther
  22474. * isOdd toLessThanHalfPi
  22475. * maxOrMin max, min
  22476. * naturalExponential P.naturalExponential, P.toPower
  22477. * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
  22478. * P.toPower, naturalExponential
  22479. * nonFiniteToString finiteToString, toStringBinary
  22480. * parseDecimal Decimal
  22481. * parseOther Decimal
  22482. * sin P.sin
  22483. * taylorSeries P.cosh, P.sinh, cos, sin
  22484. * toLessThanHalfPi P.cos, P.sin
  22485. * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal
  22486. * truncate intPow
  22487. *
  22488. * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
  22489. * naturalLogarithm, config, parseOther, random, Decimal
  22490. */
  22491. function digitsToString(d) {
  22492. var i, k, ws,
  22493. indexOfLastWord = d.length - 1,
  22494. str = '',
  22495. w = d[0];
  22496. if (indexOfLastWord > 0) {
  22497. str += w;
  22498. for (i = 1; i < indexOfLastWord; i++) {
  22499. ws = d[i] + '';
  22500. k = LOG_BASE - ws.length;
  22501. if (k) str += getZeroString(k);
  22502. str += ws;
  22503. }
  22504. w = d[i];
  22505. ws = w + '';
  22506. k = LOG_BASE - ws.length;
  22507. if (k) str += getZeroString(k);
  22508. } else if (w === 0) {
  22509. return '0';
  22510. }
  22511. // Remove trailing zeros of last w.
  22512. for (; w % 10 === 0;) w /= 10;
  22513. return str + w;
  22514. }
  22515. function checkInt32(i, min, max) {
  22516. if (i !== ~~i || i < min || i > max) {
  22517. throw Error(invalidArgument + i);
  22518. }
  22519. }
  22520. /*
  22521. * Check 5 rounding digits if `repeating` is null, 4 otherwise.
  22522. * `repeating == null` if caller is `log` or `pow`,
  22523. * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
  22524. */
  22525. function checkRoundingDigits(d, i, rm, repeating) {
  22526. var di, k, r, rd;
  22527. // Get the length of the first word of the array d.
  22528. for (k = d[0]; k >= 10; k /= 10) --i;
  22529. // Is the rounding digit in the first word of d?
  22530. if (--i < 0) {
  22531. i += LOG_BASE;
  22532. di = 0;
  22533. } else {
  22534. di = Math.ceil((i + 1) / LOG_BASE);
  22535. i %= LOG_BASE;
  22536. }
  22537. // i is the index (0 - 6) of the rounding digit.
  22538. // E.g. if within the word 3487563 the first rounding digit is 5,
  22539. // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
  22540. k = mathpow(10, LOG_BASE - i);
  22541. rd = d[di] % k | 0;
  22542. if (repeating == null) {
  22543. if (i < 3) {
  22544. if (i == 0) rd = rd / 100 | 0;
  22545. else if (i == 1) rd = rd / 10 | 0;
  22546. r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
  22547. } else {
  22548. r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
  22549. (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
  22550. (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
  22551. }
  22552. } else {
  22553. if (i < 4) {
  22554. if (i == 0) rd = rd / 1000 | 0;
  22555. else if (i == 1) rd = rd / 100 | 0;
  22556. else if (i == 2) rd = rd / 10 | 0;
  22557. r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
  22558. } else {
  22559. r = ((repeating || rm < 4) && rd + 1 == k ||
  22560. (!repeating && rm > 3) && rd + 1 == k / 2) &&
  22561. (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
  22562. }
  22563. }
  22564. return r;
  22565. }
  22566. // Convert string of `baseIn` to an array of numbers of `baseOut`.
  22567. // Eg. convertBase('255', 10, 16) returns [15, 15].
  22568. // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
  22569. function convertBase(str, baseIn, baseOut) {
  22570. var j,
  22571. arr = [0],
  22572. arrL,
  22573. i = 0,
  22574. strL = str.length;
  22575. for (; i < strL;) {
  22576. for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
  22577. arr[0] += NUMERALS.indexOf(str.charAt(i++));
  22578. for (j = 0; j < arr.length; j++) {
  22579. if (arr[j] > baseOut - 1) {
  22580. if (arr[j + 1] === void 0) arr[j + 1] = 0;
  22581. arr[j + 1] += arr[j] / baseOut | 0;
  22582. arr[j] %= baseOut;
  22583. }
  22584. }
  22585. }
  22586. return arr.reverse();
  22587. }
  22588. /*
  22589. * cos(x) = 1 - x^2/2! + x^4/4! - ...
  22590. * |x| < pi/2
  22591. *
  22592. */
  22593. function cosine(Ctor, x) {
  22594. var k, y,
  22595. len = x.d.length;
  22596. // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
  22597. // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
  22598. // Estimate the optimum number of times to use the argument reduction.
  22599. if (len < 32) {
  22600. k = Math.ceil(len / 3);
  22601. y = (1 / tinyPow(4, k)).toString();
  22602. } else {
  22603. k = 16;
  22604. y = '2.3283064365386962890625e-10';
  22605. }
  22606. Ctor.precision += k;
  22607. x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
  22608. // Reverse argument reduction
  22609. for (var i = k; i--;) {
  22610. var cos2x = x.times(x);
  22611. x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
  22612. }
  22613. Ctor.precision -= k;
  22614. return x;
  22615. }
  22616. /*
  22617. * Perform division in the specified base.
  22618. */
  22619. var divide = (function () {
  22620. // Assumes non-zero x and k, and hence non-zero result.
  22621. function multiplyInteger(x, k, base) {
  22622. var temp,
  22623. carry = 0,
  22624. i = x.length;
  22625. for (x = x.slice(); i--;) {
  22626. temp = x[i] * k + carry;
  22627. x[i] = temp % base | 0;
  22628. carry = temp / base | 0;
  22629. }
  22630. if (carry) x.unshift(carry);
  22631. return x;
  22632. }
  22633. function compare(a, b, aL, bL) {
  22634. var i, r;
  22635. if (aL != bL) {
  22636. r = aL > bL ? 1 : -1;
  22637. } else {
  22638. for (i = r = 0; i < aL; i++) {
  22639. if (a[i] != b[i]) {
  22640. r = a[i] > b[i] ? 1 : -1;
  22641. break;
  22642. }
  22643. }
  22644. }
  22645. return r;
  22646. }
  22647. function subtract(a, b, aL, base) {
  22648. var i = 0;
  22649. // Subtract b from a.
  22650. for (; aL--;) {
  22651. a[aL] -= i;
  22652. i = a[aL] < b[aL] ? 1 : 0;
  22653. a[aL] = i * base + a[aL] - b[aL];
  22654. }
  22655. // Remove leading zeros.
  22656. for (; !a[0] && a.length > 1;) a.shift();
  22657. }
  22658. return function (x, y, pr, rm, dp, base) {
  22659. var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
  22660. yL, yz,
  22661. Ctor = x.constructor,
  22662. sign = x.s == y.s ? 1 : -1,
  22663. xd = x.d,
  22664. yd = y.d;
  22665. // Either NaN, Infinity or 0?
  22666. if (!xd || !xd[0] || !yd || !yd[0]) {
  22667. return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
  22668. !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
  22669. // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
  22670. xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
  22671. }
  22672. if (base) {
  22673. logBase = 1;
  22674. e = x.e - y.e;
  22675. } else {
  22676. base = BASE;
  22677. logBase = LOG_BASE;
  22678. e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
  22679. }
  22680. yL = yd.length;
  22681. xL = xd.length;
  22682. q = new Ctor(sign);
  22683. qd = q.d = [];
  22684. // Result exponent may be one less than e.
  22685. // The digit array of a Decimal from toStringBinary may have trailing zeros.
  22686. for (i = 0; yd[i] == (xd[i] || 0); i++);
  22687. if (yd[i] > (xd[i] || 0)) e--;
  22688. if (pr == null) {
  22689. sd = pr = Ctor.precision;
  22690. rm = Ctor.rounding;
  22691. } else if (dp) {
  22692. sd = pr + (x.e - y.e) + 1;
  22693. } else {
  22694. sd = pr;
  22695. }
  22696. if (sd < 0) {
  22697. qd.push(1);
  22698. more = true;
  22699. } else {
  22700. // Convert precision in number of base 10 digits to base 1e7 digits.
  22701. sd = sd / logBase + 2 | 0;
  22702. i = 0;
  22703. // divisor < 1e7
  22704. if (yL == 1) {
  22705. k = 0;
  22706. yd = yd[0];
  22707. sd++;
  22708. // k is the carry.
  22709. for (; (i < xL || k) && sd--; i++) {
  22710. t = k * base + (xd[i] || 0);
  22711. qd[i] = t / yd | 0;
  22712. k = t % yd | 0;
  22713. }
  22714. more = k || i < xL;
  22715. // divisor >= 1e7
  22716. } else {
  22717. // Normalise xd and yd so highest order digit of yd is >= base/2
  22718. k = base / (yd[0] + 1) | 0;
  22719. if (k > 1) {
  22720. yd = multiplyInteger(yd, k, base);
  22721. xd = multiplyInteger(xd, k, base);
  22722. yL = yd.length;
  22723. xL = xd.length;
  22724. }
  22725. xi = yL;
  22726. rem = xd.slice(0, yL);
  22727. remL = rem.length;
  22728. // Add zeros to make remainder as long as divisor.
  22729. for (; remL < yL;) rem[remL++] = 0;
  22730. yz = yd.slice();
  22731. yz.unshift(0);
  22732. yd0 = yd[0];
  22733. if (yd[1] >= base / 2) ++yd0;
  22734. do {
  22735. k = 0;
  22736. // Compare divisor and remainder.
  22737. cmp = compare(yd, rem, yL, remL);
  22738. // If divisor < remainder.
  22739. if (cmp < 0) {
  22740. // Calculate trial digit, k.
  22741. rem0 = rem[0];
  22742. if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
  22743. // k will be how many times the divisor goes into the current remainder.
  22744. k = rem0 / yd0 | 0;
  22745. // Algorithm:
  22746. // 1. product = divisor * trial digit (k)
  22747. // 2. if product > remainder: product -= divisor, k--
  22748. // 3. remainder -= product
  22749. // 4. if product was < remainder at 2:
  22750. // 5. compare new remainder and divisor
  22751. // 6. If remainder > divisor: remainder -= divisor, k++
  22752. if (k > 1) {
  22753. if (k >= base) k = base - 1;
  22754. // product = divisor * trial digit.
  22755. prod = multiplyInteger(yd, k, base);
  22756. prodL = prod.length;
  22757. remL = rem.length;
  22758. // Compare product and remainder.
  22759. cmp = compare(prod, rem, prodL, remL);
  22760. // product > remainder.
  22761. if (cmp == 1) {
  22762. k--;
  22763. // Subtract divisor from product.
  22764. subtract(prod, yL < prodL ? yz : yd, prodL, base);
  22765. }
  22766. } else {
  22767. // cmp is -1.
  22768. // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
  22769. // to avoid it. If k is 1 there is a need to compare yd and rem again below.
  22770. if (k == 0) cmp = k = 1;
  22771. prod = yd.slice();
  22772. }
  22773. prodL = prod.length;
  22774. if (prodL < remL) prod.unshift(0);
  22775. // Subtract product from remainder.
  22776. subtract(rem, prod, remL, base);
  22777. // If product was < previous remainder.
  22778. if (cmp == -1) {
  22779. remL = rem.length;
  22780. // Compare divisor and new remainder.
  22781. cmp = compare(yd, rem, yL, remL);
  22782. // If divisor < new remainder, subtract divisor from remainder.
  22783. if (cmp < 1) {
  22784. k++;
  22785. // Subtract divisor from remainder.
  22786. subtract(rem, yL < remL ? yz : yd, remL, base);
  22787. }
  22788. }
  22789. remL = rem.length;
  22790. } else if (cmp === 0) {
  22791. k++;
  22792. rem = [0];
  22793. } // if cmp === 1, k will be 0
  22794. // Add the next digit, k, to the result array.
  22795. qd[i++] = k;
  22796. // Update the remainder.
  22797. if (cmp && rem[0]) {
  22798. rem[remL++] = xd[xi] || 0;
  22799. } else {
  22800. rem = [xd[xi]];
  22801. remL = 1;
  22802. }
  22803. } while ((xi++ < xL || rem[0] !== void 0) && sd--);
  22804. more = rem[0] !== void 0;
  22805. }
  22806. // Leading zero?
  22807. if (!qd[0]) qd.shift();
  22808. }
  22809. // logBase is 1 when divide is being used for base conversion.
  22810. if (logBase == 1) {
  22811. q.e = e;
  22812. inexact = more;
  22813. } else {
  22814. // To calculate q.e, first get the number of digits of qd[0].
  22815. for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
  22816. q.e = i + e * logBase - 1;
  22817. finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
  22818. }
  22819. return q;
  22820. };
  22821. })();
  22822. /*
  22823. * Round `x` to `sd` significant digits using rounding mode `rm`.
  22824. * Check for over/under-flow.
  22825. */
  22826. function finalise(x, sd, rm, isTruncated) {
  22827. var digits, i, j, k, rd, roundUp, w, xd, xdi,
  22828. Ctor = x.constructor;
  22829. // Don't round if sd is null or undefined.
  22830. out: if (sd != null) {
  22831. xd = x.d;
  22832. // Infinity/NaN.
  22833. if (!xd) return x;
  22834. // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
  22835. // w: the word of xd containing rd, a base 1e7 number.
  22836. // xdi: the index of w within xd.
  22837. // digits: the number of digits of w.
  22838. // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
  22839. // they had leading zeros)
  22840. // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
  22841. // Get the length of the first word of the digits array xd.
  22842. for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
  22843. i = sd - digits;
  22844. // Is the rounding digit in the first word of xd?
  22845. if (i < 0) {
  22846. i += LOG_BASE;
  22847. j = sd;
  22848. w = xd[xdi = 0];
  22849. // Get the rounding digit at index j of w.
  22850. rd = w / mathpow(10, digits - j - 1) % 10 | 0;
  22851. } else {
  22852. xdi = Math.ceil((i + 1) / LOG_BASE);
  22853. k = xd.length;
  22854. if (xdi >= k) {
  22855. if (isTruncated) {
  22856. // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
  22857. for (; k++ <= xdi;) xd.push(0);
  22858. w = rd = 0;
  22859. digits = 1;
  22860. i %= LOG_BASE;
  22861. j = i - LOG_BASE + 1;
  22862. } else {
  22863. break out;
  22864. }
  22865. } else {
  22866. w = k = xd[xdi];
  22867. // Get the number of digits of w.
  22868. for (digits = 1; k >= 10; k /= 10) digits++;
  22869. // Get the index of rd within w.
  22870. i %= LOG_BASE;
  22871. // Get the index of rd within w, adjusted for leading zeros.
  22872. // The number of leading zeros of w is given by LOG_BASE - digits.
  22873. j = i - LOG_BASE + digits;
  22874. // Get the rounding digit at index j of w.
  22875. rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
  22876. }
  22877. }
  22878. // Are there any non-zero digits after the rounding digit?
  22879. isTruncated = isTruncated || sd < 0 ||
  22880. xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
  22881. // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
  22882. // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
  22883. // will give 714.
  22884. roundUp = rm < 4
  22885. ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
  22886. : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
  22887. // Check whether the digit to the left of the rounding digit is odd.
  22888. ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
  22889. rm == (x.s < 0 ? 8 : 7));
  22890. if (sd < 1 || !xd[0]) {
  22891. xd.length = 0;
  22892. if (roundUp) {
  22893. // Convert sd to decimal places.
  22894. sd -= x.e + 1;
  22895. // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  22896. xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
  22897. x.e = -sd || 0;
  22898. } else {
  22899. // Zero.
  22900. xd[0] = x.e = 0;
  22901. }
  22902. return x;
  22903. }
  22904. // Remove excess digits.
  22905. if (i == 0) {
  22906. xd.length = xdi;
  22907. k = 1;
  22908. xdi--;
  22909. } else {
  22910. xd.length = xdi + 1;
  22911. k = mathpow(10, LOG_BASE - i);
  22912. // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  22913. // j > 0 means i > number of leading zeros of w.
  22914. xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
  22915. }
  22916. if (roundUp) {
  22917. for (;;) {
  22918. // Is the digit to be rounded up in the first word of xd?
  22919. if (xdi == 0) {
  22920. // i will be the length of xd[0] before k is added.
  22921. for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
  22922. j = xd[0] += k;
  22923. for (k = 1; j >= 10; j /= 10) k++;
  22924. // if i != k the length has increased.
  22925. if (i != k) {
  22926. x.e++;
  22927. if (xd[0] == BASE) xd[0] = 1;
  22928. }
  22929. break;
  22930. } else {
  22931. xd[xdi] += k;
  22932. if (xd[xdi] != BASE) break;
  22933. xd[xdi--] = 0;
  22934. k = 1;
  22935. }
  22936. }
  22937. }
  22938. // Remove trailing zeros.
  22939. for (i = xd.length; xd[--i] === 0;) xd.pop();
  22940. }
  22941. if (external) {
  22942. // Overflow?
  22943. if (x.e > Ctor.maxE) {
  22944. // Infinity.
  22945. x.d = null;
  22946. x.e = NaN;
  22947. // Underflow?
  22948. } else if (x.e < Ctor.minE) {
  22949. // Zero.
  22950. x.e = 0;
  22951. x.d = [0];
  22952. // Ctor.underflow = true;
  22953. } // else Ctor.underflow = false;
  22954. }
  22955. return x;
  22956. }
  22957. function finiteToString(x, isExp, sd) {
  22958. if (!x.isFinite()) return nonFiniteToString(x);
  22959. var k,
  22960. e = x.e,
  22961. str = digitsToString(x.d),
  22962. len = str.length;
  22963. if (isExp) {
  22964. if (sd && (k = sd - len) > 0) {
  22965. str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
  22966. } else if (len > 1) {
  22967. str = str.charAt(0) + '.' + str.slice(1);
  22968. }
  22969. str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
  22970. } else if (e < 0) {
  22971. str = '0.' + getZeroString(-e - 1) + str;
  22972. if (sd && (k = sd - len) > 0) str += getZeroString(k);
  22973. } else if (e >= len) {
  22974. str += getZeroString(e + 1 - len);
  22975. if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
  22976. } else {
  22977. if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
  22978. if (sd && (k = sd - len) > 0) {
  22979. if (e + 1 === len) str += '.';
  22980. str += getZeroString(k);
  22981. }
  22982. }
  22983. return str;
  22984. }
  22985. // Calculate the base 10 exponent from the base 1e7 exponent.
  22986. function getBase10Exponent(digits, e) {
  22987. var w = digits[0];
  22988. // Add the number of digits of the first word of the digits array.
  22989. for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
  22990. return e;
  22991. }
  22992. function getLn10(Ctor, sd, pr) {
  22993. if (sd > LN10_PRECISION) {
  22994. // Reset global state in case the exception is caught.
  22995. external = true;
  22996. if (pr) Ctor.precision = pr;
  22997. throw Error(precisionLimitExceeded);
  22998. }
  22999. return finalise(new Ctor(LN10), sd, 1, true);
  23000. }
  23001. function getPi(Ctor, sd, rm) {
  23002. if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
  23003. return finalise(new Ctor(PI), sd, rm, true);
  23004. }
  23005. function getPrecision(digits) {
  23006. var w = digits.length - 1,
  23007. len = w * LOG_BASE + 1;
  23008. w = digits[w];
  23009. // If non-zero...
  23010. if (w) {
  23011. // Subtract the number of trailing zeros of the last word.
  23012. for (; w % 10 == 0; w /= 10) len--;
  23013. // Add the number of digits of the first word.
  23014. for (w = digits[0]; w >= 10; w /= 10) len++;
  23015. }
  23016. return len;
  23017. }
  23018. function getZeroString(k) {
  23019. var zs = '';
  23020. for (; k--;) zs += '0';
  23021. return zs;
  23022. }
  23023. /*
  23024. * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
  23025. * integer of type number.
  23026. *
  23027. * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
  23028. *
  23029. */
  23030. function intPow(Ctor, x, n, pr) {
  23031. var isTruncated,
  23032. r = new Ctor(1),
  23033. // Max n of 9007199254740991 takes 53 loop iterations.
  23034. // Maximum digits array length; leaves [28, 34] guard digits.
  23035. k = Math.ceil(pr / LOG_BASE + 4);
  23036. external = false;
  23037. for (;;) {
  23038. if (n % 2) {
  23039. r = r.times(x);
  23040. if (truncate(r.d, k)) isTruncated = true;
  23041. }
  23042. n = mathfloor(n / 2);
  23043. if (n === 0) {
  23044. // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
  23045. n = r.d.length - 1;
  23046. if (isTruncated && r.d[n] === 0) ++r.d[n];
  23047. break;
  23048. }
  23049. x = x.times(x);
  23050. truncate(x.d, k);
  23051. }
  23052. external = true;
  23053. return r;
  23054. }
  23055. function isOdd(n) {
  23056. return n.d[n.d.length - 1] & 1;
  23057. }
  23058. /*
  23059. * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
  23060. */
  23061. function maxOrMin(Ctor, args, ltgt) {
  23062. var y,
  23063. x = new Ctor(args[0]),
  23064. i = 0;
  23065. for (; ++i < args.length;) {
  23066. y = new Ctor(args[i]);
  23067. if (!y.s) {
  23068. x = y;
  23069. break;
  23070. } else if (x[ltgt](y)) {
  23071. x = y;
  23072. }
  23073. }
  23074. return x;
  23075. }
  23076. /*
  23077. * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
  23078. * digits.
  23079. *
  23080. * Taylor/Maclaurin series.
  23081. *
  23082. * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
  23083. *
  23084. * Argument reduction:
  23085. * Repeat x = x / 32, k += 5, until |x| < 0.1
  23086. * exp(x) = exp(x / 2^k)^(2^k)
  23087. *
  23088. * Previously, the argument was initially reduced by
  23089. * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
  23090. * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
  23091. * found to be slower than just dividing repeatedly by 32 as above.
  23092. *
  23093. * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
  23094. * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
  23095. * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
  23096. *
  23097. * exp(Infinity) = Infinity
  23098. * exp(-Infinity) = 0
  23099. * exp(NaN) = NaN
  23100. * exp(±0) = 1
  23101. *
  23102. * exp(x) is non-terminating for any finite, non-zero x.
  23103. *
  23104. * The result will always be correctly rounded.
  23105. *
  23106. */
  23107. function naturalExponential(x, sd) {
  23108. var denominator, guard, j, pow, sum, t, wpr,
  23109. rep = 0,
  23110. i = 0,
  23111. k = 0,
  23112. Ctor = x.constructor,
  23113. rm = Ctor.rounding,
  23114. pr = Ctor.precision;
  23115. // 0/NaN/Infinity?
  23116. if (!x.d || !x.d[0] || x.e > 17) {
  23117. return new Ctor(x.d
  23118. ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
  23119. : x.s ? x.s < 0 ? 0 : x : 0 / 0);
  23120. }
  23121. if (sd == null) {
  23122. external = false;
  23123. wpr = pr;
  23124. } else {
  23125. wpr = sd;
  23126. }
  23127. t = new Ctor(0.03125);
  23128. // while abs(x) >= 0.1
  23129. while (x.e > -2) {
  23130. // x = x / 2^5
  23131. x = x.times(t);
  23132. k += 5;
  23133. }
  23134. // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
  23135. // necessary to ensure the first 4 rounding digits are correct.
  23136. guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
  23137. wpr += guard;
  23138. denominator = pow = sum = new Ctor(1);
  23139. Ctor.precision = wpr;
  23140. for (;;) {
  23141. pow = finalise(pow.times(x), wpr, 1);
  23142. denominator = denominator.times(++i);
  23143. t = sum.plus(divide(pow, denominator, wpr, 1));
  23144. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  23145. j = k;
  23146. while (j--) sum = finalise(sum.times(sum), wpr, 1);
  23147. // Check to see if the first 4 rounding digits are [49]999.
  23148. // If so, repeat the summation with a higher precision, otherwise
  23149. // e.g. with precision: 18, rounding: 1
  23150. // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
  23151. // `wpr - guard` is the index of first rounding digit.
  23152. if (sd == null) {
  23153. if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  23154. Ctor.precision = wpr += 10;
  23155. denominator = pow = t = new Ctor(1);
  23156. i = 0;
  23157. rep++;
  23158. } else {
  23159. return finalise(sum, Ctor.precision = pr, rm, external = true);
  23160. }
  23161. } else {
  23162. Ctor.precision = pr;
  23163. return sum;
  23164. }
  23165. }
  23166. sum = t;
  23167. }
  23168. }
  23169. /*
  23170. * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
  23171. * digits.
  23172. *
  23173. * ln(-n) = NaN
  23174. * ln(0) = -Infinity
  23175. * ln(-0) = -Infinity
  23176. * ln(1) = 0
  23177. * ln(Infinity) = Infinity
  23178. * ln(-Infinity) = NaN
  23179. * ln(NaN) = NaN
  23180. *
  23181. * ln(n) (n != 1) is non-terminating.
  23182. *
  23183. */
  23184. function naturalLogarithm(y, sd) {
  23185. var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
  23186. n = 1,
  23187. guard = 10,
  23188. x = y,
  23189. xd = x.d,
  23190. Ctor = x.constructor,
  23191. rm = Ctor.rounding,
  23192. pr = Ctor.precision;
  23193. // Is x negative or Infinity, NaN, 0 or 1?
  23194. if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
  23195. return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
  23196. }
  23197. if (sd == null) {
  23198. external = false;
  23199. wpr = pr;
  23200. } else {
  23201. wpr = sd;
  23202. }
  23203. Ctor.precision = wpr += guard;
  23204. c = digitsToString(xd);
  23205. c0 = c.charAt(0);
  23206. if (Math.abs(e = x.e) < 1.5e15) {
  23207. // Argument reduction.
  23208. // The series converges faster the closer the argument is to 1, so using
  23209. // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
  23210. // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
  23211. // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
  23212. // later be divided by this number, then separate out the power of 10 using
  23213. // ln(a*10^b) = ln(a) + b*ln(10).
  23214. // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
  23215. //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
  23216. // max n is 6 (gives 0.7 - 1.3)
  23217. while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
  23218. x = x.times(y);
  23219. c = digitsToString(x.d);
  23220. c0 = c.charAt(0);
  23221. n++;
  23222. }
  23223. e = x.e;
  23224. if (c0 > 1) {
  23225. x = new Ctor('0.' + c);
  23226. e++;
  23227. } else {
  23228. x = new Ctor(c0 + '.' + c.slice(1));
  23229. }
  23230. } else {
  23231. // The argument reduction method above may result in overflow if the argument y is a massive
  23232. // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
  23233. // function using ln(x*10^e) = ln(x) + e*ln(10).
  23234. t = getLn10(Ctor, wpr + 2, pr).times(e + '');
  23235. x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
  23236. Ctor.precision = pr;
  23237. return sd == null ? finalise(x, pr, rm, external = true) : x;
  23238. }
  23239. // x1 is x reduced to a value near 1.
  23240. x1 = x;
  23241. // Taylor series.
  23242. // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
  23243. // where x = (y - 1)/(y + 1) (|x| < 1)
  23244. sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
  23245. x2 = finalise(x.times(x), wpr, 1);
  23246. denominator = 3;
  23247. for (;;) {
  23248. numerator = finalise(numerator.times(x2), wpr, 1);
  23249. t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
  23250. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  23251. sum = sum.times(2);
  23252. // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
  23253. // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
  23254. if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
  23255. sum = divide(sum, new Ctor(n), wpr, 1);
  23256. // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
  23257. // been repeated previously) and the first 4 rounding digits 9999?
  23258. // If so, restart the summation with a higher precision, otherwise
  23259. // e.g. with precision: 12, rounding: 1
  23260. // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
  23261. // `wpr - guard` is the index of first rounding digit.
  23262. if (sd == null) {
  23263. if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  23264. Ctor.precision = wpr += guard;
  23265. t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
  23266. x2 = finalise(x.times(x), wpr, 1);
  23267. denominator = rep = 1;
  23268. } else {
  23269. return finalise(sum, Ctor.precision = pr, rm, external = true);
  23270. }
  23271. } else {
  23272. Ctor.precision = pr;
  23273. return sum;
  23274. }
  23275. }
  23276. sum = t;
  23277. denominator += 2;
  23278. }
  23279. }
  23280. // ±Infinity, NaN.
  23281. function nonFiniteToString(x) {
  23282. // Unsigned.
  23283. return String(x.s * x.s / 0);
  23284. }
  23285. /*
  23286. * Parse the value of a new Decimal `x` from string `str`.
  23287. */
  23288. function parseDecimal(x, str) {
  23289. var e, i, len;
  23290. // Decimal point?
  23291. if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
  23292. // Exponential form?
  23293. if ((i = str.search(/e/i)) > 0) {
  23294. // Determine exponent.
  23295. if (e < 0) e = i;
  23296. e += +str.slice(i + 1);
  23297. str = str.substring(0, i);
  23298. } else if (e < 0) {
  23299. // Integer.
  23300. e = str.length;
  23301. }
  23302. // Determine leading zeros.
  23303. for (i = 0; str.charCodeAt(i) === 48; i++);
  23304. // Determine trailing zeros.
  23305. for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
  23306. str = str.slice(i, len);
  23307. if (str) {
  23308. len -= i;
  23309. x.e = e = e - i - 1;
  23310. x.d = [];
  23311. // Transform base
  23312. // e is the base 10 exponent.
  23313. // i is where to slice str to get the first word of the digits array.
  23314. i = (e + 1) % LOG_BASE;
  23315. if (e < 0) i += LOG_BASE;
  23316. if (i < len) {
  23317. if (i) x.d.push(+str.slice(0, i));
  23318. for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
  23319. str = str.slice(i);
  23320. i = LOG_BASE - str.length;
  23321. } else {
  23322. i -= len;
  23323. }
  23324. for (; i--;) str += '0';
  23325. x.d.push(+str);
  23326. if (external) {
  23327. // Overflow?
  23328. if (x.e > x.constructor.maxE) {
  23329. // Infinity.
  23330. x.d = null;
  23331. x.e = NaN;
  23332. // Underflow?
  23333. } else if (x.e < x.constructor.minE) {
  23334. // Zero.
  23335. x.e = 0;
  23336. x.d = [0];
  23337. // x.constructor.underflow = true;
  23338. } // else x.constructor.underflow = false;
  23339. }
  23340. } else {
  23341. // Zero.
  23342. x.e = 0;
  23343. x.d = [0];
  23344. }
  23345. return x;
  23346. }
  23347. /*
  23348. * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
  23349. */
  23350. function parseOther(x, str) {
  23351. var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
  23352. if (str === 'Infinity' || str === 'NaN') {
  23353. if (!+str) x.s = NaN;
  23354. x.e = NaN;
  23355. x.d = null;
  23356. return x;
  23357. }
  23358. if (isHex.test(str)) {
  23359. base = 16;
  23360. str = str.toLowerCase();
  23361. } else if (isBinary.test(str)) {
  23362. base = 2;
  23363. } else if (isOctal.test(str)) {
  23364. base = 8;
  23365. } else {
  23366. throw Error(invalidArgument + str);
  23367. }
  23368. // Is there a binary exponent part?
  23369. i = str.search(/p/i);
  23370. if (i > 0) {
  23371. p = +str.slice(i + 1);
  23372. str = str.substring(2, i);
  23373. } else {
  23374. str = str.slice(2);
  23375. }
  23376. // Convert `str` as an integer then divide the result by `base` raised to a power such that the
  23377. // fraction part will be restored.
  23378. i = str.indexOf('.');
  23379. isFloat = i >= 0;
  23380. Ctor = x.constructor;
  23381. if (isFloat) {
  23382. str = str.replace('.', '');
  23383. len = str.length;
  23384. i = len - i;
  23385. // log[10](16) = 1.2041... , log[10](88) = 1.9444....
  23386. divisor = intPow(Ctor, new Ctor(base), i, i * 2);
  23387. }
  23388. xd = convertBase(str, base, BASE);
  23389. xe = xd.length - 1;
  23390. // Remove trailing zeros.
  23391. for (i = xe; xd[i] === 0; --i) xd.pop();
  23392. if (i < 0) return new Ctor(x.s * 0);
  23393. x.e = getBase10Exponent(xd, xe);
  23394. x.d = xd;
  23395. external = false;
  23396. // At what precision to perform the division to ensure exact conversion?
  23397. // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
  23398. // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
  23399. // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
  23400. // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
  23401. // Therefore using 4 * the number of digits of str will always be enough.
  23402. if (isFloat) x = divide(x, divisor, len * 4);
  23403. // Multiply by the binary exponent part if present.
  23404. if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));
  23405. external = true;
  23406. return x;
  23407. }
  23408. /*
  23409. * sin(x) = x - x^3/3! + x^5/5! - ...
  23410. * |x| < pi/2
  23411. *
  23412. */
  23413. function sine(Ctor, x) {
  23414. var k,
  23415. len = x.d.length;
  23416. if (len < 3) return taylorSeries(Ctor, 2, x, x);
  23417. // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
  23418. // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
  23419. // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
  23420. // Estimate the optimum number of times to use the argument reduction.
  23421. k = 1.4 * Math.sqrt(len);
  23422. k = k > 16 ? 16 : k | 0;
  23423. x = x.times(1 / tinyPow(5, k));
  23424. x = taylorSeries(Ctor, 2, x, x);
  23425. // Reverse argument reduction
  23426. var sin2_x,
  23427. d5 = new Ctor(5),
  23428. d16 = new Ctor(16),
  23429. d20 = new Ctor(20);
  23430. for (; k--;) {
  23431. sin2_x = x.times(x);
  23432. x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
  23433. }
  23434. return x;
  23435. }
  23436. // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
  23437. function taylorSeries(Ctor, n, x, y, isHyperbolic) {
  23438. var j, t, u, x2,
  23439. i = 1,
  23440. pr = Ctor.precision,
  23441. k = Math.ceil(pr / LOG_BASE);
  23442. external = false;
  23443. x2 = x.times(x);
  23444. u = new Ctor(y);
  23445. for (;;) {
  23446. t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
  23447. u = isHyperbolic ? y.plus(t) : y.minus(t);
  23448. y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
  23449. t = u.plus(y);
  23450. if (t.d[k] !== void 0) {
  23451. for (j = k; t.d[j] === u.d[j] && j--;);
  23452. if (j == -1) break;
  23453. }
  23454. j = u;
  23455. u = y;
  23456. y = t;
  23457. t = j;
  23458. i++;
  23459. }
  23460. external = true;
  23461. t.d.length = k + 1;
  23462. return t;
  23463. }
  23464. // Exponent e must be positive and non-zero.
  23465. function tinyPow(b, e) {
  23466. var n = b;
  23467. while (--e) n *= b;
  23468. return n;
  23469. }
  23470. // Return the absolute value of `x` reduced to less than or equal to half pi.
  23471. function toLessThanHalfPi(Ctor, x) {
  23472. var t,
  23473. isNeg = x.s < 0,
  23474. pi = getPi(Ctor, Ctor.precision, 1),
  23475. halfPi = pi.times(0.5);
  23476. x = x.abs();
  23477. if (x.lte(halfPi)) {
  23478. quadrant = isNeg ? 4 : 1;
  23479. return x;
  23480. }
  23481. t = x.divToInt(pi);
  23482. if (t.isZero()) {
  23483. quadrant = isNeg ? 3 : 2;
  23484. } else {
  23485. x = x.minus(t.times(pi));
  23486. // 0 <= x < pi
  23487. if (x.lte(halfPi)) {
  23488. quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
  23489. return x;
  23490. }
  23491. quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
  23492. }
  23493. return x.minus(pi).abs();
  23494. }
  23495. /*
  23496. * Return the value of Decimal `x` as a string in base `baseOut`.
  23497. *
  23498. * If the optional `sd` argument is present include a binary exponent suffix.
  23499. */
  23500. function toStringBinary(x, baseOut, sd, rm) {
  23501. var base, e, i, k, len, roundUp, str, xd, y,
  23502. Ctor = x.constructor,
  23503. isExp = sd !== void 0;
  23504. if (isExp) {
  23505. checkInt32(sd, 1, MAX_DIGITS);
  23506. if (rm === void 0) rm = Ctor.rounding;
  23507. else checkInt32(rm, 0, 8);
  23508. } else {
  23509. sd = Ctor.precision;
  23510. rm = Ctor.rounding;
  23511. }
  23512. if (!x.isFinite()) {
  23513. str = nonFiniteToString(x);
  23514. } else {
  23515. str = finiteToString(x);
  23516. i = str.indexOf('.');
  23517. // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
  23518. // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
  23519. // minBinaryExponent = floor(decimalExponent * log[2](10))
  23520. // log[2](10) = 3.321928094887362347870319429489390175864
  23521. if (isExp) {
  23522. base = 2;
  23523. if (baseOut == 16) {
  23524. sd = sd * 4 - 3;
  23525. } else if (baseOut == 8) {
  23526. sd = sd * 3 - 2;
  23527. }
  23528. } else {
  23529. base = baseOut;
  23530. }
  23531. // Convert the number as an integer then divide the result by its base raised to a power such
  23532. // that the fraction part will be restored.
  23533. // Non-integer.
  23534. if (i >= 0) {
  23535. str = str.replace('.', '');
  23536. y = new Ctor(1);
  23537. y.e = str.length - i;
  23538. y.d = convertBase(finiteToString(y), 10, base);
  23539. y.e = y.d.length;
  23540. }
  23541. xd = convertBase(str, 10, base);
  23542. e = len = xd.length;
  23543. // Remove trailing zeros.
  23544. for (; xd[--len] == 0;) xd.pop();
  23545. if (!xd[0]) {
  23546. str = isExp ? '0p+0' : '0';
  23547. } else {
  23548. if (i < 0) {
  23549. e--;
  23550. } else {
  23551. x = new Ctor(x);
  23552. x.d = xd;
  23553. x.e = e;
  23554. x = divide(x, y, sd, rm, 0, base);
  23555. xd = x.d;
  23556. e = x.e;
  23557. roundUp = inexact;
  23558. }
  23559. // The rounding digit, i.e. the digit after the digit that may be rounded up.
  23560. i = xd[sd];
  23561. k = base / 2;
  23562. roundUp = roundUp || xd[sd + 1] !== void 0;
  23563. roundUp = rm < 4
  23564. ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
  23565. : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
  23566. rm === (x.s < 0 ? 8 : 7));
  23567. xd.length = sd;
  23568. if (roundUp) {
  23569. // Rounding up may mean the previous digit has to be rounded up and so on.
  23570. for (; ++xd[--sd] > base - 1;) {
  23571. xd[sd] = 0;
  23572. if (!sd) {
  23573. ++e;
  23574. xd.unshift(1);
  23575. }
  23576. }
  23577. }
  23578. // Determine trailing zeros.
  23579. for (len = xd.length; !xd[len - 1]; --len);
  23580. // E.g. [4, 11, 15] becomes 4bf.
  23581. for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
  23582. // Add binary exponent suffix?
  23583. if (isExp) {
  23584. if (len > 1) {
  23585. if (baseOut == 16 || baseOut == 8) {
  23586. i = baseOut == 16 ? 4 : 3;
  23587. for (--len; len % i; len++) str += '0';
  23588. xd = convertBase(str, base, baseOut);
  23589. for (len = xd.length; !xd[len - 1]; --len);
  23590. // xd[0] will always be be 1
  23591. for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
  23592. } else {
  23593. str = str.charAt(0) + '.' + str.slice(1);
  23594. }
  23595. }
  23596. str = str + (e < 0 ? 'p' : 'p+') + e;
  23597. } else if (e < 0) {
  23598. for (; ++e;) str = '0' + str;
  23599. str = '0.' + str;
  23600. } else {
  23601. if (++e > len) for (e -= len; e-- ;) str += '0';
  23602. else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
  23603. }
  23604. }
  23605. str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
  23606. }
  23607. return x.s < 0 ? '-' + str : str;
  23608. }
  23609. // Does not strip trailing zeros.
  23610. function truncate(arr, len) {
  23611. if (arr.length > len) {
  23612. arr.length = len;
  23613. return true;
  23614. }
  23615. }
  23616. // Decimal methods
  23617. /*
  23618. * abs
  23619. * acos
  23620. * acosh
  23621. * add
  23622. * asin
  23623. * asinh
  23624. * atan
  23625. * atanh
  23626. * atan2
  23627. * cbrt
  23628. * ceil
  23629. * clone
  23630. * config
  23631. * cos
  23632. * cosh
  23633. * div
  23634. * exp
  23635. * floor
  23636. * hypot
  23637. * ln
  23638. * log
  23639. * log2
  23640. * log10
  23641. * max
  23642. * min
  23643. * mod
  23644. * mul
  23645. * pow
  23646. * random
  23647. * round
  23648. * set
  23649. * sign
  23650. * sin
  23651. * sinh
  23652. * sqrt
  23653. * sub
  23654. * tan
  23655. * tanh
  23656. * trunc
  23657. */
  23658. /*
  23659. * Return a new Decimal whose value is the absolute value of `x`.
  23660. *
  23661. * x {number|string|Decimal}
  23662. *
  23663. */
  23664. function abs(x) {
  23665. return new this(x).abs();
  23666. }
  23667. /*
  23668. * Return a new Decimal whose value is the arccosine in radians of `x`.
  23669. *
  23670. * x {number|string|Decimal}
  23671. *
  23672. */
  23673. function acos(x) {
  23674. return new this(x).acos();
  23675. }
  23676. /*
  23677. * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
  23678. * `precision` significant digits using rounding mode `rounding`.
  23679. *
  23680. * x {number|string|Decimal} A value in radians.
  23681. *
  23682. */
  23683. function acosh(x) {
  23684. return new this(x).acosh();
  23685. }
  23686. /*
  23687. * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
  23688. * digits using rounding mode `rounding`.
  23689. *
  23690. * x {number|string|Decimal}
  23691. * y {number|string|Decimal}
  23692. *
  23693. */
  23694. function add(x, y) {
  23695. return new this(x).plus(y);
  23696. }
  23697. /*
  23698. * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
  23699. * significant digits using rounding mode `rounding`.
  23700. *
  23701. * x {number|string|Decimal}
  23702. *
  23703. */
  23704. function asin(x) {
  23705. return new this(x).asin();
  23706. }
  23707. /*
  23708. * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
  23709. * `precision` significant digits using rounding mode `rounding`.
  23710. *
  23711. * x {number|string|Decimal} A value in radians.
  23712. *
  23713. */
  23714. function asinh(x) {
  23715. return new this(x).asinh();
  23716. }
  23717. /*
  23718. * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
  23719. * significant digits using rounding mode `rounding`.
  23720. *
  23721. * x {number|string|Decimal}
  23722. *
  23723. */
  23724. function atan(x) {
  23725. return new this(x).atan();
  23726. }
  23727. /*
  23728. * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
  23729. * `precision` significant digits using rounding mode `rounding`.
  23730. *
  23731. * x {number|string|Decimal} A value in radians.
  23732. *
  23733. */
  23734. function atanh(x) {
  23735. return new this(x).atanh();
  23736. }
  23737. /*
  23738. * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
  23739. * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
  23740. *
  23741. * Domain: [-Infinity, Infinity]
  23742. * Range: [-pi, pi]
  23743. *
  23744. * y {number|string|Decimal} The y-coordinate.
  23745. * x {number|string|Decimal} The x-coordinate.
  23746. *
  23747. * atan2(±0, -0) = ±pi
  23748. * atan2(±0, +0) = ±0
  23749. * atan2(±0, -x) = ±pi for x > 0
  23750. * atan2(±0, x) = ±0 for x > 0
  23751. * atan2(-y, ±0) = -pi/2 for y > 0
  23752. * atan2(y, ±0) = pi/2 for y > 0
  23753. * atan2(±y, -Infinity) = ±pi for finite y > 0
  23754. * atan2(±y, +Infinity) = ±0 for finite y > 0
  23755. * atan2(±Infinity, x) = ±pi/2 for finite x
  23756. * atan2(±Infinity, -Infinity) = ±3*pi/4
  23757. * atan2(±Infinity, +Infinity) = ±pi/4
  23758. * atan2(NaN, x) = NaN
  23759. * atan2(y, NaN) = NaN
  23760. *
  23761. */
  23762. function atan2(y, x) {
  23763. y = new this(y);
  23764. x = new this(x);
  23765. var r,
  23766. pr = this.precision,
  23767. rm = this.rounding,
  23768. wpr = pr + 4;
  23769. // Either NaN
  23770. if (!y.s || !x.s) {
  23771. r = new this(NaN);
  23772. // Both ±Infinity
  23773. } else if (!y.d && !x.d) {
  23774. r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
  23775. r.s = y.s;
  23776. // x is ±Infinity or y is ±0
  23777. } else if (!x.d || y.isZero()) {
  23778. r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
  23779. r.s = y.s;
  23780. // y is ±Infinity or x is ±0
  23781. } else if (!y.d || x.isZero()) {
  23782. r = getPi(this, wpr, 1).times(0.5);
  23783. r.s = y.s;
  23784. // Both non-zero and finite
  23785. } else if (x.s < 0) {
  23786. this.precision = wpr;
  23787. this.rounding = 1;
  23788. r = this.atan(divide(y, x, wpr, 1));
  23789. x = getPi(this, wpr, 1);
  23790. this.precision = pr;
  23791. this.rounding = rm;
  23792. r = y.s < 0 ? r.minus(x) : r.plus(x);
  23793. } else {
  23794. r = this.atan(divide(y, x, wpr, 1));
  23795. }
  23796. return r;
  23797. }
  23798. /*
  23799. * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
  23800. * digits using rounding mode `rounding`.
  23801. *
  23802. * x {number|string|Decimal}
  23803. *
  23804. */
  23805. function cbrt(x) {
  23806. return new this(x).cbrt();
  23807. }
  23808. /*
  23809. * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
  23810. *
  23811. * x {number|string|Decimal}
  23812. *
  23813. */
  23814. function ceil(x) {
  23815. return finalise(x = new this(x), x.e + 1, 2);
  23816. }
  23817. /*
  23818. * Configure global settings for a Decimal constructor.
  23819. *
  23820. * `obj` is an object with one or more of the following properties,
  23821. *
  23822. * precision {number}
  23823. * rounding {number}
  23824. * toExpNeg {number}
  23825. * toExpPos {number}
  23826. * maxE {number}
  23827. * minE {number}
  23828. * modulo {number}
  23829. * crypto {boolean|number}
  23830. * defaults {true}
  23831. *
  23832. * E.g. Decimal.config({ precision: 20, rounding: 4 })
  23833. *
  23834. */
  23835. function config(obj) {
  23836. if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
  23837. var i, p, v,
  23838. useDefaults = obj.defaults === true,
  23839. ps = [
  23840. 'precision', 1, MAX_DIGITS,
  23841. 'rounding', 0, 8,
  23842. 'toExpNeg', -EXP_LIMIT, 0,
  23843. 'toExpPos', 0, EXP_LIMIT,
  23844. 'maxE', 0, EXP_LIMIT,
  23845. 'minE', -EXP_LIMIT, 0,
  23846. 'modulo', 0, 9
  23847. ];
  23848. for (i = 0; i < ps.length; i += 3) {
  23849. if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
  23850. if ((v = obj[p]) !== void 0) {
  23851. if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
  23852. else throw Error(invalidArgument + p + ': ' + v);
  23853. }
  23854. }
  23855. if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
  23856. if ((v = obj[p]) !== void 0) {
  23857. if (v === true || v === false || v === 0 || v === 1) {
  23858. if (v) {
  23859. if (typeof crypto != 'undefined' && crypto &&
  23860. (crypto.getRandomValues || crypto.randomBytes)) {
  23861. this[p] = true;
  23862. } else {
  23863. throw Error(cryptoUnavailable);
  23864. }
  23865. } else {
  23866. this[p] = false;
  23867. }
  23868. } else {
  23869. throw Error(invalidArgument + p + ': ' + v);
  23870. }
  23871. }
  23872. return this;
  23873. }
  23874. /*
  23875. * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
  23876. * digits using rounding mode `rounding`.
  23877. *
  23878. * x {number|string|Decimal} A value in radians.
  23879. *
  23880. */
  23881. function cos(x) {
  23882. return new this(x).cos();
  23883. }
  23884. /*
  23885. * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
  23886. * significant digits using rounding mode `rounding`.
  23887. *
  23888. * x {number|string|Decimal} A value in radians.
  23889. *
  23890. */
  23891. function cosh(x) {
  23892. return new this(x).cosh();
  23893. }
  23894. /*
  23895. * Create and return a Decimal constructor with the same configuration properties as this Decimal
  23896. * constructor.
  23897. *
  23898. */
  23899. function clone(obj) {
  23900. var i, p, ps;
  23901. /*
  23902. * The Decimal constructor and exported function.
  23903. * Return a new Decimal instance.
  23904. *
  23905. * v {number|string|Decimal} A numeric value.
  23906. *
  23907. */
  23908. function Decimal(v) {
  23909. var e, i, t,
  23910. x = this;
  23911. // Decimal called without new.
  23912. if (!(x instanceof Decimal)) return new Decimal(v);
  23913. // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
  23914. // which points to Object.
  23915. x.constructor = Decimal;
  23916. // Duplicate.
  23917. if (v instanceof Decimal) {
  23918. x.s = v.s;
  23919. if (external) {
  23920. if (!v.d || v.e > Decimal.maxE) {
  23921. // Infinity.
  23922. x.e = NaN;
  23923. x.d = null;
  23924. } else if (v.e < Decimal.minE) {
  23925. // Zero.
  23926. x.e = 0;
  23927. x.d = [0];
  23928. } else {
  23929. x.e = v.e;
  23930. x.d = v.d.slice();
  23931. }
  23932. } else {
  23933. x.e = v.e;
  23934. x.d = v.d ? v.d.slice() : v.d;
  23935. }
  23936. return;
  23937. }
  23938. t = typeof v;
  23939. if (t === 'number') {
  23940. if (v === 0) {
  23941. x.s = 1 / v < 0 ? -1 : 1;
  23942. x.e = 0;
  23943. x.d = [0];
  23944. return;
  23945. }
  23946. if (v < 0) {
  23947. v = -v;
  23948. x.s = -1;
  23949. } else {
  23950. x.s = 1;
  23951. }
  23952. // Fast path for small integers.
  23953. if (v === ~~v && v < 1e7) {
  23954. for (e = 0, i = v; i >= 10; i /= 10) e++;
  23955. if (external) {
  23956. if (e > Decimal.maxE) {
  23957. x.e = NaN;
  23958. x.d = null;
  23959. } else if (e < Decimal.minE) {
  23960. x.e = 0;
  23961. x.d = [0];
  23962. } else {
  23963. x.e = e;
  23964. x.d = [v];
  23965. }
  23966. } else {
  23967. x.e = e;
  23968. x.d = [v];
  23969. }
  23970. return;
  23971. // Infinity, NaN.
  23972. } else if (v * 0 !== 0) {
  23973. if (!v) x.s = NaN;
  23974. x.e = NaN;
  23975. x.d = null;
  23976. return;
  23977. }
  23978. return parseDecimal(x, v.toString());
  23979. } else if (t !== 'string') {
  23980. throw Error(invalidArgument + v);
  23981. }
  23982. // Minus sign?
  23983. if ((i = v.charCodeAt(0)) === 45) {
  23984. v = v.slice(1);
  23985. x.s = -1;
  23986. } else {
  23987. // Plus sign?
  23988. if (i === 43) v = v.slice(1);
  23989. x.s = 1;
  23990. }
  23991. return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
  23992. }
  23993. Decimal.prototype = P;
  23994. Decimal.ROUND_UP = 0;
  23995. Decimal.ROUND_DOWN = 1;
  23996. Decimal.ROUND_CEIL = 2;
  23997. Decimal.ROUND_FLOOR = 3;
  23998. Decimal.ROUND_HALF_UP = 4;
  23999. Decimal.ROUND_HALF_DOWN = 5;
  24000. Decimal.ROUND_HALF_EVEN = 6;
  24001. Decimal.ROUND_HALF_CEIL = 7;
  24002. Decimal.ROUND_HALF_FLOOR = 8;
  24003. Decimal.EUCLID = 9;
  24004. Decimal.config = Decimal.set = config;
  24005. Decimal.clone = clone;
  24006. Decimal.isDecimal = isDecimalInstance;
  24007. Decimal.abs = abs;
  24008. Decimal.acos = acos;
  24009. Decimal.acosh = acosh; // ES6
  24010. Decimal.add = add;
  24011. Decimal.asin = asin;
  24012. Decimal.asinh = asinh; // ES6
  24013. Decimal.atan = atan;
  24014. Decimal.atanh = atanh; // ES6
  24015. Decimal.atan2 = atan2;
  24016. Decimal.cbrt = cbrt; // ES6
  24017. Decimal.ceil = ceil;
  24018. Decimal.cos = cos;
  24019. Decimal.cosh = cosh; // ES6
  24020. Decimal.div = div;
  24021. Decimal.exp = exp;
  24022. Decimal.floor = floor;
  24023. Decimal.hypot = hypot; // ES6
  24024. Decimal.ln = ln;
  24025. Decimal.log = log;
  24026. Decimal.log10 = log10; // ES6
  24027. Decimal.log2 = log2; // ES6
  24028. Decimal.max = max;
  24029. Decimal.min = min;
  24030. Decimal.mod = mod;
  24031. Decimal.mul = mul;
  24032. Decimal.pow = pow;
  24033. Decimal.random = random;
  24034. Decimal.round = round;
  24035. Decimal.sign = sign; // ES6
  24036. Decimal.sin = sin;
  24037. Decimal.sinh = sinh; // ES6
  24038. Decimal.sqrt = sqrt;
  24039. Decimal.sub = sub;
  24040. Decimal.tan = tan;
  24041. Decimal.tanh = tanh; // ES6
  24042. Decimal.trunc = trunc; // ES6
  24043. if (obj === void 0) obj = {};
  24044. if (obj) {
  24045. if (obj.defaults !== true) {
  24046. ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
  24047. for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
  24048. }
  24049. }
  24050. Decimal.config(obj);
  24051. return Decimal;
  24052. }
  24053. /*
  24054. * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
  24055. * digits using rounding mode `rounding`.
  24056. *
  24057. * x {number|string|Decimal}
  24058. * y {number|string|Decimal}
  24059. *
  24060. */
  24061. function div(x, y) {
  24062. return new this(x).div(y);
  24063. }
  24064. /*
  24065. * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
  24066. * significant digits using rounding mode `rounding`.
  24067. *
  24068. * x {number|string|Decimal} The power to which to raise the base of the natural log.
  24069. *
  24070. */
  24071. function exp(x) {
  24072. return new this(x).exp();
  24073. }
  24074. /*
  24075. * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
  24076. *
  24077. * x {number|string|Decimal}
  24078. *
  24079. */
  24080. function floor(x) {
  24081. return finalise(x = new this(x), x.e + 1, 3);
  24082. }
  24083. /*
  24084. * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
  24085. * rounded to `precision` significant digits using rounding mode `rounding`.
  24086. *
  24087. * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
  24088. *
  24089. * arguments {number|string|Decimal}
  24090. *
  24091. */
  24092. function hypot() {
  24093. var i, n,
  24094. t = new this(0);
  24095. external = false;
  24096. for (i = 0; i < arguments.length;) {
  24097. n = new this(arguments[i++]);
  24098. if (!n.d) {
  24099. if (n.s) {
  24100. external = true;
  24101. return new this(1 / 0);
  24102. }
  24103. t = n;
  24104. } else if (t.d) {
  24105. t = t.plus(n.times(n));
  24106. }
  24107. }
  24108. external = true;
  24109. return t.sqrt();
  24110. }
  24111. /*
  24112. * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
  24113. * otherwise return false.
  24114. *
  24115. */
  24116. function isDecimalInstance(obj) {
  24117. return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false;
  24118. }
  24119. /*
  24120. * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
  24121. * significant digits using rounding mode `rounding`.
  24122. *
  24123. * x {number|string|Decimal}
  24124. *
  24125. */
  24126. function ln(x) {
  24127. return new this(x).ln();
  24128. }
  24129. /*
  24130. * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
  24131. * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
  24132. *
  24133. * log[y](x)
  24134. *
  24135. * x {number|string|Decimal} The argument of the logarithm.
  24136. * y {number|string|Decimal} The base of the logarithm.
  24137. *
  24138. */
  24139. function log(x, y) {
  24140. return new this(x).log(y);
  24141. }
  24142. /*
  24143. * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
  24144. * significant digits using rounding mode `rounding`.
  24145. *
  24146. * x {number|string|Decimal}
  24147. *
  24148. */
  24149. function log2(x) {
  24150. return new this(x).log(2);
  24151. }
  24152. /*
  24153. * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
  24154. * significant digits using rounding mode `rounding`.
  24155. *
  24156. * x {number|string|Decimal}
  24157. *
  24158. */
  24159. function log10(x) {
  24160. return new this(x).log(10);
  24161. }
  24162. /*
  24163. * Return a new Decimal whose value is the maximum of the arguments.
  24164. *
  24165. * arguments {number|string|Decimal}
  24166. *
  24167. */
  24168. function max() {
  24169. return maxOrMin(this, arguments, 'lt');
  24170. }
  24171. /*
  24172. * Return a new Decimal whose value is the minimum of the arguments.
  24173. *
  24174. * arguments {number|string|Decimal}
  24175. *
  24176. */
  24177. function min() {
  24178. return maxOrMin(this, arguments, 'gt');
  24179. }
  24180. /*
  24181. * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
  24182. * using rounding mode `rounding`.
  24183. *
  24184. * x {number|string|Decimal}
  24185. * y {number|string|Decimal}
  24186. *
  24187. */
  24188. function mod(x, y) {
  24189. return new this(x).mod(y);
  24190. }
  24191. /*
  24192. * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
  24193. * digits using rounding mode `rounding`.
  24194. *
  24195. * x {number|string|Decimal}
  24196. * y {number|string|Decimal}
  24197. *
  24198. */
  24199. function mul(x, y) {
  24200. return new this(x).mul(y);
  24201. }
  24202. /*
  24203. * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
  24204. * significant digits using rounding mode `rounding`.
  24205. *
  24206. * x {number|string|Decimal} The base.
  24207. * y {number|string|Decimal} The exponent.
  24208. *
  24209. */
  24210. function pow(x, y) {
  24211. return new this(x).pow(y);
  24212. }
  24213. /*
  24214. * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
  24215. * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
  24216. * are produced).
  24217. *
  24218. * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
  24219. *
  24220. */
  24221. function random(sd) {
  24222. var d, e, k, n,
  24223. i = 0,
  24224. r = new this(1),
  24225. rd = [];
  24226. if (sd === void 0) sd = this.precision;
  24227. else checkInt32(sd, 1, MAX_DIGITS);
  24228. k = Math.ceil(sd / LOG_BASE);
  24229. if (!this.crypto) {
  24230. for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
  24231. // Browsers supporting crypto.getRandomValues.
  24232. } else if (crypto.getRandomValues) {
  24233. d = crypto.getRandomValues(new Uint32Array(k));
  24234. for (; i < k;) {
  24235. n = d[i];
  24236. // 0 <= n < 4294967296
  24237. // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
  24238. if (n >= 4.29e9) {
  24239. d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
  24240. } else {
  24241. // 0 <= n <= 4289999999
  24242. // 0 <= (n % 1e7) <= 9999999
  24243. rd[i++] = n % 1e7;
  24244. }
  24245. }
  24246. // Node.js supporting crypto.randomBytes.
  24247. } else if (crypto.randomBytes) {
  24248. // buffer
  24249. d = crypto.randomBytes(k *= 4);
  24250. for (; i < k;) {
  24251. // 0 <= n < 2147483648
  24252. n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
  24253. // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
  24254. if (n >= 2.14e9) {
  24255. crypto.randomBytes(4).copy(d, i);
  24256. } else {
  24257. // 0 <= n <= 2139999999
  24258. // 0 <= (n % 1e7) <= 9999999
  24259. rd.push(n % 1e7);
  24260. i += 4;
  24261. }
  24262. }
  24263. i = k / 4;
  24264. } else {
  24265. throw Error(cryptoUnavailable);
  24266. }
  24267. k = rd[--i];
  24268. sd %= LOG_BASE;
  24269. // Convert trailing digits to zeros according to sd.
  24270. if (k && sd) {
  24271. n = mathpow(10, LOG_BASE - sd);
  24272. rd[i] = (k / n | 0) * n;
  24273. }
  24274. // Remove trailing words which are zero.
  24275. for (; rd[i] === 0; i--) rd.pop();
  24276. // Zero?
  24277. if (i < 0) {
  24278. e = 0;
  24279. rd = [0];
  24280. } else {
  24281. e = -1;
  24282. // Remove leading words which are zero and adjust exponent accordingly.
  24283. for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
  24284. // Count the digits of the first word of rd to determine leading zeros.
  24285. for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
  24286. // Adjust the exponent for leading zeros of the first word of rd.
  24287. if (k < LOG_BASE) e -= LOG_BASE - k;
  24288. }
  24289. r.e = e;
  24290. r.d = rd;
  24291. return r;
  24292. }
  24293. /*
  24294. * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
  24295. *
  24296. * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
  24297. *
  24298. * x {number|string|Decimal}
  24299. *
  24300. */
  24301. function round(x) {
  24302. return finalise(x = new this(x), x.e + 1, this.rounding);
  24303. }
  24304. /*
  24305. * Return
  24306. * 1 if x > 0,
  24307. * -1 if x < 0,
  24308. * 0 if x is 0,
  24309. * -0 if x is -0,
  24310. * NaN otherwise
  24311. *
  24312. * x {number|string|Decimal}
  24313. *
  24314. */
  24315. function sign(x) {
  24316. x = new this(x);
  24317. return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
  24318. }
  24319. /*
  24320. * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
  24321. * using rounding mode `rounding`.
  24322. *
  24323. * x {number|string|Decimal} A value in radians.
  24324. *
  24325. */
  24326. function sin(x) {
  24327. return new this(x).sin();
  24328. }
  24329. /*
  24330. * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
  24331. * significant digits using rounding mode `rounding`.
  24332. *
  24333. * x {number|string|Decimal} A value in radians.
  24334. *
  24335. */
  24336. function sinh(x) {
  24337. return new this(x).sinh();
  24338. }
  24339. /*
  24340. * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
  24341. * digits using rounding mode `rounding`.
  24342. *
  24343. * x {number|string|Decimal}
  24344. *
  24345. */
  24346. function sqrt(x) {
  24347. return new this(x).sqrt();
  24348. }
  24349. /*
  24350. * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
  24351. * using rounding mode `rounding`.
  24352. *
  24353. * x {number|string|Decimal}
  24354. * y {number|string|Decimal}
  24355. *
  24356. */
  24357. function sub(x, y) {
  24358. return new this(x).sub(y);
  24359. }
  24360. /*
  24361. * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
  24362. * digits using rounding mode `rounding`.
  24363. *
  24364. * x {number|string|Decimal} A value in radians.
  24365. *
  24366. */
  24367. function tan(x) {
  24368. return new this(x).tan();
  24369. }
  24370. /*
  24371. * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
  24372. * significant digits using rounding mode `rounding`.
  24373. *
  24374. * x {number|string|Decimal} A value in radians.
  24375. *
  24376. */
  24377. function tanh(x) {
  24378. return new this(x).tanh();
  24379. }
  24380. /*
  24381. * Return a new Decimal whose value is `x` truncated to an integer.
  24382. *
  24383. * x {number|string|Decimal}
  24384. *
  24385. */
  24386. function trunc(x) {
  24387. return finalise(x = new this(x), x.e + 1, 1);
  24388. }
  24389. // Create and configure initial Decimal constructor.
  24390. Decimal = clone(DEFAULTS);
  24391. Decimal['default'] = Decimal.Decimal = Decimal;
  24392. // Create the internal constants from their string values.
  24393. LN10 = new Decimal(LN10);
  24394. PI = new Decimal(PI);
  24395. // Export.
  24396. // AMD.
  24397. if (true) {
  24398. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
  24399. return Decimal;
  24400. }).call(exports, __webpack_require__, exports, module),
  24401. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  24402. // Node and other environments that support module.exports.
  24403. } else {}
  24404. })(this);
  24405. /***/ }),
  24406. /***/ "./node_modules/line-i18n/dist/LanguageService.js":
  24407. /*!********************************************************!*\
  24408. !*** ./node_modules/line-i18n/dist/LanguageService.js ***!
  24409. \********************************************************/
  24410. /*! exports provided: LanguageService */
  24411. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  24412. "use strict";
  24413. __webpack_require__.r(__webpack_exports__);
  24414. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LanguageService", function() { return LanguageService; });
  24415. var LanguageService = /** @class */ (function () {
  24416. function LanguageService(lsKey, defaultLang) {
  24417. if (defaultLang === void 0) { defaultLang = 'pt'; }
  24418. this.lsKey = lsKey;
  24419. this.defaultLang = defaultLang;
  24420. this.listeners = [];
  24421. this.document = document;
  24422. this.setupListener();
  24423. }
  24424. LanguageService.prototype.setupListener = function () {
  24425. var _this = this;
  24426. if (this.document !== null) {
  24427. this.document.addEventListener("storage", (function (event) {
  24428. var e = event;
  24429. if (e.key === _this.lsKey) {
  24430. _this.listeners.forEach(function (l) { return l(); });
  24431. }
  24432. }));
  24433. }
  24434. };
  24435. LanguageService.prototype.getLang = function () {
  24436. var lang = localStorage.getItem(this.lsKey);
  24437. if (lang === null || lang === undefined) {
  24438. console.warn("Internal Error: User language information has not been set. Returning default...");
  24439. return this.getDefaultLang();
  24440. }
  24441. return lang;
  24442. };
  24443. LanguageService.prototype.getDefaultLang = function () {
  24444. return this.defaultLang;
  24445. };
  24446. LanguageService.prototype.registerLanguageChangeListener = function (listener) {
  24447. this.listeners.push(listener);
  24448. };
  24449. return LanguageService;
  24450. }());
  24451. /***/ }),
  24452. /***/ "./node_modules/line-i18n/dist/LanguageServiceNoLS.js":
  24453. /*!************************************************************!*\
  24454. !*** ./node_modules/line-i18n/dist/LanguageServiceNoLS.js ***!
  24455. \************************************************************/
  24456. /*! exports provided: LanguageServiceNoLS */
  24457. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  24458. "use strict";
  24459. __webpack_require__.r(__webpack_exports__);
  24460. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LanguageServiceNoLS", function() { return LanguageServiceNoLS; });
  24461. var LanguageServiceNoLS = /** @class */ (function () {
  24462. function LanguageServiceNoLS(lang) {
  24463. this.lang = lang;
  24464. this.listeners = [];
  24465. }
  24466. LanguageServiceNoLS.prototype.setupListener = function () { };
  24467. LanguageServiceNoLS.prototype.notifyChange = function () {
  24468. this.listeners.forEach(function (l) { return l(); });
  24469. };
  24470. LanguageServiceNoLS.prototype.setLang = function (lang) {
  24471. this.lang = lang;
  24472. this.notifyChange();
  24473. };
  24474. LanguageServiceNoLS.prototype.getLang = function () {
  24475. return this.lang;
  24476. };
  24477. LanguageServiceNoLS.prototype.getDefaultLang = function () {
  24478. return this.lang;
  24479. };
  24480. LanguageServiceNoLS.prototype.registerLanguageChangeListener = function (listener) {
  24481. this.listeners.push(listener);
  24482. };
  24483. return LanguageServiceNoLS;
  24484. }());
  24485. /***/ }),
  24486. /***/ "./node_modules/line-i18n/dist/LocalizedStrings.js":
  24487. /*!*********************************************************!*\
  24488. !*** ./node_modules/line-i18n/dist/LocalizedStrings.js ***!
  24489. \*********************************************************/
  24490. /*! exports provided: LocalizedStrings */
  24491. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  24492. "use strict";
  24493. __webpack_require__.r(__webpack_exports__);
  24494. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocalizedStrings", function() { return LocalizedStrings; });
  24495. /* harmony import */ var _StringTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./StringTypes */ "./node_modules/line-i18n/dist/StringTypes.js");
  24496. var LocalizedStrings = /** @class */ (function () {
  24497. function LocalizedStrings(service, i18nData, listenToChange) {
  24498. var _this = this;
  24499. if (listenToChange === void 0) { listenToChange = false; }
  24500. this.service = service;
  24501. this.i18nData = i18nData;
  24502. this.listenToChange = listenToChange;
  24503. this.document = document;
  24504. if (this.listenToChange) {
  24505. service.registerLanguageChangeListener(function () {
  24506. _this.updateTagText();
  24507. });
  24508. }
  24509. }
  24510. LocalizedStrings.prototype.getString = function (id, type) {
  24511. var i18nObj = this.i18nData[this.service.getLang()];
  24512. if (!!!i18nObj) {
  24513. console.warn("Internal Error. The language set at ivprog.lang is not valid: " + this.service.getLang());
  24514. i18nObj = this.i18nData[this.service.getDefaultLang()];
  24515. }
  24516. if (!!!i18nObj[type]) {
  24517. return "{MISSING_I18N_TYPE_IDENTIFIER}";
  24518. }
  24519. else if (!!!i18nObj[type][id]) {
  24520. return "{MISSING_I18N_IDENTIFIER}";
  24521. }
  24522. else {
  24523. return i18nObj[type][id];
  24524. }
  24525. };
  24526. LocalizedStrings.prototype.getOR = function () {
  24527. return this.getUI('string_join_or');
  24528. };
  24529. LocalizedStrings.prototype.getError = function (id, context) {
  24530. if (context === void 0) { context = []; }
  24531. var text = this.getString(id, _StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].ERROR);
  24532. return this.processString(text, context);
  24533. };
  24534. LocalizedStrings.prototype.getMessage = function (id, context) {
  24535. if (context === void 0) { context = []; }
  24536. var text = this.getString(id, _StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].MESSAGE);
  24537. return this.processString(text, context);
  24538. };
  24539. LocalizedStrings.prototype.getUI = function (id, context) {
  24540. if (context === void 0) { context = []; }
  24541. var text = this.getString(id, _StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].UI);
  24542. return this.processString(text, context);
  24543. };
  24544. LocalizedStrings.prototype.processString = function (text, context) {
  24545. for (var i = 0; i < context.length; i++) {
  24546. var v = context[i];
  24547. text = text.replace('\$' + i, v);
  24548. }
  24549. return text;
  24550. };
  24551. LocalizedStrings.prototype.updateTagText = function (func) {
  24552. var _this = this;
  24553. if (func === void 0) { func = null; }
  24554. if (this.document !== null) {
  24555. var list = this.document.querySelectorAll("data.i18n");
  24556. list.forEach(function (node) {
  24557. if (func === null) {
  24558. node.innerHTML = _this.processTagTex(node.getAttribute("value"));
  24559. }
  24560. else {
  24561. node.innerHTML = func(node.getAttribute("value"));
  24562. }
  24563. });
  24564. }
  24565. };
  24566. LocalizedStrings.prototype.processTagTex = function (text) {
  24567. if (text === null) {
  24568. return "<Invalid i18n identifier>";
  24569. }
  24570. var opts = text.split(':');
  24571. var type = opts[0].toLowerCase();
  24572. var id = opts[1];
  24573. if (_StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].ERROR === type) {
  24574. return this.getError(id);
  24575. }
  24576. else if (_StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].MESSAGE === type) {
  24577. return this.getMessage(id);
  24578. }
  24579. else if (_StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].UI === type) {
  24580. return this.getUI(id);
  24581. }
  24582. else {
  24583. console.warn(" A string has been passed to the i18n helper function that was not in the form type:id -> " + text);
  24584. return this.getString(id, type);
  24585. }
  24586. };
  24587. return LocalizedStrings;
  24588. }());
  24589. /***/ }),
  24590. /***/ "./node_modules/line-i18n/dist/StringTypes.js":
  24591. /*!****************************************************!*\
  24592. !*** ./node_modules/line-i18n/dist/StringTypes.js ***!
  24593. \****************************************************/
  24594. /*! exports provided: StringTypes */
  24595. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  24596. "use strict";
  24597. __webpack_require__.r(__webpack_exports__);
  24598. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringTypes", function() { return StringTypes; });
  24599. var StringTypes;
  24600. (function (StringTypes) {
  24601. StringTypes["ERROR"] = "error";
  24602. StringTypes["MESSAGE"] = "message";
  24603. StringTypes["UI"] = "ui";
  24604. })(StringTypes || (StringTypes = {}));
  24605. /***/ }),
  24606. /***/ "./node_modules/line-i18n/dist/index.js":
  24607. /*!**********************************************!*\
  24608. !*** ./node_modules/line-i18n/dist/index.js ***!
  24609. \**********************************************/
  24610. /*! exports provided: default */
  24611. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  24612. "use strict";
  24613. __webpack_require__.r(__webpack_exports__);
  24614. /* harmony import */ var _LanguageService__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./LanguageService */ "./node_modules/line-i18n/dist/LanguageService.js");
  24615. /* harmony import */ var _LocalizedStrings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./LocalizedStrings */ "./node_modules/line-i18n/dist/LocalizedStrings.js");
  24616. /* harmony import */ var _StringTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./StringTypes */ "./node_modules/line-i18n/dist/StringTypes.js");
  24617. /* harmony import */ var _LanguageServiceNoLS__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LanguageServiceNoLS */ "./node_modules/line-i18n/dist/LanguageServiceNoLS.js");
  24618. /* harmony default export */ __webpack_exports__["default"] = ({
  24619. LanguageService: _LanguageService__WEBPACK_IMPORTED_MODULE_0__["LanguageService"],
  24620. LanguageServiceNoLS: _LanguageServiceNoLS__WEBPACK_IMPORTED_MODULE_3__["LanguageServiceNoLS"],
  24621. LocalizedStrings: _LocalizedStrings__WEBPACK_IMPORTED_MODULE_1__["LocalizedStrings"],
  24622. StringTypes: _StringTypes__WEBPACK_IMPORTED_MODULE_2__["StringTypes"]
  24623. });
  24624. /***/ }),
  24625. /***/ "./node_modules/melanke-watchjs/src/watch.js":
  24626. /*!***************************************************!*\
  24627. !*** ./node_modules/melanke-watchjs/src/watch.js ***!
  24628. \***************************************************/
  24629. /*! no static exports found */
  24630. /***/ (function(module, exports, __webpack_require__) {
  24631. "use strict";
  24632. /**
  24633. * DEVELOPED BY
  24634. * GIL LOPES BUENO
  24635. * gilbueno.mail@gmail.com
  24636. *
  24637. * WORKS WITH:
  24638. * IE8*, IE 9+, FF 4+, SF 5+, WebKit, CH 7+, OP 12+, BESEN, Rhino 1.7+
  24639. * For IE8 (and other legacy browsers) WatchJS will use dirty checking
  24640. *
  24641. * FORK:
  24642. * https://github.com/melanke/Watch.JS
  24643. *
  24644. * LICENSE: MIT
  24645. */
  24646. (function (factory) {
  24647. if (true) {
  24648. // Node. Does not work with strict CommonJS, but
  24649. // only CommonJS-like enviroments that support module.exports,
  24650. // like Node.
  24651. module.exports = factory();
  24652. } else {}
  24653. }(function () {
  24654. var WatchJS = {
  24655. noMore: false, // use WatchJS.suspend(obj) instead
  24656. useDirtyCheck: false, // use only dirty checking to track changes.
  24657. preserveExistingSetters: false
  24658. },
  24659. lengthsubjects = [];
  24660. var dirtyChecklist = [];
  24661. var pendingChanges = []; // used coalesce changes from defineProperty and __defineSetter__
  24662. var supportDefineProperty = false;
  24663. try {
  24664. supportDefineProperty = Object.defineProperty && Object.defineProperty({},'x', {});
  24665. } catch(ex) { /* not supported */ }
  24666. var isFunction = function (functionToCheck) {
  24667. var getType = {};
  24668. return functionToCheck && getType.toString.call(functionToCheck) == '[object Function]';
  24669. };
  24670. var isInt = function (x) {
  24671. return x % 1 === 0;
  24672. };
  24673. var isArray = function(obj) {
  24674. return Object.prototype.toString.call(obj) === '[object Array]';
  24675. };
  24676. var isObject = function(obj) {
  24677. return {}.toString.apply(obj) === '[object Object]';
  24678. };
  24679. var getObjDiff = function(a, b){
  24680. var aplus = [],
  24681. bplus = [];
  24682. if(!(typeof a == "string") && !(typeof b == "string")){
  24683. if (isArray(a) && b) {
  24684. for (var i=0; i<a.length; i++) {
  24685. if (b[i] === undefined) aplus.push(i);
  24686. }
  24687. } else {
  24688. for(var i in a){
  24689. if (a.hasOwnProperty(i)) {
  24690. if(b && !b.hasOwnProperty(i)) {
  24691. aplus.push(i);
  24692. }
  24693. }
  24694. }
  24695. }
  24696. if (isArray(b) && a) {
  24697. for (var j=0; j<b.length; j++) {
  24698. if (a[j] === undefined) bplus.push(j);
  24699. }
  24700. } else {
  24701. for(var j in b){
  24702. if (b.hasOwnProperty(j)) {
  24703. if(a && !a.hasOwnProperty(j)) {
  24704. bplus.push(j);
  24705. }
  24706. }
  24707. }
  24708. }
  24709. }
  24710. return {
  24711. added: aplus,
  24712. removed: bplus
  24713. }
  24714. };
  24715. var clone = function(obj){
  24716. if (null == obj || "object" != typeof obj) {
  24717. return obj;
  24718. }
  24719. var copy = obj.constructor();
  24720. for (var attr in obj) {
  24721. copy[attr] = obj[attr];
  24722. }
  24723. return copy;
  24724. }
  24725. var getExistingSetter = function (obj, propName) {
  24726. if (WatchJS.preserveExistingSetters) {
  24727. var existing = Object.getOwnPropertyDescriptor(obj, propName);
  24728. return existing.set;
  24729. }
  24730. return undefined;
  24731. }
  24732. var defineGetAndSet = function (obj, propName, getter, setter) {
  24733. try {
  24734. var existingSetter = getExistingSetter(obj, propName);
  24735. Object.defineProperty(obj, propName, {
  24736. get: getter,
  24737. set: function(value) {
  24738. setter.call(this, value, true); // coalesce changes
  24739. if (existingSetter) {
  24740. existingSetter(value);
  24741. }
  24742. },
  24743. enumerable: true,
  24744. configurable: true
  24745. });
  24746. }
  24747. catch(e1) {
  24748. try{
  24749. Object.prototype.__defineGetter__.call(obj, propName, getter);
  24750. Object.prototype.__defineSetter__.call(obj, propName, function(value) {
  24751. setter.call(this,value,true); // coalesce changes
  24752. });
  24753. }
  24754. catch(e2) {
  24755. observeDirtyChanges(obj,propName,setter);
  24756. //throw new Error("watchJS error: browser not supported :/")
  24757. }
  24758. }
  24759. };
  24760. var defineProp = function (obj, propName, value) {
  24761. try {
  24762. Object.defineProperty(obj, propName, {
  24763. enumerable: false,
  24764. configurable: true,
  24765. writable: false,
  24766. value: value
  24767. });
  24768. } catch(error) {
  24769. obj[propName] = value;
  24770. }
  24771. };
  24772. var observeDirtyChanges = function(obj,propName,setter) {
  24773. dirtyChecklist[dirtyChecklist.length] = {
  24774. prop: propName,
  24775. object: obj,
  24776. orig: clone(obj[propName]),
  24777. callback: setter
  24778. }
  24779. }
  24780. var watch = function () {
  24781. if (isFunction(arguments[1])) {
  24782. watchAll.apply(this, arguments);
  24783. } else if (isArray(arguments[1])) {
  24784. watchMany.apply(this, arguments);
  24785. } else {
  24786. watchOne.apply(this, arguments);
  24787. }
  24788. };
  24789. var watchAll = function (obj, watcher, level, addNRemove) {
  24790. if ((typeof obj == "string") || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  24791. return;
  24792. }
  24793. if(isArray(obj)) {
  24794. defineWatcher(obj, "__watchall__", watcher, level); // watch all changes on the array
  24795. if (level===undefined||level > 0) {
  24796. for (var prop = 0; prop < obj.length; prop++) { // watch objects in array
  24797. watchAll(obj[prop],watcher,level, addNRemove);
  24798. }
  24799. }
  24800. }
  24801. else {
  24802. var prop,props = [];
  24803. for (prop in obj) { //for each attribute if obj is an object
  24804. if (prop == "$val" || (!supportDefineProperty && prop === 'watchers')) {
  24805. continue;
  24806. }
  24807. if (Object.prototype.hasOwnProperty.call(obj, prop)) {
  24808. props.push(prop); //put in the props
  24809. }
  24810. }
  24811. watchMany(obj, props, watcher, level, addNRemove); //watch all items of the props
  24812. }
  24813. if (addNRemove) {
  24814. pushToLengthSubjects(obj, "$$watchlengthsubjectroot", watcher, level);
  24815. }
  24816. };
  24817. var watchMany = function (obj, props, watcher, level, addNRemove) {
  24818. if ((typeof obj == "string") || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  24819. return;
  24820. }
  24821. for (var i=0; i<props.length; i++) { //watch each property
  24822. var prop = props[i];
  24823. watchOne(obj, prop, watcher, level, addNRemove);
  24824. }
  24825. };
  24826. var watchOne = function (obj, prop, watcher, level, addNRemove) {
  24827. if ((typeof obj == "string") || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  24828. return;
  24829. }
  24830. if(isFunction(obj[prop])) { //dont watch if it is a function
  24831. return;
  24832. }
  24833. if(obj[prop] != null && (level === undefined || level > 0)){
  24834. watchAll(obj[prop], watcher, level!==undefined? level-1 : level); //recursively watch all attributes of this
  24835. }
  24836. defineWatcher(obj, prop, watcher, level);
  24837. if(addNRemove && (level === undefined || level > 0)){
  24838. pushToLengthSubjects(obj, prop, watcher, level);
  24839. }
  24840. };
  24841. var unwatch = function () {
  24842. if (isFunction(arguments[1])) {
  24843. unwatchAll.apply(this, arguments);
  24844. } else if (isArray(arguments[1])) {
  24845. unwatchMany.apply(this, arguments);
  24846. } else {
  24847. unwatchOne.apply(this, arguments);
  24848. }
  24849. };
  24850. var unwatchAll = function (obj, watcher) {
  24851. if (obj instanceof String || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  24852. return;
  24853. }
  24854. if (isArray(obj)) {
  24855. var props = ['__watchall__'];
  24856. for (var prop = 0; prop < obj.length; prop++) { //for each item if obj is an array
  24857. props.push(prop); //put in the props
  24858. }
  24859. unwatchMany(obj, props, watcher); //watch all itens of the props
  24860. } else {
  24861. var unwatchPropsInObject = function (obj2) {
  24862. var props = [];
  24863. for (var prop2 in obj2) { //for each attribute if obj is an object
  24864. if (obj2.hasOwnProperty(prop2)) {
  24865. if (obj2[prop2] instanceof Object) {
  24866. unwatchPropsInObject(obj2[prop2]); //recurs into object props
  24867. } else {
  24868. props.push(prop2); //put in the props
  24869. }
  24870. }
  24871. }
  24872. unwatchMany(obj2, props, watcher); //unwatch all of the props
  24873. };
  24874. unwatchPropsInObject(obj);
  24875. }
  24876. };
  24877. var unwatchMany = function (obj, props, watcher) {
  24878. for (var prop2 in props) { //watch each attribute of "props" if is an object
  24879. if (props.hasOwnProperty(prop2)) {
  24880. unwatchOne(obj, props[prop2], watcher);
  24881. }
  24882. }
  24883. };
  24884. var timeouts = [],
  24885. timerID = null;
  24886. function clearTimerID() {
  24887. timerID = null;
  24888. for(var i=0; i< timeouts.length; i++) {
  24889. timeouts[i]();
  24890. }
  24891. timeouts.length = 0;
  24892. }
  24893. var getTimerID= function () {
  24894. if (!timerID) {
  24895. timerID = setTimeout(clearTimerID);
  24896. }
  24897. return timerID;
  24898. }
  24899. var registerTimeout = function(fn) { // register function to be called on timeout
  24900. if (timerID==null) getTimerID();
  24901. timeouts[timeouts.length] = fn;
  24902. }
  24903. // Track changes made to an array, object or an object's property
  24904. // and invoke callback with a single change object containing type, value, oldvalue and array splices
  24905. // Syntax:
  24906. // trackChange(obj, callback, recursive, addNRemove)
  24907. // trackChange(obj, prop, callback, recursive, addNRemove)
  24908. var trackChange = function() {
  24909. var fn = (isFunction(arguments[2])) ? trackProperty : trackObject ;
  24910. fn.apply(this,arguments);
  24911. }
  24912. // track changes made to an object and invoke callback with a single change object containing type, value and array splices
  24913. var trackObject= function(obj, callback, recursive, addNRemove) {
  24914. var change = null,lastTimerID = -1;
  24915. var isArr = isArray(obj);
  24916. var level,fn = function(prop, action, newValue, oldValue) {
  24917. var timerID = getTimerID();
  24918. if (lastTimerID!==timerID) { // check if timer has changed since last update
  24919. lastTimerID = timerID;
  24920. change = {
  24921. type: 'update'
  24922. }
  24923. change['value'] = obj;
  24924. change['splices'] = null;
  24925. registerTimeout(function() {
  24926. callback.call(this,change);
  24927. change = null;
  24928. });
  24929. }
  24930. // create splices for array changes
  24931. if (isArr && obj === this && change !== null) {
  24932. if (action==='pop'||action==='shift') {
  24933. newValue = [];
  24934. oldValue = [oldValue];
  24935. }
  24936. else if (action==='push'||action==='unshift') {
  24937. newValue = [newValue];
  24938. oldValue = [];
  24939. }
  24940. else if (action!=='splice') {
  24941. return; // return here - for reverse and sort operations we don't need to return splices. a simple update will do
  24942. }
  24943. if (!change.splices) change.splices = [];
  24944. change.splices[change.splices.length] = {
  24945. index: prop,
  24946. deleteCount: oldValue ? oldValue.length : 0,
  24947. addedCount: newValue ? newValue.length : 0,
  24948. added: newValue,
  24949. deleted: oldValue
  24950. };
  24951. }
  24952. }
  24953. level = (recursive==true) ? undefined : 0;
  24954. watchAll(obj,fn, level, addNRemove);
  24955. }
  24956. // track changes made to the property of an object and invoke callback with a single change object containing type, value, oldvalue and splices
  24957. var trackProperty = function(obj,prop,callback,recursive, addNRemove) {
  24958. if (obj && prop) {
  24959. watchOne(obj,prop,function(prop, action, newvalue, oldvalue) {
  24960. var change = {
  24961. type: 'update'
  24962. }
  24963. change['value'] = newvalue;
  24964. change['oldvalue'] = oldvalue;
  24965. if (recursive && isObject(newvalue)||isArray(newvalue)) {
  24966. trackObject(newvalue,callback,recursive, addNRemove);
  24967. }
  24968. callback.call(this,change);
  24969. },0)
  24970. if (recursive && isObject(obj[prop])||isArray(obj[prop])) {
  24971. trackObject(obj[prop],callback,recursive, addNRemove);
  24972. }
  24973. }
  24974. }
  24975. var defineWatcher = function (obj, prop, watcher, level) {
  24976. var newWatcher = false;
  24977. var isArr = isArray(obj);
  24978. if (!obj.watchers) {
  24979. defineProp(obj, "watchers", {});
  24980. if (isArr) {
  24981. // watch array functions
  24982. watchFunctions(obj, function(index,action,newValue, oldValue) {
  24983. addPendingChange(obj, index, action,newValue, oldValue);
  24984. if (level !== 0 && newValue && (isObject(newValue) || isArray(newValue))) {
  24985. var i,n, ln, wAll, watchList = obj.watchers[prop];
  24986. if ((wAll = obj.watchers['__watchall__'])) {
  24987. watchList = watchList ? watchList.concat(wAll) : wAll;
  24988. }
  24989. ln = watchList ? watchList.length : 0;
  24990. for (i = 0; i<ln; i++) {
  24991. if (action!=='splice') {
  24992. watchAll(newValue, watchList[i], (level===undefined)?level:level-1);
  24993. }
  24994. else {
  24995. // watch spliced values
  24996. for(n=0; n < newValue.length; n++) {
  24997. watchAll(newValue[n], watchList[i], (level===undefined)?level:level-1);
  24998. }
  24999. }
  25000. }
  25001. }
  25002. });
  25003. }
  25004. }
  25005. if (!obj.watchers[prop]) {
  25006. obj.watchers[prop] = [];
  25007. if (!isArr) newWatcher = true;
  25008. }
  25009. for (var i=0; i<obj.watchers[prop].length; i++) {
  25010. if(obj.watchers[prop][i] === watcher){
  25011. return;
  25012. }
  25013. }
  25014. obj.watchers[prop].push(watcher); //add the new watcher to the watchers array
  25015. if (newWatcher) {
  25016. var val = obj[prop];
  25017. var getter = function () {
  25018. return val;
  25019. };
  25020. var setter = function (newval, delayWatcher) {
  25021. var oldval = val;
  25022. val = newval;
  25023. if (level !== 0
  25024. && obj[prop] && (isObject(obj[prop]) || isArray(obj[prop]))
  25025. && !obj[prop].watchers) {
  25026. // watch sub properties
  25027. var i,ln = obj.watchers[prop].length;
  25028. for(i=0; i<ln; i++) {
  25029. watchAll(obj[prop], obj.watchers[prop][i], (level===undefined)?level:level-1);
  25030. }
  25031. }
  25032. //watchFunctions(obj, prop);
  25033. if (isSuspended(obj, prop)) {
  25034. resume(obj, prop);
  25035. return;
  25036. }
  25037. if (!WatchJS.noMore){ // this does not work with Object.observe
  25038. //if (JSON.stringify(oldval) !== JSON.stringify(newval)) {
  25039. if (oldval !== newval) {
  25040. if (!delayWatcher) {
  25041. callWatchers(obj, prop, "set", newval, oldval);
  25042. }
  25043. else {
  25044. addPendingChange(obj, prop, "set", newval, oldval);
  25045. }
  25046. WatchJS.noMore = false;
  25047. }
  25048. }
  25049. };
  25050. if (WatchJS.useDirtyCheck) {
  25051. observeDirtyChanges(obj,prop,setter);
  25052. }
  25053. else {
  25054. defineGetAndSet(obj, prop, getter, setter);
  25055. }
  25056. }
  25057. };
  25058. var callWatchers = function (obj, prop, action, newval, oldval) {
  25059. if (prop !== undefined) {
  25060. var ln, wl, watchList = obj.watchers[prop];
  25061. if ((wl = obj.watchers['__watchall__'])) {
  25062. watchList = watchList ? watchList.concat(wl) : wl;
  25063. }
  25064. ln = watchList ? watchList.length : 0;
  25065. for (var wr=0; wr< ln; wr++) {
  25066. watchList[wr].call(obj, prop, action, newval, oldval);
  25067. }
  25068. } else {
  25069. for (var prop in obj) {//call all
  25070. if (obj.hasOwnProperty(prop)) {
  25071. callWatchers(obj, prop, action, newval, oldval);
  25072. }
  25073. }
  25074. }
  25075. };
  25076. var methodNames = ['pop', 'push', 'reverse', 'shift', 'sort', 'slice', 'unshift', 'splice'];
  25077. var defineArrayMethodWatcher = function (obj, original, methodName, callback) {
  25078. defineProp(obj, methodName, function () {
  25079. var index = 0;
  25080. var i,newValue, oldValue, response;
  25081. // get values before splicing array
  25082. if (methodName === 'splice') {
  25083. var start = arguments[0];
  25084. var end = start + arguments[1];
  25085. oldValue = obj.slice(start,end);
  25086. newValue = [];
  25087. for(i=2;i<arguments.length;i++) {
  25088. newValue[i-2] = arguments[i];
  25089. }
  25090. index = start;
  25091. }
  25092. else {
  25093. newValue = arguments.length > 0 ? arguments[0] : undefined;
  25094. }
  25095. response = original.apply(obj, arguments);
  25096. if (methodName !== 'slice') {
  25097. if (methodName === 'pop') {
  25098. oldValue = response;
  25099. index = obj.length;
  25100. }
  25101. else if (methodName === 'push') {
  25102. index = obj.length-1;
  25103. }
  25104. else if (methodName === 'shift') {
  25105. oldValue = response;
  25106. }
  25107. else if (methodName !== 'unshift' && newValue===undefined) {
  25108. newValue = response;
  25109. }
  25110. callback.call(obj, index, methodName,newValue, oldValue)
  25111. }
  25112. return response;
  25113. });
  25114. };
  25115. var watchFunctions = function(obj, callback) {
  25116. if (!isFunction(callback) || !obj || (obj instanceof String) || (!isArray(obj))) {
  25117. return;
  25118. }
  25119. for (var i = methodNames.length, methodName; i--;) {
  25120. methodName = methodNames[i];
  25121. defineArrayMethodWatcher(obj, obj[methodName], methodName, callback);
  25122. }
  25123. };
  25124. var unwatchOne = function (obj, prop, watcher) {
  25125. if (prop) {
  25126. if (obj.watchers && obj.watchers[prop]) {
  25127. if (watcher === undefined) {
  25128. delete obj.watchers[prop]; // remove all property watchers
  25129. }
  25130. else {
  25131. for (var i = 0; i < obj.watchers[prop].length; i++) {
  25132. var w = obj.watchers[prop][i];
  25133. if (w == watcher) {
  25134. obj.watchers[prop].splice(i, 1);
  25135. }
  25136. }
  25137. }
  25138. }
  25139. } else {
  25140. delete obj.watchers;
  25141. }
  25142. removeFromLengthSubjects(obj, prop, watcher);
  25143. removeFromDirtyChecklist(obj, prop);
  25144. };
  25145. // suspend watchers until next update cycle
  25146. var suspend = function(obj, prop) {
  25147. if (obj.watchers) {
  25148. var name = '__wjs_suspend__'+(prop!==undefined ? prop : '');
  25149. obj.watchers[name] = true;
  25150. }
  25151. }
  25152. var isSuspended = function(obj, prop) {
  25153. return obj.watchers
  25154. && (obj.watchers['__wjs_suspend__'] ||
  25155. obj.watchers['__wjs_suspend__'+prop]);
  25156. }
  25157. // resumes preivously suspended watchers
  25158. var resume = function(obj, prop) {
  25159. registerTimeout(function() {
  25160. delete obj.watchers['__wjs_suspend__'];
  25161. delete obj.watchers['__wjs_suspend__'+prop];
  25162. })
  25163. }
  25164. var pendingTimerID = null;
  25165. var addPendingChange = function(obj,prop, mode, newval, oldval) {
  25166. pendingChanges[pendingChanges.length] = {
  25167. obj:obj,
  25168. prop: prop,
  25169. mode: mode,
  25170. newval: newval,
  25171. oldval: oldval
  25172. };
  25173. if (pendingTimerID===null) {
  25174. pendingTimerID = setTimeout(applyPendingChanges);
  25175. }
  25176. };
  25177. var applyPendingChanges = function() {
  25178. // apply pending changes
  25179. var change = null;
  25180. pendingTimerID = null;
  25181. for(var i=0;i < pendingChanges.length;i++) {
  25182. change = pendingChanges[i];
  25183. callWatchers(change.obj, change.prop, change.mode, change.newval, change.oldval);
  25184. }
  25185. if (change) {
  25186. pendingChanges = [];
  25187. change = null;
  25188. }
  25189. }
  25190. var loop = function(){
  25191. // check for new or deleted props
  25192. for(var i=0; i<lengthsubjects.length; i++) {
  25193. var subj = lengthsubjects[i];
  25194. if (subj.prop === "$$watchlengthsubjectroot") {
  25195. var difference = getObjDiff(subj.obj, subj.actual);
  25196. if(difference.added.length || difference.removed.length){
  25197. if(difference.added.length){
  25198. watchMany(subj.obj, difference.added, subj.watcher, subj.level - 1, true);
  25199. }
  25200. subj.watcher.call(subj.obj, "root", "differentattr", difference, subj.actual);
  25201. }
  25202. subj.actual = clone(subj.obj);
  25203. } else {
  25204. var difference = getObjDiff(subj.obj[subj.prop], subj.actual);
  25205. if(difference.added.length || difference.removed.length){
  25206. if(difference.added.length){
  25207. for (var j=0; j<subj.obj.watchers[subj.prop].length; j++) {
  25208. watchMany(subj.obj[subj.prop], difference.added, subj.obj.watchers[subj.prop][j], subj.level - 1, true);
  25209. }
  25210. }
  25211. callWatchers(subj.obj, subj.prop, "differentattr", difference, subj.actual);
  25212. }
  25213. subj.actual = clone(subj.obj[subj.prop]);
  25214. }
  25215. }
  25216. // start dirty check
  25217. var n, value;
  25218. if (dirtyChecklist.length > 0) {
  25219. for (var i = 0; i < dirtyChecklist.length; i++) {
  25220. n = dirtyChecklist[i];
  25221. value = n.object[n.prop];
  25222. if (!compareValues(n.orig, value)) {
  25223. n.orig = clone(value);
  25224. n.callback(value);
  25225. }
  25226. }
  25227. }
  25228. };
  25229. var compareValues = function(a,b) {
  25230. var i, state = true;
  25231. if (a!==b) {
  25232. if (isObject(a)) {
  25233. for(i in a) {
  25234. if (!supportDefineProperty && i==='watchers') continue;
  25235. if (a[i]!==b[i]) {
  25236. state = false;
  25237. break;
  25238. };
  25239. }
  25240. }
  25241. else {
  25242. state = false;
  25243. }
  25244. }
  25245. return state;
  25246. }
  25247. var pushToLengthSubjects = function(obj, prop, watcher, level){
  25248. var actual;
  25249. if (prop === "$$watchlengthsubjectroot") {
  25250. actual = clone(obj);
  25251. } else {
  25252. actual = clone(obj[prop]);
  25253. }
  25254. lengthsubjects.push({
  25255. obj: obj,
  25256. prop: prop,
  25257. actual: actual,
  25258. watcher: watcher,
  25259. level: level
  25260. });
  25261. };
  25262. var removeFromLengthSubjects = function(obj, prop, watcher){
  25263. for (var i=0; i<lengthsubjects.length; i++) {
  25264. var subj = lengthsubjects[i];
  25265. if (subj.obj == obj) {
  25266. if (!prop || subj.prop == prop) {
  25267. if (!watcher || subj.watcher == watcher) {
  25268. // if we splice off one item at position i
  25269. // we need to decrement i as the array is one item shorter
  25270. // so when we increment i in the loop statement we
  25271. // will land at the correct index.
  25272. // if it's not decremented, you won't delete all length subjects
  25273. lengthsubjects.splice(i--, 1);
  25274. }
  25275. }
  25276. }
  25277. }
  25278. };
  25279. var removeFromDirtyChecklist = function(obj, prop){
  25280. var notInUse;
  25281. for (var i=0; i<dirtyChecklist.length; i++) {
  25282. var n = dirtyChecklist[i];
  25283. var watchers = n.object.watchers;
  25284. notInUse = (
  25285. n.object == obj
  25286. && (!prop || n.prop == prop)
  25287. && watchers
  25288. && (!prop || !watchers[prop] || watchers[prop].length == 0 )
  25289. );
  25290. if (notInUse) {
  25291. // we use the same syntax as in removeFromLengthSubjects
  25292. dirtyChecklist.splice(i--, 1);
  25293. }
  25294. }
  25295. };
  25296. setInterval(loop, 50);
  25297. WatchJS.watch = watch;
  25298. WatchJS.unwatch = unwatch;
  25299. WatchJS.callWatchers = callWatchers;
  25300. WatchJS.suspend = suspend; // suspend watchers
  25301. WatchJS.onChange = trackChange; // track changes made to object or it's property and return a single change object
  25302. return WatchJS;
  25303. }));
  25304. /***/ }),
  25305. /***/ "./node_modules/node-libs-browser/mock/empty.js":
  25306. /*!******************************************************!*\
  25307. !*** ./node_modules/node-libs-browser/mock/empty.js ***!
  25308. \******************************************************/
  25309. /*! no static exports found */
  25310. /***/ (function(module, exports) {
  25311. /***/ })
  25312. }]);
  25313. //# sourceMappingURL=vendors~main.28bb9bf067b35b9514f7.js.map