vendors~main.685d1cf2ece1ed4ebb99.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080
  1. (window["webpackJsonpivprogCore"] = window["webpackJsonpivprogCore"] || []).push([["vendors~main"],{
  2. /***/ "./node_modules/@babel/runtime/helpers/arrayLikeToArray.js":
  3. /*!*****************************************************************!*\
  4. !*** ./node_modules/@babel/runtime/helpers/arrayLikeToArray.js ***!
  5. \*****************************************************************/
  6. /*! no static exports found */
  7. /***/ (function(module, exports) {
  8. function _arrayLikeToArray(arr, len) {
  9. if (len == null || len > arr.length) len = arr.length;
  10. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  11. arr2[i] = arr[i];
  12. }
  13. return arr2;
  14. }
  15. module.exports = _arrayLikeToArray;
  16. /***/ }),
  17. /***/ "./node_modules/@babel/runtime/helpers/arrayWithHoles.js":
  18. /*!***************************************************************!*\
  19. !*** ./node_modules/@babel/runtime/helpers/arrayWithHoles.js ***!
  20. \***************************************************************/
  21. /*! no static exports found */
  22. /***/ (function(module, exports) {
  23. function _arrayWithHoles(arr) {
  24. if (Array.isArray(arr)) return arr;
  25. }
  26. module.exports = _arrayWithHoles;
  27. /***/ }),
  28. /***/ "./node_modules/@babel/runtime/helpers/arrayWithoutHoles.js":
  29. /*!******************************************************************!*\
  30. !*** ./node_modules/@babel/runtime/helpers/arrayWithoutHoles.js ***!
  31. \******************************************************************/
  32. /*! no static exports found */
  33. /***/ (function(module, exports, __webpack_require__) {
  34. var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray */ "./node_modules/@babel/runtime/helpers/arrayLikeToArray.js");
  35. function _arrayWithoutHoles(arr) {
  36. if (Array.isArray(arr)) return arrayLikeToArray(arr);
  37. }
  38. module.exports = _arrayWithoutHoles;
  39. /***/ }),
  40. /***/ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js":
  41. /*!**********************************************************************!*\
  42. !*** ./node_modules/@babel/runtime/helpers/assertThisInitialized.js ***!
  43. \**********************************************************************/
  44. /*! no static exports found */
  45. /***/ (function(module, exports) {
  46. function _assertThisInitialized(self) {
  47. if (self === void 0) {
  48. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  49. }
  50. return self;
  51. }
  52. module.exports = _assertThisInitialized;
  53. /***/ }),
  54. /***/ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js":
  55. /*!*****************************************************************!*\
  56. !*** ./node_modules/@babel/runtime/helpers/asyncToGenerator.js ***!
  57. \*****************************************************************/
  58. /*! no static exports found */
  59. /***/ (function(module, exports) {
  60. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  61. try {
  62. var info = gen[key](arg);
  63. var value = info.value;
  64. } catch (error) {
  65. reject(error);
  66. return;
  67. }
  68. if (info.done) {
  69. resolve(value);
  70. } else {
  71. Promise.resolve(value).then(_next, _throw);
  72. }
  73. }
  74. function _asyncToGenerator(fn) {
  75. return function () {
  76. var self = this,
  77. args = arguments;
  78. return new Promise(function (resolve, reject) {
  79. var gen = fn.apply(self, args);
  80. function _next(value) {
  81. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  82. }
  83. function _throw(err) {
  84. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  85. }
  86. _next(undefined);
  87. });
  88. };
  89. }
  90. module.exports = _asyncToGenerator;
  91. /***/ }),
  92. /***/ "./node_modules/@babel/runtime/helpers/classCallCheck.js":
  93. /*!***************************************************************!*\
  94. !*** ./node_modules/@babel/runtime/helpers/classCallCheck.js ***!
  95. \***************************************************************/
  96. /*! no static exports found */
  97. /***/ (function(module, exports) {
  98. function _classCallCheck(instance, Constructor) {
  99. if (!(instance instanceof Constructor)) {
  100. throw new TypeError("Cannot call a class as a function");
  101. }
  102. }
  103. module.exports = _classCallCheck;
  104. /***/ }),
  105. /***/ "./node_modules/@babel/runtime/helpers/construct.js":
  106. /*!**********************************************************!*\
  107. !*** ./node_modules/@babel/runtime/helpers/construct.js ***!
  108. \**********************************************************/
  109. /*! no static exports found */
  110. /***/ (function(module, exports, __webpack_require__) {
  111. var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js");
  112. var isNativeReflectConstruct = __webpack_require__(/*! ./isNativeReflectConstruct */ "./node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js");
  113. function _construct(Parent, args, Class) {
  114. if (isNativeReflectConstruct()) {
  115. module.exports = _construct = Reflect.construct;
  116. } else {
  117. module.exports = _construct = function _construct(Parent, args, Class) {
  118. var a = [null];
  119. a.push.apply(a, args);
  120. var Constructor = Function.bind.apply(Parent, a);
  121. var instance = new Constructor();
  122. if (Class) setPrototypeOf(instance, Class.prototype);
  123. return instance;
  124. };
  125. }
  126. return _construct.apply(null, arguments);
  127. }
  128. module.exports = _construct;
  129. /***/ }),
  130. /***/ "./node_modules/@babel/runtime/helpers/createClass.js":
  131. /*!************************************************************!*\
  132. !*** ./node_modules/@babel/runtime/helpers/createClass.js ***!
  133. \************************************************************/
  134. /*! no static exports found */
  135. /***/ (function(module, exports) {
  136. function _defineProperties(target, props) {
  137. for (var i = 0; i < props.length; i++) {
  138. var descriptor = props[i];
  139. descriptor.enumerable = descriptor.enumerable || false;
  140. descriptor.configurable = true;
  141. if ("value" in descriptor) descriptor.writable = true;
  142. Object.defineProperty(target, descriptor.key, descriptor);
  143. }
  144. }
  145. function _createClass(Constructor, protoProps, staticProps) {
  146. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  147. if (staticProps) _defineProperties(Constructor, staticProps);
  148. return Constructor;
  149. }
  150. module.exports = _createClass;
  151. /***/ }),
  152. /***/ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js":
  153. /*!***************************************************************!*\
  154. !*** ./node_modules/@babel/runtime/helpers/getPrototypeOf.js ***!
  155. \***************************************************************/
  156. /*! no static exports found */
  157. /***/ (function(module, exports) {
  158. function _getPrototypeOf(o) {
  159. module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  160. return o.__proto__ || Object.getPrototypeOf(o);
  161. };
  162. return _getPrototypeOf(o);
  163. }
  164. module.exports = _getPrototypeOf;
  165. /***/ }),
  166. /***/ "./node_modules/@babel/runtime/helpers/inherits.js":
  167. /*!*********************************************************!*\
  168. !*** ./node_modules/@babel/runtime/helpers/inherits.js ***!
  169. \*********************************************************/
  170. /*! no static exports found */
  171. /***/ (function(module, exports, __webpack_require__) {
  172. var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js");
  173. function _inherits(subClass, superClass) {
  174. if (typeof superClass !== "function" && superClass !== null) {
  175. throw new TypeError("Super expression must either be null or a function");
  176. }
  177. subClass.prototype = Object.create(superClass && superClass.prototype, {
  178. constructor: {
  179. value: subClass,
  180. writable: true,
  181. configurable: true
  182. }
  183. });
  184. if (superClass) setPrototypeOf(subClass, superClass);
  185. }
  186. module.exports = _inherits;
  187. /***/ }),
  188. /***/ "./node_modules/@babel/runtime/helpers/isNativeFunction.js":
  189. /*!*****************************************************************!*\
  190. !*** ./node_modules/@babel/runtime/helpers/isNativeFunction.js ***!
  191. \*****************************************************************/
  192. /*! no static exports found */
  193. /***/ (function(module, exports) {
  194. function _isNativeFunction(fn) {
  195. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  196. }
  197. module.exports = _isNativeFunction;
  198. /***/ }),
  199. /***/ "./node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js":
  200. /*!*************************************************************************!*\
  201. !*** ./node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js ***!
  202. \*************************************************************************/
  203. /*! no static exports found */
  204. /***/ (function(module, exports) {
  205. function _isNativeReflectConstruct() {
  206. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  207. if (Reflect.construct.sham) return false;
  208. if (typeof Proxy === "function") return true;
  209. try {
  210. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  211. return true;
  212. } catch (e) {
  213. return false;
  214. }
  215. }
  216. module.exports = _isNativeReflectConstruct;
  217. /***/ }),
  218. /***/ "./node_modules/@babel/runtime/helpers/iterableToArray.js":
  219. /*!****************************************************************!*\
  220. !*** ./node_modules/@babel/runtime/helpers/iterableToArray.js ***!
  221. \****************************************************************/
  222. /*! no static exports found */
  223. /***/ (function(module, exports) {
  224. function _iterableToArray(iter) {
  225. if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  226. }
  227. module.exports = _iterableToArray;
  228. /***/ }),
  229. /***/ "./node_modules/@babel/runtime/helpers/iterableToArrayLimit.js":
  230. /*!*********************************************************************!*\
  231. !*** ./node_modules/@babel/runtime/helpers/iterableToArrayLimit.js ***!
  232. \*********************************************************************/
  233. /*! no static exports found */
  234. /***/ (function(module, exports) {
  235. function _iterableToArrayLimit(arr, i) {
  236. if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
  237. var _arr = [];
  238. var _n = true;
  239. var _d = false;
  240. var _e = undefined;
  241. try {
  242. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  243. _arr.push(_s.value);
  244. if (i && _arr.length === i) break;
  245. }
  246. } catch (err) {
  247. _d = true;
  248. _e = err;
  249. } finally {
  250. try {
  251. if (!_n && _i["return"] != null) _i["return"]();
  252. } finally {
  253. if (_d) throw _e;
  254. }
  255. }
  256. return _arr;
  257. }
  258. module.exports = _iterableToArrayLimit;
  259. /***/ }),
  260. /***/ "./node_modules/@babel/runtime/helpers/nonIterableRest.js":
  261. /*!****************************************************************!*\
  262. !*** ./node_modules/@babel/runtime/helpers/nonIterableRest.js ***!
  263. \****************************************************************/
  264. /*! no static exports found */
  265. /***/ (function(module, exports) {
  266. function _nonIterableRest() {
  267. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  268. }
  269. module.exports = _nonIterableRest;
  270. /***/ }),
  271. /***/ "./node_modules/@babel/runtime/helpers/nonIterableSpread.js":
  272. /*!******************************************************************!*\
  273. !*** ./node_modules/@babel/runtime/helpers/nonIterableSpread.js ***!
  274. \******************************************************************/
  275. /*! no static exports found */
  276. /***/ (function(module, exports) {
  277. function _nonIterableSpread() {
  278. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  279. }
  280. module.exports = _nonIterableSpread;
  281. /***/ }),
  282. /***/ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js":
  283. /*!**************************************************************************!*\
  284. !*** ./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***!
  285. \**************************************************************************/
  286. /*! no static exports found */
  287. /***/ (function(module, exports, __webpack_require__) {
  288. var _typeof = __webpack_require__(/*! ../helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
  289. var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
  290. function _possibleConstructorReturn(self, call) {
  291. if (call && (_typeof(call) === "object" || typeof call === "function")) {
  292. return call;
  293. }
  294. return assertThisInitialized(self);
  295. }
  296. module.exports = _possibleConstructorReturn;
  297. /***/ }),
  298. /***/ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js":
  299. /*!***************************************************************!*\
  300. !*** ./node_modules/@babel/runtime/helpers/setPrototypeOf.js ***!
  301. \***************************************************************/
  302. /*! no static exports found */
  303. /***/ (function(module, exports) {
  304. function _setPrototypeOf(o, p) {
  305. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  306. o.__proto__ = p;
  307. return o;
  308. };
  309. return _setPrototypeOf(o, p);
  310. }
  311. module.exports = _setPrototypeOf;
  312. /***/ }),
  313. /***/ "./node_modules/@babel/runtime/helpers/slicedToArray.js":
  314. /*!**************************************************************!*\
  315. !*** ./node_modules/@babel/runtime/helpers/slicedToArray.js ***!
  316. \**************************************************************/
  317. /*! no static exports found */
  318. /***/ (function(module, exports, __webpack_require__) {
  319. var arrayWithHoles = __webpack_require__(/*! ./arrayWithHoles */ "./node_modules/@babel/runtime/helpers/arrayWithHoles.js");
  320. var iterableToArrayLimit = __webpack_require__(/*! ./iterableToArrayLimit */ "./node_modules/@babel/runtime/helpers/iterableToArrayLimit.js");
  321. var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray */ "./node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js");
  322. var nonIterableRest = __webpack_require__(/*! ./nonIterableRest */ "./node_modules/@babel/runtime/helpers/nonIterableRest.js");
  323. function _slicedToArray(arr, i) {
  324. return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
  325. }
  326. module.exports = _slicedToArray;
  327. /***/ }),
  328. /***/ "./node_modules/@babel/runtime/helpers/toConsumableArray.js":
  329. /*!******************************************************************!*\
  330. !*** ./node_modules/@babel/runtime/helpers/toConsumableArray.js ***!
  331. \******************************************************************/
  332. /*! no static exports found */
  333. /***/ (function(module, exports, __webpack_require__) {
  334. var arrayWithoutHoles = __webpack_require__(/*! ./arrayWithoutHoles */ "./node_modules/@babel/runtime/helpers/arrayWithoutHoles.js");
  335. var iterableToArray = __webpack_require__(/*! ./iterableToArray */ "./node_modules/@babel/runtime/helpers/iterableToArray.js");
  336. var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray */ "./node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js");
  337. var nonIterableSpread = __webpack_require__(/*! ./nonIterableSpread */ "./node_modules/@babel/runtime/helpers/nonIterableSpread.js");
  338. function _toConsumableArray(arr) {
  339. return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
  340. }
  341. module.exports = _toConsumableArray;
  342. /***/ }),
  343. /***/ "./node_modules/@babel/runtime/helpers/typeof.js":
  344. /*!*******************************************************!*\
  345. !*** ./node_modules/@babel/runtime/helpers/typeof.js ***!
  346. \*******************************************************/
  347. /*! no static exports found */
  348. /***/ (function(module, exports) {
  349. function _typeof(obj) {
  350. "@babel/helpers - typeof";
  351. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  352. module.exports = _typeof = function _typeof(obj) {
  353. return typeof obj;
  354. };
  355. } else {
  356. module.exports = _typeof = function _typeof(obj) {
  357. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  358. };
  359. }
  360. return _typeof(obj);
  361. }
  362. module.exports = _typeof;
  363. /***/ }),
  364. /***/ "./node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js":
  365. /*!***************************************************************************!*\
  366. !*** ./node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js ***!
  367. \***************************************************************************/
  368. /*! no static exports found */
  369. /***/ (function(module, exports, __webpack_require__) {
  370. var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray */ "./node_modules/@babel/runtime/helpers/arrayLikeToArray.js");
  371. function _unsupportedIterableToArray(o, minLen) {
  372. if (!o) return;
  373. if (typeof o === "string") return arrayLikeToArray(o, minLen);
  374. var n = Object.prototype.toString.call(o).slice(8, -1);
  375. if (n === "Object" && o.constructor) n = o.constructor.name;
  376. if (n === "Map" || n === "Set") return Array.from(o);
  377. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
  378. }
  379. module.exports = _unsupportedIterableToArray;
  380. /***/ }),
  381. /***/ "./node_modules/@babel/runtime/helpers/wrapNativeSuper.js":
  382. /*!****************************************************************!*\
  383. !*** ./node_modules/@babel/runtime/helpers/wrapNativeSuper.js ***!
  384. \****************************************************************/
  385. /*! no static exports found */
  386. /***/ (function(module, exports, __webpack_require__) {
  387. var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
  388. var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js");
  389. var isNativeFunction = __webpack_require__(/*! ./isNativeFunction */ "./node_modules/@babel/runtime/helpers/isNativeFunction.js");
  390. var construct = __webpack_require__(/*! ./construct */ "./node_modules/@babel/runtime/helpers/construct.js");
  391. function _wrapNativeSuper(Class) {
  392. var _cache = typeof Map === "function" ? new Map() : undefined;
  393. module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {
  394. if (Class === null || !isNativeFunction(Class)) return Class;
  395. if (typeof Class !== "function") {
  396. throw new TypeError("Super expression must either be null or a function");
  397. }
  398. if (typeof _cache !== "undefined") {
  399. if (_cache.has(Class)) return _cache.get(Class);
  400. _cache.set(Class, Wrapper);
  401. }
  402. function Wrapper() {
  403. return construct(Class, arguments, getPrototypeOf(this).constructor);
  404. }
  405. Wrapper.prototype = Object.create(Class.prototype, {
  406. constructor: {
  407. value: Wrapper,
  408. enumerable: false,
  409. writable: true,
  410. configurable: true
  411. }
  412. });
  413. return setPrototypeOf(Wrapper, Class);
  414. };
  415. return _wrapNativeSuper(Class);
  416. }
  417. module.exports = _wrapNativeSuper;
  418. /***/ }),
  419. /***/ "./node_modules/@babel/runtime/regenerator/index.js":
  420. /*!**********************************************************!*\
  421. !*** ./node_modules/@babel/runtime/regenerator/index.js ***!
  422. \**********************************************************/
  423. /*! no static exports found */
  424. /***/ (function(module, exports, __webpack_require__) {
  425. module.exports = __webpack_require__(/*! regenerator-runtime */ "./node_modules/regenerator-runtime/runtime.js");
  426. /***/ }),
  427. /***/ "./node_modules/antlr4/BufferedTokenStream.js":
  428. /*!****************************************************!*\
  429. !*** ./node_modules/antlr4/BufferedTokenStream.js ***!
  430. \****************************************************/
  431. /*! no static exports found */
  432. /***/ (function(module, exports, __webpack_require__) {
  433. //
  434. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  435. * Use of this file is governed by the BSD 3-clause license that
  436. * can be found in the LICENSE.txt file in the project root.
  437. */
  438. // This implementation of {@link TokenStream} loads tokens from a
  439. // {@link TokenSource} on-demand, and places the tokens in a buffer to provide
  440. // access to any previous token by index.
  441. //
  442. // <p>
  443. // This token stream ignores the value of {@link Token//getChannel}. If your
  444. // parser requires the token stream filter tokens to only those on a particular
  445. // channel, such as {@link Token//DEFAULT_CHANNEL} or
  446. // {@link Token//HIDDEN_CHANNEL}, use a filtering token stream such a
  447. // {@link CommonTokenStream}.</p>
  448. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  449. var Lexer = __webpack_require__(/*! ./Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
  450. var Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  451. // this is just to keep meaningful parameter types to Parser
  452. function TokenStream() {
  453. return this;
  454. }
  455. function BufferedTokenStream(tokenSource) {
  456. TokenStream.call(this);
  457. // The {@link TokenSource} from which tokens for this stream are fetched.
  458. this.tokenSource = tokenSource;
  459. // A collection of all tokens fetched from the token source. The list is
  460. // considered a complete view of the input once {@link //fetchedEOF} is set
  461. // to {@code true}.
  462. this.tokens = [];
  463. // The index into {@link //tokens} of the current token (next token to
  464. // {@link //consume}). {@link //tokens}{@code [}{@link //p}{@code ]} should
  465. // be
  466. // {@link //LT LT(1)}.
  467. //
  468. // <p>This field is set to -1 when the stream is first constructed or when
  469. // {@link //setTokenSource} is called, indicating that the first token has
  470. // not yet been fetched from the token source. For additional information,
  471. // see the documentation of {@link IntStream} for a description of
  472. // Initializing Methods.</p>
  473. this.index = -1;
  474. // Indicates whether the {@link Token//EOF} token has been fetched from
  475. // {@link //tokenSource} and added to {@link //tokens}. This field improves
  476. // performance for the following cases:
  477. //
  478. // <ul>
  479. // <li>{@link //consume}: The lookahead check in {@link //consume} to
  480. // prevent
  481. // consuming the EOF symbol is optimized by checking the values of
  482. // {@link //fetchedEOF} and {@link //p} instead of calling {@link
  483. // //LA}.</li>
  484. // <li>{@link //fetch}: The check to prevent adding multiple EOF symbols
  485. // into
  486. // {@link //tokens} is trivial with this field.</li>
  487. // <ul>
  488. this.fetchedEOF = false;
  489. return this;
  490. }
  491. BufferedTokenStream.prototype = Object.create(TokenStream.prototype);
  492. BufferedTokenStream.prototype.constructor = BufferedTokenStream;
  493. BufferedTokenStream.prototype.mark = function() {
  494. return 0;
  495. };
  496. BufferedTokenStream.prototype.release = function(marker) {
  497. // no resources to release
  498. };
  499. BufferedTokenStream.prototype.reset = function() {
  500. this.seek(0);
  501. };
  502. BufferedTokenStream.prototype.seek = function(index) {
  503. this.lazyInit();
  504. this.index = this.adjustSeekIndex(index);
  505. };
  506. BufferedTokenStream.prototype.get = function(index) {
  507. this.lazyInit();
  508. return this.tokens[index];
  509. };
  510. BufferedTokenStream.prototype.consume = function() {
  511. var skipEofCheck = false;
  512. if (this.index >= 0) {
  513. if (this.fetchedEOF) {
  514. // the last token in tokens is EOF. skip check if p indexes any
  515. // fetched token except the last.
  516. skipEofCheck = this.index < this.tokens.length - 1;
  517. } else {
  518. // no EOF token in tokens. skip check if p indexes a fetched token.
  519. skipEofCheck = this.index < this.tokens.length;
  520. }
  521. } else {
  522. // not yet initialized
  523. skipEofCheck = false;
  524. }
  525. if (!skipEofCheck && this.LA(1) === Token.EOF) {
  526. throw "cannot consume EOF";
  527. }
  528. if (this.sync(this.index + 1)) {
  529. this.index = this.adjustSeekIndex(this.index + 1);
  530. }
  531. };
  532. // Make sure index {@code i} in tokens has a token.
  533. //
  534. // @return {@code true} if a token is located at index {@code i}, otherwise
  535. // {@code false}.
  536. // @see //get(int i)
  537. // /
  538. BufferedTokenStream.prototype.sync = function(i) {
  539. var n = i - this.tokens.length + 1; // how many more elements we need?
  540. if (n > 0) {
  541. var fetched = this.fetch(n);
  542. return fetched >= n;
  543. }
  544. return true;
  545. };
  546. // Add {@code n} elements to buffer.
  547. //
  548. // @return The actual number of elements added to the buffer.
  549. // /
  550. BufferedTokenStream.prototype.fetch = function(n) {
  551. if (this.fetchedEOF) {
  552. return 0;
  553. }
  554. for (var i = 0; i < n; i++) {
  555. var t = this.tokenSource.nextToken();
  556. t.tokenIndex = this.tokens.length;
  557. this.tokens.push(t);
  558. if (t.type === Token.EOF) {
  559. this.fetchedEOF = true;
  560. return i + 1;
  561. }
  562. }
  563. return n;
  564. };
  565. // Get all tokens from start..stop inclusively///
  566. BufferedTokenStream.prototype.getTokens = function(start, stop, types) {
  567. if (types === undefined) {
  568. types = null;
  569. }
  570. if (start < 0 || stop < 0) {
  571. return null;
  572. }
  573. this.lazyInit();
  574. var subset = [];
  575. if (stop >= this.tokens.length) {
  576. stop = this.tokens.length - 1;
  577. }
  578. for (var i = start; i < stop; i++) {
  579. var t = this.tokens[i];
  580. if (t.type === Token.EOF) {
  581. break;
  582. }
  583. if (types === null || types.contains(t.type)) {
  584. subset.push(t);
  585. }
  586. }
  587. return subset;
  588. };
  589. BufferedTokenStream.prototype.LA = function(i) {
  590. return this.LT(i).type;
  591. };
  592. BufferedTokenStream.prototype.LB = function(k) {
  593. if (this.index - k < 0) {
  594. return null;
  595. }
  596. return this.tokens[this.index - k];
  597. };
  598. BufferedTokenStream.prototype.LT = function(k) {
  599. this.lazyInit();
  600. if (k === 0) {
  601. return null;
  602. }
  603. if (k < 0) {
  604. return this.LB(-k);
  605. }
  606. var i = this.index + k - 1;
  607. this.sync(i);
  608. if (i >= this.tokens.length) { // return EOF token
  609. // EOF must be last token
  610. return this.tokens[this.tokens.length - 1];
  611. }
  612. return this.tokens[i];
  613. };
  614. // Allowed derived classes to modify the behavior of operations which change
  615. // the current stream position by adjusting the target token index of a seek
  616. // operation. The default implementation simply returns {@code i}. If an
  617. // exception is thrown in this method, the current stream index should not be
  618. // changed.
  619. //
  620. // <p>For example, {@link CommonTokenStream} overrides this method to ensure
  621. // that
  622. // the seek target is always an on-channel token.</p>
  623. //
  624. // @param i The target token index.
  625. // @return The adjusted target token index.
  626. BufferedTokenStream.prototype.adjustSeekIndex = function(i) {
  627. return i;
  628. };
  629. BufferedTokenStream.prototype.lazyInit = function() {
  630. if (this.index === -1) {
  631. this.setup();
  632. }
  633. };
  634. BufferedTokenStream.prototype.setup = function() {
  635. this.sync(0);
  636. this.index = this.adjustSeekIndex(0);
  637. };
  638. // Reset this token stream by setting its token source.///
  639. BufferedTokenStream.prototype.setTokenSource = function(tokenSource) {
  640. this.tokenSource = tokenSource;
  641. this.tokens = [];
  642. this.index = -1;
  643. this.fetchedEOF = false;
  644. };
  645. // Given a starting index, return the index of the next token on channel.
  646. // Return i if tokens[i] is on channel. Return -1 if there are no tokens
  647. // on channel between i and EOF.
  648. // /
  649. BufferedTokenStream.prototype.nextTokenOnChannel = function(i, channel) {
  650. this.sync(i);
  651. if (i >= this.tokens.length) {
  652. return -1;
  653. }
  654. var token = this.tokens[i];
  655. while (token.channel !== this.channel) {
  656. if (token.type === Token.EOF) {
  657. return -1;
  658. }
  659. i += 1;
  660. this.sync(i);
  661. token = this.tokens[i];
  662. }
  663. return i;
  664. };
  665. // Given a starting index, return the index of the previous token on channel.
  666. // Return i if tokens[i] is on channel. Return -1 if there are no tokens
  667. // on channel between i and 0.
  668. BufferedTokenStream.prototype.previousTokenOnChannel = function(i, channel) {
  669. while (i >= 0 && this.tokens[i].channel !== channel) {
  670. i -= 1;
  671. }
  672. return i;
  673. };
  674. // Collect all tokens on specified channel to the right of
  675. // the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or
  676. // EOF. If channel is -1, find any non default channel token.
  677. BufferedTokenStream.prototype.getHiddenTokensToRight = function(tokenIndex,
  678. channel) {
  679. if (channel === undefined) {
  680. channel = -1;
  681. }
  682. this.lazyInit();
  683. if (tokenIndex < 0 || tokenIndex >= this.tokens.length) {
  684. throw "" + tokenIndex + " not in 0.." + this.tokens.length - 1;
  685. }
  686. var nextOnChannel = this.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL);
  687. var from_ = tokenIndex + 1;
  688. // if none onchannel to right, nextOnChannel=-1 so set to = last token
  689. var to = nextOnChannel === -1 ? this.tokens.length - 1 : nextOnChannel;
  690. return this.filterForChannel(from_, to, channel);
  691. };
  692. // Collect all tokens on specified channel to the left of
  693. // the current token up until we see a token on DEFAULT_TOKEN_CHANNEL.
  694. // If channel is -1, find any non default channel token.
  695. BufferedTokenStream.prototype.getHiddenTokensToLeft = function(tokenIndex,
  696. channel) {
  697. if (channel === undefined) {
  698. channel = -1;
  699. }
  700. this.lazyInit();
  701. if (tokenIndex < 0 || tokenIndex >= this.tokens.length) {
  702. throw "" + tokenIndex + " not in 0.." + this.tokens.length - 1;
  703. }
  704. var prevOnChannel = this.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL);
  705. if (prevOnChannel === tokenIndex - 1) {
  706. return null;
  707. }
  708. // if none on channel to left, prevOnChannel=-1 then from=0
  709. var from_ = prevOnChannel + 1;
  710. var to = tokenIndex - 1;
  711. return this.filterForChannel(from_, to, channel);
  712. };
  713. BufferedTokenStream.prototype.filterForChannel = function(left, right, channel) {
  714. var hidden = [];
  715. for (var i = left; i < right + 1; i++) {
  716. var t = this.tokens[i];
  717. if (channel === -1) {
  718. if (t.channel !== Lexer.DEFAULT_TOKEN_CHANNEL) {
  719. hidden.push(t);
  720. }
  721. } else if (t.channel === channel) {
  722. hidden.push(t);
  723. }
  724. }
  725. if (hidden.length === 0) {
  726. return null;
  727. }
  728. return hidden;
  729. };
  730. BufferedTokenStream.prototype.getSourceName = function() {
  731. return this.tokenSource.getSourceName();
  732. };
  733. // Get the text of all tokens in this buffer.///
  734. BufferedTokenStream.prototype.getText = function(interval) {
  735. this.lazyInit();
  736. this.fill();
  737. if (interval === undefined || interval === null) {
  738. interval = new Interval(0, this.tokens.length - 1);
  739. }
  740. var start = interval.start;
  741. if (start instanceof Token) {
  742. start = start.tokenIndex;
  743. }
  744. var stop = interval.stop;
  745. if (stop instanceof Token) {
  746. stop = stop.tokenIndex;
  747. }
  748. if (start === null || stop === null || start < 0 || stop < 0) {
  749. return "";
  750. }
  751. if (stop >= this.tokens.length) {
  752. stop = this.tokens.length - 1;
  753. }
  754. var s = "";
  755. for (var i = start; i < stop + 1; i++) {
  756. var t = this.tokens[i];
  757. if (t.type === Token.EOF) {
  758. break;
  759. }
  760. s = s + t.text;
  761. }
  762. return s;
  763. };
  764. // Get all tokens from lexer until EOF///
  765. BufferedTokenStream.prototype.fill = function() {
  766. this.lazyInit();
  767. while (this.fetch(1000) === 1000) {
  768. continue;
  769. }
  770. };
  771. exports.BufferedTokenStream = BufferedTokenStream;
  772. /***/ }),
  773. /***/ "./node_modules/antlr4/CharStreams.js":
  774. /*!********************************************!*\
  775. !*** ./node_modules/antlr4/CharStreams.js ***!
  776. \********************************************/
  777. /*! no static exports found */
  778. /***/ (function(module, exports, __webpack_require__) {
  779. //
  780. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  781. * Use of this file is governed by the BSD 3-clause license that
  782. * can be found in the LICENSE.txt file in the project root.
  783. */
  784. //
  785. var InputStream = __webpack_require__(/*! ./InputStream */ "./node_modules/antlr4/InputStream.js").InputStream;
  786. var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined';
  787. var fs = isNodeJs ? __webpack_require__(/*! fs */ "./node_modules/node-libs-browser/mock/empty.js") : null;
  788. // Utility functions to create InputStreams from various sources.
  789. //
  790. // All returned InputStreams support the full range of Unicode
  791. // up to U+10FFFF (the default behavior of InputStream only supports
  792. // code points up to U+FFFF).
  793. var CharStreams = {
  794. // Creates an InputStream from a string.
  795. fromString: function(str) {
  796. return new InputStream(str, true);
  797. },
  798. // Asynchronously creates an InputStream from a blob given the
  799. // encoding of the bytes in that blob (defaults to 'utf8' if
  800. // encoding is null).
  801. //
  802. // Invokes onLoad(result) on success, onError(error) on
  803. // failure.
  804. fromBlob: function(blob, encoding, onLoad, onError) {
  805. var reader = FileReader();
  806. reader.onload = function(e) {
  807. var is = new InputStream(e.target.result, true);
  808. onLoad(is);
  809. };
  810. reader.onerror = onError;
  811. reader.readAsText(blob, encoding);
  812. },
  813. // Creates an InputStream from a Buffer given the
  814. // encoding of the bytes in that buffer (defaults to 'utf8' if
  815. // encoding is null).
  816. fromBuffer: function(buffer, encoding) {
  817. return new InputStream(buffer.toString(encoding), true);
  818. },
  819. // Asynchronously creates an InputStream from a file on disk given
  820. // the encoding of the bytes in that file (defaults to 'utf8' if
  821. // encoding is null).
  822. //
  823. // Invokes callback(error, result) on completion.
  824. fromPath: function(path, encoding, callback) {
  825. fs.readFile(path, encoding, function(err, data) {
  826. var is = null;
  827. if (data !== null) {
  828. is = new InputStream(data, true);
  829. }
  830. callback(err, is);
  831. });
  832. },
  833. // Synchronously creates an InputStream given a path to a file
  834. // on disk and the encoding of the bytes in that file (defaults to
  835. // 'utf8' if encoding is null).
  836. fromPathSync: function(path, encoding) {
  837. var data = fs.readFileSync(path, encoding);
  838. return new InputStream(data, true);
  839. }
  840. };
  841. exports.CharStreams = CharStreams;
  842. /***/ }),
  843. /***/ "./node_modules/antlr4/CommonTokenFactory.js":
  844. /*!***************************************************!*\
  845. !*** ./node_modules/antlr4/CommonTokenFactory.js ***!
  846. \***************************************************/
  847. /*! no static exports found */
  848. /***/ (function(module, exports, __webpack_require__) {
  849. //
  850. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  851. * Use of this file is governed by the BSD 3-clause license that
  852. * can be found in the LICENSE.txt file in the project root.
  853. */
  854. //
  855. //
  856. // This default implementation of {@link TokenFactory} creates
  857. // {@link CommonToken} objects.
  858. //
  859. var CommonToken = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").CommonToken;
  860. function TokenFactory() {
  861. return this;
  862. }
  863. function CommonTokenFactory(copyText) {
  864. TokenFactory.call(this);
  865. // Indicates whether {@link CommonToken//setText} should be called after
  866. // constructing tokens to explicitly set the text. This is useful for cases
  867. // where the input stream might not be able to provide arbitrary substrings
  868. // of text from the input after the lexer creates a token (e.g. the
  869. // implementation of {@link CharStream//getText} in
  870. // {@link UnbufferedCharStream} throws an
  871. // {@link UnsupportedOperationException}). Explicitly setting the token text
  872. // allows {@link Token//getText} to be called at any time regardless of the
  873. // input stream implementation.
  874. //
  875. // <p>
  876. // The default value is {@code false} to avoid the performance and memory
  877. // overhead of copying text for every token unless explicitly requested.</p>
  878. //
  879. this.copyText = copyText===undefined ? false : copyText;
  880. return this;
  881. }
  882. CommonTokenFactory.prototype = Object.create(TokenFactory.prototype);
  883. CommonTokenFactory.prototype.constructor = CommonTokenFactory;
  884. //
  885. // The default {@link CommonTokenFactory} instance.
  886. //
  887. // <p>
  888. // This token factory does not explicitly copy token text when constructing
  889. // tokens.</p>
  890. //
  891. CommonTokenFactory.DEFAULT = new CommonTokenFactory();
  892. CommonTokenFactory.prototype.create = function(source, type, text, channel, start, stop, line, column) {
  893. var t = new CommonToken(source, type, channel, start, stop);
  894. t.line = line;
  895. t.column = column;
  896. if (text !==null) {
  897. t.text = text;
  898. } else if (this.copyText && source[1] !==null) {
  899. t.text = source[1].getText(start,stop);
  900. }
  901. return t;
  902. };
  903. CommonTokenFactory.prototype.createThin = function(type, text) {
  904. var t = new CommonToken(null, type);
  905. t.text = text;
  906. return t;
  907. };
  908. exports.CommonTokenFactory = CommonTokenFactory;
  909. /***/ }),
  910. /***/ "./node_modules/antlr4/CommonTokenStream.js":
  911. /*!**************************************************!*\
  912. !*** ./node_modules/antlr4/CommonTokenStream.js ***!
  913. \**************************************************/
  914. /*! no static exports found */
  915. /***/ (function(module, exports, __webpack_require__) {
  916. //
  917. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  918. * Use of this file is governed by the BSD 3-clause license that
  919. * can be found in the LICENSE.txt file in the project root.
  920. */
  921. ///
  922. //
  923. // This class extends {@link BufferedTokenStream} with functionality to filter
  924. // token streams to tokens on a particular channel (tokens where
  925. // {@link Token//getChannel} returns a particular value).
  926. //
  927. // <p>
  928. // This token stream provides access to all tokens by index or when calling
  929. // methods like {@link //getText}. The channel filtering is only used for code
  930. // accessing tokens via the lookahead methods {@link //LA}, {@link //LT}, and
  931. // {@link //LB}.</p>
  932. //
  933. // <p>
  934. // By default, tokens are placed on the default channel
  935. // ({@link Token//DEFAULT_CHANNEL}), but may be reassigned by using the
  936. // {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to
  937. // call {@link Lexer//setChannel}.
  938. // </p>
  939. //
  940. // <p>
  941. // Note: lexer rules which use the {@code ->skip} lexer command or call
  942. // {@link Lexer//skip} do not produce tokens at all, so input text matched by
  943. // such a rule will not be available as part of the token stream, regardless of
  944. // channel.</p>
  945. ///
  946. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  947. var BufferedTokenStream = __webpack_require__(/*! ./BufferedTokenStream */ "./node_modules/antlr4/BufferedTokenStream.js").BufferedTokenStream;
  948. function CommonTokenStream(lexer, channel) {
  949. BufferedTokenStream.call(this, lexer);
  950. this.channel = channel===undefined ? Token.DEFAULT_CHANNEL : channel;
  951. return this;
  952. }
  953. CommonTokenStream.prototype = Object.create(BufferedTokenStream.prototype);
  954. CommonTokenStream.prototype.constructor = CommonTokenStream;
  955. CommonTokenStream.prototype.adjustSeekIndex = function(i) {
  956. return this.nextTokenOnChannel(i, this.channel);
  957. };
  958. CommonTokenStream.prototype.LB = function(k) {
  959. if (k===0 || this.index-k<0) {
  960. return null;
  961. }
  962. var i = this.index;
  963. var n = 1;
  964. // find k good tokens looking backwards
  965. while (n <= k) {
  966. // skip off-channel tokens
  967. i = this.previousTokenOnChannel(i - 1, this.channel);
  968. n += 1;
  969. }
  970. if (i < 0) {
  971. return null;
  972. }
  973. return this.tokens[i];
  974. };
  975. CommonTokenStream.prototype.LT = function(k) {
  976. this.lazyInit();
  977. if (k === 0) {
  978. return null;
  979. }
  980. if (k < 0) {
  981. return this.LB(-k);
  982. }
  983. var i = this.index;
  984. var n = 1; // we know tokens[pos] is a good one
  985. // find k good tokens
  986. while (n < k) {
  987. // skip off-channel tokens, but make sure to not look past EOF
  988. if (this.sync(i + 1)) {
  989. i = this.nextTokenOnChannel(i + 1, this.channel);
  990. }
  991. n += 1;
  992. }
  993. return this.tokens[i];
  994. };
  995. // Count EOF just once.///
  996. CommonTokenStream.prototype.getNumberOfOnChannelTokens = function() {
  997. var n = 0;
  998. this.fill();
  999. for (var i =0; i< this.tokens.length;i++) {
  1000. var t = this.tokens[i];
  1001. if( t.channel===this.channel) {
  1002. n += 1;
  1003. }
  1004. if( t.type===Token.EOF) {
  1005. break;
  1006. }
  1007. }
  1008. return n;
  1009. };
  1010. exports.CommonTokenStream = CommonTokenStream;
  1011. /***/ }),
  1012. /***/ "./node_modules/antlr4/FileStream.js":
  1013. /*!*******************************************!*\
  1014. !*** ./node_modules/antlr4/FileStream.js ***!
  1015. \*******************************************/
  1016. /*! no static exports found */
  1017. /***/ (function(module, exports, __webpack_require__) {
  1018. //
  1019. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  1020. * Use of this file is governed by the BSD 3-clause license that
  1021. * can be found in the LICENSE.txt file in the project root.
  1022. */
  1023. //
  1024. //
  1025. // This is an InputStream that is loaded from a file all at once
  1026. // when you construct the object.
  1027. //
  1028. var InputStream = __webpack_require__(/*! ./InputStream */ "./node_modules/antlr4/InputStream.js").InputStream;
  1029. var isNodeJs = typeof window === 'undefined' && typeof importScripts === 'undefined';
  1030. var fs = isNodeJs ? __webpack_require__(/*! fs */ "./node_modules/node-libs-browser/mock/empty.js") : null;
  1031. function FileStream(fileName, decodeToUnicodeCodePoints) {
  1032. var data = fs.readFileSync(fileName, "utf8");
  1033. InputStream.call(this, data, decodeToUnicodeCodePoints);
  1034. this.fileName = fileName;
  1035. return this;
  1036. }
  1037. FileStream.prototype = Object.create(InputStream.prototype);
  1038. FileStream.prototype.constructor = FileStream;
  1039. exports.FileStream = FileStream;
  1040. /***/ }),
  1041. /***/ "./node_modules/antlr4/InputStream.js":
  1042. /*!********************************************!*\
  1043. !*** ./node_modules/antlr4/InputStream.js ***!
  1044. \********************************************/
  1045. /*! no static exports found */
  1046. /***/ (function(module, exports, __webpack_require__) {
  1047. //
  1048. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  1049. * Use of this file is governed by the BSD 3-clause license that
  1050. * can be found in the LICENSE.txt file in the project root.
  1051. */
  1052. //
  1053. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  1054. __webpack_require__(/*! ./polyfills/codepointat */ "./node_modules/antlr4/polyfills/codepointat.js");
  1055. __webpack_require__(/*! ./polyfills/fromcodepoint */ "./node_modules/antlr4/polyfills/fromcodepoint.js");
  1056. // Vacuum all input from a string and then treat it like a buffer.
  1057. function _loadString(stream) {
  1058. stream._index = 0;
  1059. stream.data = [];
  1060. if (stream.decodeToUnicodeCodePoints) {
  1061. for (var i = 0; i < stream.strdata.length; ) {
  1062. var codePoint = stream.strdata.codePointAt(i);
  1063. stream.data.push(codePoint);
  1064. i += codePoint <= 0xFFFF ? 1 : 2;
  1065. }
  1066. } else {
  1067. for (var i = 0; i < stream.strdata.length; i++) {
  1068. var codeUnit = stream.strdata.charCodeAt(i);
  1069. stream.data.push(codeUnit);
  1070. }
  1071. }
  1072. stream._size = stream.data.length;
  1073. }
  1074. // If decodeToUnicodeCodePoints is true, the input is treated
  1075. // as a series of Unicode code points.
  1076. //
  1077. // Otherwise, the input is treated as a series of 16-bit UTF-16 code
  1078. // units.
  1079. function InputStream(data, decodeToUnicodeCodePoints) {
  1080. this.name = "<empty>";
  1081. this.strdata = data;
  1082. this.decodeToUnicodeCodePoints = decodeToUnicodeCodePoints || false;
  1083. _loadString(this);
  1084. return this;
  1085. }
  1086. Object.defineProperty(InputStream.prototype, "index", {
  1087. get : function() {
  1088. return this._index;
  1089. }
  1090. });
  1091. Object.defineProperty(InputStream.prototype, "size", {
  1092. get : function() {
  1093. return this._size;
  1094. }
  1095. });
  1096. // Reset the stream so that it's in the same state it was
  1097. // when the object was created *except* the data array is not
  1098. // touched.
  1099. //
  1100. InputStream.prototype.reset = function() {
  1101. this._index = 0;
  1102. };
  1103. InputStream.prototype.consume = function() {
  1104. if (this._index >= this._size) {
  1105. // assert this.LA(1) == Token.EOF
  1106. throw ("cannot consume EOF");
  1107. }
  1108. this._index += 1;
  1109. };
  1110. InputStream.prototype.LA = function(offset) {
  1111. if (offset === 0) {
  1112. return 0; // undefined
  1113. }
  1114. if (offset < 0) {
  1115. offset += 1; // e.g., translate LA(-1) to use offset=0
  1116. }
  1117. var pos = this._index + offset - 1;
  1118. if (pos < 0 || pos >= this._size) { // invalid
  1119. return Token.EOF;
  1120. }
  1121. return this.data[pos];
  1122. };
  1123. InputStream.prototype.LT = function(offset) {
  1124. return this.LA(offset);
  1125. };
  1126. // mark/release do nothing; we have entire buffer
  1127. InputStream.prototype.mark = function() {
  1128. return -1;
  1129. };
  1130. InputStream.prototype.release = function(marker) {
  1131. };
  1132. // consume() ahead until p==_index; can't just set p=_index as we must
  1133. // update line and column. If we seek backwards, just set p
  1134. //
  1135. InputStream.prototype.seek = function(_index) {
  1136. if (_index <= this._index) {
  1137. this._index = _index; // just jump; don't update stream state (line,
  1138. // ...)
  1139. return;
  1140. }
  1141. // seek forward
  1142. this._index = Math.min(_index, this._size);
  1143. };
  1144. InputStream.prototype.getText = function(start, stop) {
  1145. if (stop >= this._size) {
  1146. stop = this._size - 1;
  1147. }
  1148. if (start >= this._size) {
  1149. return "";
  1150. } else {
  1151. if (this.decodeToUnicodeCodePoints) {
  1152. var result = "";
  1153. for (var i = start; i <= stop; i++) {
  1154. result += String.fromCodePoint(this.data[i]);
  1155. }
  1156. return result;
  1157. } else {
  1158. return this.strdata.slice(start, stop + 1);
  1159. }
  1160. }
  1161. };
  1162. InputStream.prototype.toString = function() {
  1163. return this.strdata;
  1164. };
  1165. exports.InputStream = InputStream;
  1166. /***/ }),
  1167. /***/ "./node_modules/antlr4/IntervalSet.js":
  1168. /*!********************************************!*\
  1169. !*** ./node_modules/antlr4/IntervalSet.js ***!
  1170. \********************************************/
  1171. /*! no static exports found */
  1172. /***/ (function(module, exports, __webpack_require__) {
  1173. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  1174. * Use of this file is governed by the BSD 3-clause license that
  1175. * can be found in the LICENSE.txt file in the project root.
  1176. */
  1177. /*jslint smarttabs:true */
  1178. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  1179. /* stop is not included! */
  1180. function Interval(start, stop) {
  1181. this.start = start;
  1182. this.stop = stop;
  1183. return this;
  1184. }
  1185. Interval.prototype.contains = function(item) {
  1186. return item >= this.start && item < this.stop;
  1187. };
  1188. Interval.prototype.toString = function() {
  1189. if(this.start===this.stop-1) {
  1190. return this.start.toString();
  1191. } else {
  1192. return this.start.toString() + ".." + (this.stop-1).toString();
  1193. }
  1194. };
  1195. Object.defineProperty(Interval.prototype, "length", {
  1196. get : function() {
  1197. return this.stop - this.start;
  1198. }
  1199. });
  1200. function IntervalSet() {
  1201. this.intervals = null;
  1202. this.readOnly = false;
  1203. }
  1204. IntervalSet.prototype.first = function(v) {
  1205. if (this.intervals === null || this.intervals.length===0) {
  1206. return Token.INVALID_TYPE;
  1207. } else {
  1208. return this.intervals[0].start;
  1209. }
  1210. };
  1211. IntervalSet.prototype.addOne = function(v) {
  1212. this.addInterval(new Interval(v, v + 1));
  1213. };
  1214. IntervalSet.prototype.addRange = function(l, h) {
  1215. this.addInterval(new Interval(l, h + 1));
  1216. };
  1217. IntervalSet.prototype.addInterval = function(v) {
  1218. if (this.intervals === null) {
  1219. this.intervals = [];
  1220. this.intervals.push(v);
  1221. } else {
  1222. // find insert pos
  1223. for (var k = 0; k < this.intervals.length; k++) {
  1224. var i = this.intervals[k];
  1225. // distinct range -> insert
  1226. if (v.stop < i.start) {
  1227. this.intervals.splice(k, 0, v);
  1228. return;
  1229. }
  1230. // contiguous range -> adjust
  1231. else if (v.stop === i.start) {
  1232. this.intervals[k].start = v.start;
  1233. return;
  1234. }
  1235. // overlapping range -> adjust and reduce
  1236. else if (v.start <= i.stop) {
  1237. this.intervals[k] = new Interval(Math.min(i.start, v.start), Math.max(i.stop, v.stop));
  1238. this.reduce(k);
  1239. return;
  1240. }
  1241. }
  1242. // greater than any existing
  1243. this.intervals.push(v);
  1244. }
  1245. };
  1246. IntervalSet.prototype.addSet = function(other) {
  1247. if (other.intervals !== null) {
  1248. for (var k = 0; k < other.intervals.length; k++) {
  1249. var i = other.intervals[k];
  1250. this.addInterval(new Interval(i.start, i.stop));
  1251. }
  1252. }
  1253. return this;
  1254. };
  1255. IntervalSet.prototype.reduce = function(k) {
  1256. // only need to reduce if k is not the last
  1257. if (k < this.intervalslength - 1) {
  1258. var l = this.intervals[k];
  1259. var r = this.intervals[k + 1];
  1260. // if r contained in l
  1261. if (l.stop >= r.stop) {
  1262. this.intervals.pop(k + 1);
  1263. this.reduce(k);
  1264. } else if (l.stop >= r.start) {
  1265. this.intervals[k] = new Interval(l.start, r.stop);
  1266. this.intervals.pop(k + 1);
  1267. }
  1268. }
  1269. };
  1270. IntervalSet.prototype.complement = function(start, stop) {
  1271. var result = new IntervalSet();
  1272. result.addInterval(new Interval(start,stop+1));
  1273. for(var i=0; i<this.intervals.length; i++) {
  1274. result.removeRange(this.intervals[i]);
  1275. }
  1276. return result;
  1277. };
  1278. IntervalSet.prototype.contains = function(item) {
  1279. if (this.intervals === null) {
  1280. return false;
  1281. } else {
  1282. for (var k = 0; k < this.intervals.length; k++) {
  1283. if(this.intervals[k].contains(item)) {
  1284. return true;
  1285. }
  1286. }
  1287. return false;
  1288. }
  1289. };
  1290. Object.defineProperty(IntervalSet.prototype, "length", {
  1291. get : function() {
  1292. var len = 0;
  1293. this.intervals.map(function(i) {len += i.length;});
  1294. return len;
  1295. }
  1296. });
  1297. IntervalSet.prototype.removeRange = function(v) {
  1298. if(v.start===v.stop-1) {
  1299. this.removeOne(v.start);
  1300. } else if (this.intervals!==null) {
  1301. var k = 0;
  1302. for(var n=0; n<this.intervals.length; n++) {
  1303. var i = this.intervals[k];
  1304. // intervals are ordered
  1305. if (v.stop<=i.start) {
  1306. return;
  1307. }
  1308. // check for including range, split it
  1309. else if(v.start>i.start && v.stop<i.stop) {
  1310. this.intervals[k] = new Interval(i.start, v.start);
  1311. var x = new Interval(v.stop, i.stop);
  1312. this.intervals.splice(k, 0, x);
  1313. return;
  1314. }
  1315. // check for included range, remove it
  1316. else if(v.start<=i.start && v.stop>=i.stop) {
  1317. this.intervals.splice(k, 1);
  1318. k = k - 1; // need another pass
  1319. }
  1320. // check for lower boundary
  1321. else if(v.start<i.stop) {
  1322. this.intervals[k] = new Interval(i.start, v.start);
  1323. }
  1324. // check for upper boundary
  1325. else if(v.stop<i.stop) {
  1326. this.intervals[k] = new Interval(v.stop, i.stop);
  1327. }
  1328. k += 1;
  1329. }
  1330. }
  1331. };
  1332. IntervalSet.prototype.removeOne = function(v) {
  1333. if (this.intervals !== null) {
  1334. for (var k = 0; k < this.intervals.length; k++) {
  1335. var i = this.intervals[k];
  1336. // intervals is ordered
  1337. if (v < i.start) {
  1338. return;
  1339. }
  1340. // check for single value range
  1341. else if (v === i.start && v === i.stop - 1) {
  1342. this.intervals.splice(k, 1);
  1343. return;
  1344. }
  1345. // check for lower boundary
  1346. else if (v === i.start) {
  1347. this.intervals[k] = new Interval(i.start + 1, i.stop);
  1348. return;
  1349. }
  1350. // check for upper boundary
  1351. else if (v === i.stop - 1) {
  1352. this.intervals[k] = new Interval(i.start, i.stop - 1);
  1353. return;
  1354. }
  1355. // split existing range
  1356. else if (v < i.stop - 1) {
  1357. var x = new Interval(i.start, v);
  1358. i.start = v + 1;
  1359. this.intervals.splice(k, 0, x);
  1360. return;
  1361. }
  1362. }
  1363. }
  1364. };
  1365. IntervalSet.prototype.toString = function(literalNames, symbolicNames, elemsAreChar) {
  1366. literalNames = literalNames || null;
  1367. symbolicNames = symbolicNames || null;
  1368. elemsAreChar = elemsAreChar || false;
  1369. if (this.intervals === null) {
  1370. return "{}";
  1371. } else if(literalNames!==null || symbolicNames!==null) {
  1372. return this.toTokenString(literalNames, symbolicNames);
  1373. } else if(elemsAreChar) {
  1374. return this.toCharString();
  1375. } else {
  1376. return this.toIndexString();
  1377. }
  1378. };
  1379. IntervalSet.prototype.toCharString = function() {
  1380. var names = [];
  1381. for (var i = 0; i < this.intervals.length; i++) {
  1382. var v = this.intervals[i];
  1383. if(v.stop===v.start+1) {
  1384. if ( v.start===Token.EOF ) {
  1385. names.push("<EOF>");
  1386. } else {
  1387. names.push("'" + String.fromCharCode(v.start) + "'");
  1388. }
  1389. } else {
  1390. names.push("'" + String.fromCharCode(v.start) + "'..'" + String.fromCharCode(v.stop-1) + "'");
  1391. }
  1392. }
  1393. if (names.length > 1) {
  1394. return "{" + names.join(", ") + "}";
  1395. } else {
  1396. return names[0];
  1397. }
  1398. };
  1399. IntervalSet.prototype.toIndexString = function() {
  1400. var names = [];
  1401. for (var i = 0; i < this.intervals.length; i++) {
  1402. var v = this.intervals[i];
  1403. if(v.stop===v.start+1) {
  1404. if ( v.start===Token.EOF ) {
  1405. names.push("<EOF>");
  1406. } else {
  1407. names.push(v.start.toString());
  1408. }
  1409. } else {
  1410. names.push(v.start.toString() + ".." + (v.stop-1).toString());
  1411. }
  1412. }
  1413. if (names.length > 1) {
  1414. return "{" + names.join(", ") + "}";
  1415. } else {
  1416. return names[0];
  1417. }
  1418. };
  1419. IntervalSet.prototype.toTokenString = function(literalNames, symbolicNames) {
  1420. var names = [];
  1421. for (var i = 0; i < this.intervals.length; i++) {
  1422. var v = this.intervals[i];
  1423. for (var j = v.start; j < v.stop; j++) {
  1424. names.push(this.elementName(literalNames, symbolicNames, j));
  1425. }
  1426. }
  1427. if (names.length > 1) {
  1428. return "{" + names.join(", ") + "}";
  1429. } else {
  1430. return names[0];
  1431. }
  1432. };
  1433. IntervalSet.prototype.elementName = function(literalNames, symbolicNames, a) {
  1434. if (a === Token.EOF) {
  1435. return "<EOF>";
  1436. } else if (a === Token.EPSILON) {
  1437. return "<EPSILON>";
  1438. } else {
  1439. return literalNames[a] || symbolicNames[a];
  1440. }
  1441. };
  1442. exports.Interval = Interval;
  1443. exports.IntervalSet = IntervalSet;
  1444. /***/ }),
  1445. /***/ "./node_modules/antlr4/LL1Analyzer.js":
  1446. /*!********************************************!*\
  1447. !*** ./node_modules/antlr4/LL1Analyzer.js ***!
  1448. \********************************************/
  1449. /*! no static exports found */
  1450. /***/ (function(module, exports, __webpack_require__) {
  1451. //
  1452. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  1453. * Use of this file is governed by the BSD 3-clause license that
  1454. * can be found in the LICENSE.txt file in the project root.
  1455. */
  1456. ///
  1457. var Set = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").Set;
  1458. var BitSet = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").BitSet;
  1459. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  1460. var ATNConfig = __webpack_require__(/*! ./atn/ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").ATNConfig;
  1461. var Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  1462. var IntervalSet = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  1463. var RuleStopState = __webpack_require__(/*! ./atn/ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
  1464. var RuleTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").RuleTransition;
  1465. var NotSetTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").NotSetTransition;
  1466. var WildcardTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").WildcardTransition;
  1467. var AbstractPredicateTransition = __webpack_require__(/*! ./atn/Transition */ "./node_modules/antlr4/atn/Transition.js").AbstractPredicateTransition;
  1468. var pc = __webpack_require__(/*! ./PredictionContext */ "./node_modules/antlr4/PredictionContext.js");
  1469. var predictionContextFromRuleContext = pc.predictionContextFromRuleContext;
  1470. var PredictionContext = pc.PredictionContext;
  1471. var SingletonPredictionContext = pc.SingletonPredictionContext;
  1472. function LL1Analyzer (atn) {
  1473. this.atn = atn;
  1474. }
  1475. //* Special value added to the lookahead sets to indicate that we hit
  1476. // a predicate during analysis if {@code seeThruPreds==false}.
  1477. ///
  1478. LL1Analyzer.HIT_PRED = Token.INVALID_TYPE;
  1479. //*
  1480. // Calculates the SLL(1) expected lookahead set for each outgoing transition
  1481. // of an {@link ATNState}. The returned array has one element for each
  1482. // outgoing transition in {@code s}. If the closure from transition
  1483. // <em>i</em> leads to a semantic predicate before matching a symbol, the
  1484. // element at index <em>i</em> of the result will be {@code null}.
  1485. //
  1486. // @param s the ATN state
  1487. // @return the expected symbols for each outgoing transition of {@code s}.
  1488. ///
  1489. LL1Analyzer.prototype.getDecisionLookahead = function(s) {
  1490. if (s === null) {
  1491. return null;
  1492. }
  1493. var count = s.transitions.length;
  1494. var look = [];
  1495. for(var alt=0; alt< count; alt++) {
  1496. look[alt] = new IntervalSet();
  1497. var lookBusy = new Set();
  1498. var seeThruPreds = false; // fail to get lookahead upon pred
  1499. this._LOOK(s.transition(alt).target, null, PredictionContext.EMPTY,
  1500. look[alt], lookBusy, new BitSet(), seeThruPreds, false);
  1501. // Wipe out lookahead for this alternative if we found nothing
  1502. // or we had a predicate when we !seeThruPreds
  1503. if (look[alt].length===0 || look[alt].contains(LL1Analyzer.HIT_PRED)) {
  1504. look[alt] = null;
  1505. }
  1506. }
  1507. return look;
  1508. };
  1509. //*
  1510. // Compute set of tokens that can follow {@code s} in the ATN in the
  1511. // specified {@code ctx}.
  1512. //
  1513. // <p>If {@code ctx} is {@code null} and the end of the rule containing
  1514. // {@code s} is reached, {@link Token//EPSILON} is added to the result set.
  1515. // If {@code ctx} is not {@code null} and the end of the outermost rule is
  1516. // reached, {@link Token//EOF} is added to the result set.</p>
  1517. //
  1518. // @param s the ATN state
  1519. // @param stopState the ATN state to stop at. This can be a
  1520. // {@link BlockEndState} to detect epsilon paths through a closure.
  1521. // @param ctx the complete parser context, or {@code null} if the context
  1522. // should be ignored
  1523. //
  1524. // @return The set of tokens that can follow {@code s} in the ATN in the
  1525. // specified {@code ctx}.
  1526. ///
  1527. LL1Analyzer.prototype.LOOK = function(s, stopState, ctx) {
  1528. var r = new IntervalSet();
  1529. var seeThruPreds = true; // ignore preds; get all lookahead
  1530. ctx = ctx || null;
  1531. var lookContext = ctx!==null ? predictionContextFromRuleContext(s.atn, ctx) : null;
  1532. this._LOOK(s, stopState, lookContext, r, new Set(), new BitSet(), seeThruPreds, true);
  1533. return r;
  1534. };
  1535. //*
  1536. // Compute set of tokens that can follow {@code s} in the ATN in the
  1537. // specified {@code ctx}.
  1538. //
  1539. // <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the
  1540. // rule containing {@code s} is reached, {@link Token//EPSILON} is added to
  1541. // the result set. If {@code ctx} is not {@code null} and {@code addEOF} is
  1542. // {@code true} and {@code stopState} or the end of the outermost rule is
  1543. // reached, {@link Token//EOF} is added to the result set.</p>
  1544. //
  1545. // @param s the ATN state.
  1546. // @param stopState the ATN state to stop at. This can be a
  1547. // {@link BlockEndState} to detect epsilon paths through a closure.
  1548. // @param ctx The outer context, or {@code null} if the outer context should
  1549. // not be used.
  1550. // @param look The result lookahead set.
  1551. // @param lookBusy A set used for preventing epsilon closures in the ATN
  1552. // from causing a stack overflow. Outside code should pass
  1553. // {@code new Set<ATNConfig>} for this argument.
  1554. // @param calledRuleStack A set used for preventing left recursion in the
  1555. // ATN from causing a stack overflow. Outside code should pass
  1556. // {@code new BitSet()} for this argument.
  1557. // @param seeThruPreds {@code true} to true semantic predicates as
  1558. // implicitly {@code true} and "see through them", otherwise {@code false}
  1559. // to treat semantic predicates as opaque and add {@link //HIT_PRED} to the
  1560. // result if one is encountered.
  1561. // @param addEOF Add {@link Token//EOF} to the result if the end of the
  1562. // outermost context is reached. This parameter has no effect if {@code ctx}
  1563. // is {@code null}.
  1564. ///
  1565. LL1Analyzer.prototype._LOOK = function(s, stopState , ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) {
  1566. var c = new ATNConfig({state:s, alt:0, context: ctx}, null);
  1567. if (lookBusy.contains(c)) {
  1568. return;
  1569. }
  1570. lookBusy.add(c);
  1571. if (s === stopState) {
  1572. if (ctx ===null) {
  1573. look.addOne(Token.EPSILON);
  1574. return;
  1575. } else if (ctx.isEmpty() && addEOF) {
  1576. look.addOne(Token.EOF);
  1577. return;
  1578. }
  1579. }
  1580. if (s instanceof RuleStopState ) {
  1581. if (ctx ===null) {
  1582. look.addOne(Token.EPSILON);
  1583. return;
  1584. } else if (ctx.isEmpty() && addEOF) {
  1585. look.addOne(Token.EOF);
  1586. return;
  1587. }
  1588. if (ctx !== PredictionContext.EMPTY) {
  1589. // run thru all possible stack tops in ctx
  1590. for(var i=0; i<ctx.length; i++) {
  1591. var returnState = this.atn.states[ctx.getReturnState(i)];
  1592. var removed = calledRuleStack.contains(returnState.ruleIndex);
  1593. try {
  1594. calledRuleStack.remove(returnState.ruleIndex);
  1595. this._LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
  1596. } finally {
  1597. if (removed) {
  1598. calledRuleStack.add(returnState.ruleIndex);
  1599. }
  1600. }
  1601. }
  1602. return;
  1603. }
  1604. }
  1605. for(var j=0; j<s.transitions.length; j++) {
  1606. var t = s.transitions[j];
  1607. if (t.constructor === RuleTransition) {
  1608. if (calledRuleStack.contains(t.target.ruleIndex)) {
  1609. continue;
  1610. }
  1611. var newContext = SingletonPredictionContext.create(ctx, t.followState.stateNumber);
  1612. try {
  1613. calledRuleStack.add(t.target.ruleIndex);
  1614. this._LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
  1615. } finally {
  1616. calledRuleStack.remove(t.target.ruleIndex);
  1617. }
  1618. } else if (t instanceof AbstractPredicateTransition ) {
  1619. if (seeThruPreds) {
  1620. this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
  1621. } else {
  1622. look.addOne(LL1Analyzer.HIT_PRED);
  1623. }
  1624. } else if( t.isEpsilon) {
  1625. this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF);
  1626. } else if (t.constructor === WildcardTransition) {
  1627. look.addRange( Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType );
  1628. } else {
  1629. var set = t.label;
  1630. if (set !== null) {
  1631. if (t instanceof NotSetTransition) {
  1632. set = set.complement(Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType);
  1633. }
  1634. look.addSet(set);
  1635. }
  1636. }
  1637. }
  1638. };
  1639. exports.LL1Analyzer = LL1Analyzer;
  1640. /***/ }),
  1641. /***/ "./node_modules/antlr4/Lexer.js":
  1642. /*!**************************************!*\
  1643. !*** ./node_modules/antlr4/Lexer.js ***!
  1644. \**************************************/
  1645. /*! no static exports found */
  1646. /***/ (function(module, exports, __webpack_require__) {
  1647. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  1648. * Use of this file is governed by the BSD 3-clause license that
  1649. * can be found in the LICENSE.txt file in the project root.
  1650. */
  1651. ///
  1652. // A lexer is recognizer that draws input symbols from a character stream.
  1653. // lexer grammars result in a subclass of this object. A Lexer object
  1654. // uses simplified match() and error recovery mechanisms in the interest of speed.
  1655. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  1656. var Recognizer = __webpack_require__(/*! ./Recognizer */ "./node_modules/antlr4/Recognizer.js").Recognizer;
  1657. var CommonTokenFactory = __webpack_require__(/*! ./CommonTokenFactory */ "./node_modules/antlr4/CommonTokenFactory.js").CommonTokenFactory;
  1658. var RecognitionException = __webpack_require__(/*! ./error/Errors */ "./node_modules/antlr4/error/Errors.js").RecognitionException;
  1659. var LexerNoViableAltException = __webpack_require__(/*! ./error/Errors */ "./node_modules/antlr4/error/Errors.js").LexerNoViableAltException;
  1660. function TokenSource() {
  1661. return this;
  1662. }
  1663. function Lexer(input) {
  1664. Recognizer.call(this);
  1665. this._input = input;
  1666. this._factory = CommonTokenFactory.DEFAULT;
  1667. this._tokenFactorySourcePair = [ this, input ];
  1668. this._interp = null; // child classes must populate this
  1669. // The goal of all lexer rules/methods is to create a token object.
  1670. // this is an instance variable as multiple rules may collaborate to
  1671. // create a single token. nextToken will return this object after
  1672. // matching lexer rule(s). If you subclass to allow multiple token
  1673. // emissions, then set this to the last token to be matched or
  1674. // something nonnull so that the auto token emit mechanism will not
  1675. // emit another token.
  1676. this._token = null;
  1677. // What character index in the stream did the current token start at?
  1678. // Needed, for example, to get the text for current token. Set at
  1679. // the start of nextToken.
  1680. this._tokenStartCharIndex = -1;
  1681. // The line on which the first character of the token resides///
  1682. this._tokenStartLine = -1;
  1683. // The character position of first character within the line///
  1684. this._tokenStartColumn = -1;
  1685. // Once we see EOF on char stream, next token will be EOF.
  1686. // If you have DONE : EOF ; then you see DONE EOF.
  1687. this._hitEOF = false;
  1688. // The channel number for the current token///
  1689. this._channel = Token.DEFAULT_CHANNEL;
  1690. // The token type for the current token///
  1691. this._type = Token.INVALID_TYPE;
  1692. this._modeStack = [];
  1693. this._mode = Lexer.DEFAULT_MODE;
  1694. // You can set the text for the current token to override what is in
  1695. // the input char buffer. Use setText() or can set this instance var.
  1696. // /
  1697. this._text = null;
  1698. return this;
  1699. }
  1700. Lexer.prototype = Object.create(Recognizer.prototype);
  1701. Lexer.prototype.constructor = Lexer;
  1702. Lexer.DEFAULT_MODE = 0;
  1703. Lexer.MORE = -2;
  1704. Lexer.SKIP = -3;
  1705. Lexer.DEFAULT_TOKEN_CHANNEL = Token.DEFAULT_CHANNEL;
  1706. Lexer.HIDDEN = Token.HIDDEN_CHANNEL;
  1707. Lexer.MIN_CHAR_VALUE = 0x0000;
  1708. Lexer.MAX_CHAR_VALUE = 0x10FFFF;
  1709. Lexer.prototype.reset = function() {
  1710. // wack Lexer state variables
  1711. if (this._input !== null) {
  1712. this._input.seek(0); // rewind the input
  1713. }
  1714. this._token = null;
  1715. this._type = Token.INVALID_TYPE;
  1716. this._channel = Token.DEFAULT_CHANNEL;
  1717. this._tokenStartCharIndex = -1;
  1718. this._tokenStartColumn = -1;
  1719. this._tokenStartLine = -1;
  1720. this._text = null;
  1721. this._hitEOF = false;
  1722. this._mode = Lexer.DEFAULT_MODE;
  1723. this._modeStack = [];
  1724. this._interp.reset();
  1725. };
  1726. // Return a token from this source; i.e., match a token on the char stream.
  1727. Lexer.prototype.nextToken = function() {
  1728. if (this._input === null) {
  1729. throw "nextToken requires a non-null input stream.";
  1730. }
  1731. // Mark start location in char stream so unbuffered streams are
  1732. // guaranteed at least have text of current token
  1733. var tokenStartMarker = this._input.mark();
  1734. try {
  1735. while (true) {
  1736. if (this._hitEOF) {
  1737. this.emitEOF();
  1738. return this._token;
  1739. }
  1740. this._token = null;
  1741. this._channel = Token.DEFAULT_CHANNEL;
  1742. this._tokenStartCharIndex = this._input.index;
  1743. this._tokenStartColumn = this._interp.column;
  1744. this._tokenStartLine = this._interp.line;
  1745. this._text = null;
  1746. var continueOuter = false;
  1747. while (true) {
  1748. this._type = Token.INVALID_TYPE;
  1749. var ttype = Lexer.SKIP;
  1750. try {
  1751. ttype = this._interp.match(this._input, this._mode);
  1752. } catch (e) {
  1753. if(e instanceof RecognitionException) {
  1754. this.notifyListeners(e); // report error
  1755. this.recover(e);
  1756. } else {
  1757. console.log(e.stack);
  1758. throw e;
  1759. }
  1760. }
  1761. if (this._input.LA(1) === Token.EOF) {
  1762. this._hitEOF = true;
  1763. }
  1764. if (this._type === Token.INVALID_TYPE) {
  1765. this._type = ttype;
  1766. }
  1767. if (this._type === Lexer.SKIP) {
  1768. continueOuter = true;
  1769. break;
  1770. }
  1771. if (this._type !== Lexer.MORE) {
  1772. break;
  1773. }
  1774. }
  1775. if (continueOuter) {
  1776. continue;
  1777. }
  1778. if (this._token === null) {
  1779. this.emit();
  1780. }
  1781. return this._token;
  1782. }
  1783. } finally {
  1784. // make sure we release marker after match or
  1785. // unbuffered char stream will keep buffering
  1786. this._input.release(tokenStartMarker);
  1787. }
  1788. };
  1789. // Instruct the lexer to skip creating a token for current lexer rule
  1790. // and look for another token. nextToken() knows to keep looking when
  1791. // a lexer rule finishes with token set to SKIP_TOKEN. Recall that
  1792. // if token==null at end of any token rule, it creates one for you
  1793. // and emits it.
  1794. // /
  1795. Lexer.prototype.skip = function() {
  1796. this._type = Lexer.SKIP;
  1797. };
  1798. Lexer.prototype.more = function() {
  1799. this._type = Lexer.MORE;
  1800. };
  1801. Lexer.prototype.mode = function(m) {
  1802. this._mode = m;
  1803. };
  1804. Lexer.prototype.pushMode = function(m) {
  1805. if (this._interp.debug) {
  1806. console.log("pushMode " + m);
  1807. }
  1808. this._modeStack.push(this._mode);
  1809. this.mode(m);
  1810. };
  1811. Lexer.prototype.popMode = function() {
  1812. if (this._modeStack.length === 0) {
  1813. throw "Empty Stack";
  1814. }
  1815. if (this._interp.debug) {
  1816. console.log("popMode back to " + this._modeStack.slice(0, -1));
  1817. }
  1818. this.mode(this._modeStack.pop());
  1819. return this._mode;
  1820. };
  1821. // Set the char stream and reset the lexer
  1822. Object.defineProperty(Lexer.prototype, "inputStream", {
  1823. get : function() {
  1824. return this._input;
  1825. },
  1826. set : function(input) {
  1827. this._input = null;
  1828. this._tokenFactorySourcePair = [ this, this._input ];
  1829. this.reset();
  1830. this._input = input;
  1831. this._tokenFactorySourcePair = [ this, this._input ];
  1832. }
  1833. });
  1834. Object.defineProperty(Lexer.prototype, "sourceName", {
  1835. get : function sourceName() {
  1836. return this._input.sourceName;
  1837. }
  1838. });
  1839. // By default does not support multiple emits per nextToken invocation
  1840. // for efficiency reasons. Subclass and override this method, nextToken,
  1841. // and getToken (to push tokens into a list and pull from that list
  1842. // rather than a single variable as this implementation does).
  1843. // /
  1844. Lexer.prototype.emitToken = function(token) {
  1845. this._token = token;
  1846. };
  1847. // The standard method called to automatically emit a token at the
  1848. // outermost lexical rule. The token object should point into the
  1849. // char buffer start..stop. If there is a text override in 'text',
  1850. // use that to set the token's text. Override this method to emit
  1851. // custom Token objects or provide a new factory.
  1852. // /
  1853. Lexer.prototype.emit = function() {
  1854. var t = this._factory.create(this._tokenFactorySourcePair, this._type,
  1855. this._text, this._channel, this._tokenStartCharIndex, this
  1856. .getCharIndex() - 1, this._tokenStartLine,
  1857. this._tokenStartColumn);
  1858. this.emitToken(t);
  1859. return t;
  1860. };
  1861. Lexer.prototype.emitEOF = function() {
  1862. var cpos = this.column;
  1863. var lpos = this.line;
  1864. var eof = this._factory.create(this._tokenFactorySourcePair, Token.EOF,
  1865. null, Token.DEFAULT_CHANNEL, this._input.index,
  1866. this._input.index - 1, lpos, cpos);
  1867. this.emitToken(eof);
  1868. return eof;
  1869. };
  1870. Object.defineProperty(Lexer.prototype, "type", {
  1871. get : function() {
  1872. return this.type;
  1873. },
  1874. set : function(type) {
  1875. this._type = type;
  1876. }
  1877. });
  1878. Object.defineProperty(Lexer.prototype, "line", {
  1879. get : function() {
  1880. return this._interp.line;
  1881. },
  1882. set : function(line) {
  1883. this._interp.line = line;
  1884. }
  1885. });
  1886. Object.defineProperty(Lexer.prototype, "column", {
  1887. get : function() {
  1888. return this._interp.column;
  1889. },
  1890. set : function(column) {
  1891. this._interp.column = column;
  1892. }
  1893. });
  1894. // What is the index of the current character of lookahead?///
  1895. Lexer.prototype.getCharIndex = function() {
  1896. return this._input.index;
  1897. };
  1898. // Return the text matched so far for the current token or any text override.
  1899. //Set the complete text of this token; it wipes any previous changes to the text.
  1900. Object.defineProperty(Lexer.prototype, "text", {
  1901. get : function() {
  1902. if (this._text !== null) {
  1903. return this._text;
  1904. } else {
  1905. return this._interp.getText(this._input);
  1906. }
  1907. },
  1908. set : function(text) {
  1909. this._text = text;
  1910. }
  1911. });
  1912. // Return a list of all Token objects in input char stream.
  1913. // Forces load of all tokens. Does not include EOF token.
  1914. // /
  1915. Lexer.prototype.getAllTokens = function() {
  1916. var tokens = [];
  1917. var t = this.nextToken();
  1918. while (t.type !== Token.EOF) {
  1919. tokens.push(t);
  1920. t = this.nextToken();
  1921. }
  1922. return tokens;
  1923. };
  1924. Lexer.prototype.notifyListeners = function(e) {
  1925. var start = this._tokenStartCharIndex;
  1926. var stop = this._input.index;
  1927. var text = this._input.getText(start, stop);
  1928. var msg = "token recognition error at: '" + this.getErrorDisplay(text) + "'";
  1929. var listener = this.getErrorListenerDispatch();
  1930. listener.syntaxError(this, null, this._tokenStartLine,
  1931. this._tokenStartColumn, msg, e);
  1932. };
  1933. Lexer.prototype.getErrorDisplay = function(s) {
  1934. var d = [];
  1935. for (var i = 0; i < s.length; i++) {
  1936. d.push(s[i]);
  1937. }
  1938. return d.join('');
  1939. };
  1940. Lexer.prototype.getErrorDisplayForChar = function(c) {
  1941. if (c.charCodeAt(0) === Token.EOF) {
  1942. return "<EOF>";
  1943. } else if (c === '\n') {
  1944. return "\\n";
  1945. } else if (c === '\t') {
  1946. return "\\t";
  1947. } else if (c === '\r') {
  1948. return "\\r";
  1949. } else {
  1950. return c;
  1951. }
  1952. };
  1953. Lexer.prototype.getCharErrorDisplay = function(c) {
  1954. return "'" + this.getErrorDisplayForChar(c) + "'";
  1955. };
  1956. // Lexers can normally match any char in it's vocabulary after matching
  1957. // a token, so do the easy thing and just kill a character and hope
  1958. // it all works out. You can instead use the rule invocation stack
  1959. // to do sophisticated error recovery if you are in a fragment rule.
  1960. // /
  1961. Lexer.prototype.recover = function(re) {
  1962. if (this._input.LA(1) !== Token.EOF) {
  1963. if (re instanceof LexerNoViableAltException) {
  1964. // skip a char and try again
  1965. this._interp.consume(this._input);
  1966. } else {
  1967. // TODO: Do we lose character or line position information?
  1968. this._input.consume();
  1969. }
  1970. }
  1971. };
  1972. exports.Lexer = Lexer;
  1973. /***/ }),
  1974. /***/ "./node_modules/antlr4/Parser.js":
  1975. /*!***************************************!*\
  1976. !*** ./node_modules/antlr4/Parser.js ***!
  1977. \***************************************/
  1978. /*! no static exports found */
  1979. /***/ (function(module, exports, __webpack_require__) {
  1980. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  1981. * Use of this file is governed by the BSD 3-clause license that
  1982. * can be found in the LICENSE.txt file in the project root.
  1983. */
  1984. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  1985. var ParseTreeListener = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").ParseTreeListener;
  1986. var Recognizer = __webpack_require__(/*! ./Recognizer */ "./node_modules/antlr4/Recognizer.js").Recognizer;
  1987. var DefaultErrorStrategy = __webpack_require__(/*! ./error/ErrorStrategy */ "./node_modules/antlr4/error/ErrorStrategy.js").DefaultErrorStrategy;
  1988. var ATNDeserializer = __webpack_require__(/*! ./atn/ATNDeserializer */ "./node_modules/antlr4/atn/ATNDeserializer.js").ATNDeserializer;
  1989. var ATNDeserializationOptions = __webpack_require__(/*! ./atn/ATNDeserializationOptions */ "./node_modules/antlr4/atn/ATNDeserializationOptions.js").ATNDeserializationOptions;
  1990. var TerminalNode = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").TerminalNode;
  1991. var ErrorNode = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").ErrorNode;
  1992. function TraceListener(parser) {
  1993. ParseTreeListener.call(this);
  1994. this.parser = parser;
  1995. return this;
  1996. }
  1997. TraceListener.prototype = Object.create(ParseTreeListener.prototype);
  1998. TraceListener.prototype.constructor = TraceListener;
  1999. TraceListener.prototype.enterEveryRule = function(ctx) {
  2000. console.log("enter " + this.parser.ruleNames[ctx.ruleIndex] + ", LT(1)=" + this.parser._input.LT(1).text);
  2001. };
  2002. TraceListener.prototype.visitTerminal = function( node) {
  2003. console.log("consume " + node.symbol + " rule " + this.parser.ruleNames[this.parser._ctx.ruleIndex]);
  2004. };
  2005. TraceListener.prototype.exitEveryRule = function(ctx) {
  2006. console.log("exit " + this.parser.ruleNames[ctx.ruleIndex] + ", LT(1)=" + this.parser._input.LT(1).text);
  2007. };
  2008. // this is all the parsing support code essentially; most of it is error
  2009. // recovery stuff.//
  2010. function Parser(input) {
  2011. Recognizer.call(this);
  2012. // The input stream.
  2013. this._input = null;
  2014. // The error handling strategy for the parser. The default value is a new
  2015. // instance of {@link DefaultErrorStrategy}.
  2016. this._errHandler = new DefaultErrorStrategy();
  2017. this._precedenceStack = [];
  2018. this._precedenceStack.push(0);
  2019. // The {@link ParserRuleContext} object for the currently executing rule.
  2020. // this is always non-null during the parsing process.
  2021. this._ctx = null;
  2022. // Specifies whether or not the parser should construct a parse tree during
  2023. // the parsing process. The default value is {@code true}.
  2024. this.buildParseTrees = true;
  2025. // When {@link //setTrace}{@code (true)} is called, a reference to the
  2026. // {@link TraceListener} is stored here so it can be easily removed in a
  2027. // later call to {@link //setTrace}{@code (false)}. The listener itself is
  2028. // implemented as a parser listener so this field is not directly used by
  2029. // other parser methods.
  2030. this._tracer = null;
  2031. // The list of {@link ParseTreeListener} listeners registered to receive
  2032. // events during the parse.
  2033. this._parseListeners = null;
  2034. // The number of syntax errors reported during parsing. this value is
  2035. // incremented each time {@link //notifyErrorListeners} is called.
  2036. this._syntaxErrors = 0;
  2037. this.setInputStream(input);
  2038. return this;
  2039. }
  2040. Parser.prototype = Object.create(Recognizer.prototype);
  2041. Parser.prototype.contructor = Parser;
  2042. // this field maps from the serialized ATN string to the deserialized {@link
  2043. // ATN} with
  2044. // bypass alternatives.
  2045. //
  2046. // @see ATNDeserializationOptions//isGenerateRuleBypassTransitions()
  2047. //
  2048. Parser.bypassAltsAtnCache = {};
  2049. // reset the parser's state//
  2050. Parser.prototype.reset = function() {
  2051. if (this._input !== null) {
  2052. this._input.seek(0);
  2053. }
  2054. this._errHandler.reset(this);
  2055. this._ctx = null;
  2056. this._syntaxErrors = 0;
  2057. this.setTrace(false);
  2058. this._precedenceStack = [];
  2059. this._precedenceStack.push(0);
  2060. if (this._interp !== null) {
  2061. this._interp.reset();
  2062. }
  2063. };
  2064. // Match current input symbol against {@code ttype}. If the symbol type
  2065. // matches, {@link ANTLRErrorStrategy//reportMatch} and {@link //consume} are
  2066. // called to complete the match process.
  2067. //
  2068. // <p>If the symbol type does not match,
  2069. // {@link ANTLRErrorStrategy//recoverInline} is called on the current error
  2070. // strategy to attempt recovery. If {@link //getBuildParseTree} is
  2071. // {@code true} and the token index of the symbol returned by
  2072. // {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to
  2073. // the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>
  2074. //
  2075. // @param ttype the token type to match
  2076. // @return the matched symbol
  2077. // @throws RecognitionException if the current input symbol did not match
  2078. // {@code ttype} and the error strategy could not recover from the
  2079. // mismatched symbol
  2080. Parser.prototype.match = function(ttype) {
  2081. var t = this.getCurrentToken();
  2082. if (t.type === ttype) {
  2083. this._errHandler.reportMatch(this);
  2084. this.consume();
  2085. } else {
  2086. t = this._errHandler.recoverInline(this);
  2087. if (this.buildParseTrees && t.tokenIndex === -1) {
  2088. // we must have conjured up a new token during single token
  2089. // insertion
  2090. // if it's not the current symbol
  2091. this._ctx.addErrorNode(t);
  2092. }
  2093. }
  2094. return t;
  2095. };
  2096. // Match current input symbol as a wildcard. If the symbol type matches
  2097. // (i.e. has a value greater than 0), {@link ANTLRErrorStrategy//reportMatch}
  2098. // and {@link //consume} are called to complete the match process.
  2099. //
  2100. // <p>If the symbol type does not match,
  2101. // {@link ANTLRErrorStrategy//recoverInline} is called on the current error
  2102. // strategy to attempt recovery. If {@link //getBuildParseTree} is
  2103. // {@code true} and the token index of the symbol returned by
  2104. // {@link ANTLRErrorStrategy//recoverInline} is -1, the symbol is added to
  2105. // the parse tree by calling {@link ParserRuleContext//addErrorNode}.</p>
  2106. //
  2107. // @return the matched symbol
  2108. // @throws RecognitionException if the current input symbol did not match
  2109. // a wildcard and the error strategy could not recover from the mismatched
  2110. // symbol
  2111. Parser.prototype.matchWildcard = function() {
  2112. var t = this.getCurrentToken();
  2113. if (t.type > 0) {
  2114. this._errHandler.reportMatch(this);
  2115. this.consume();
  2116. } else {
  2117. t = this._errHandler.recoverInline(this);
  2118. if (this._buildParseTrees && t.tokenIndex === -1) {
  2119. // we must have conjured up a new token during single token
  2120. // insertion
  2121. // if it's not the current symbol
  2122. this._ctx.addErrorNode(t);
  2123. }
  2124. }
  2125. return t;
  2126. };
  2127. Parser.prototype.getParseListeners = function() {
  2128. return this._parseListeners || [];
  2129. };
  2130. // Registers {@code listener} to receive events during the parsing process.
  2131. //
  2132. // <p>To support output-preserving grammar transformations (including but not
  2133. // limited to left-recursion removal, automated left-factoring, and
  2134. // optimized code generation), calls to listener methods during the parse
  2135. // may differ substantially from calls made by
  2136. // {@link ParseTreeWalker//DEFAULT} used after the parse is complete. In
  2137. // particular, rule entry and exit events may occur in a different order
  2138. // during the parse than after the parser. In addition, calls to certain
  2139. // rule entry methods may be omitted.</p>
  2140. //
  2141. // <p>With the following specific exceptions, calls to listener events are
  2142. // <em>deterministic</em>, i.e. for identical input the calls to listener
  2143. // methods will be the same.</p>
  2144. //
  2145. // <ul>
  2146. // <li>Alterations to the grammar used to generate code may change the
  2147. // behavior of the listener calls.</li>
  2148. // <li>Alterations to the command line options passed to ANTLR 4 when
  2149. // generating the parser may change the behavior of the listener calls.</li>
  2150. // <li>Changing the version of the ANTLR Tool used to generate the parser
  2151. // may change the behavior of the listener calls.</li>
  2152. // </ul>
  2153. //
  2154. // @param listener the listener to add
  2155. //
  2156. // @throws NullPointerException if {@code} listener is {@code null}
  2157. //
  2158. Parser.prototype.addParseListener = function(listener) {
  2159. if (listener === null) {
  2160. throw "listener";
  2161. }
  2162. if (this._parseListeners === null) {
  2163. this._parseListeners = [];
  2164. }
  2165. this._parseListeners.push(listener);
  2166. };
  2167. //
  2168. // Remove {@code listener} from the list of parse listeners.
  2169. //
  2170. // <p>If {@code listener} is {@code null} or has not been added as a parse
  2171. // listener, this method does nothing.</p>
  2172. // @param listener the listener to remove
  2173. //
  2174. Parser.prototype.removeParseListener = function(listener) {
  2175. if (this._parseListeners !== null) {
  2176. var idx = this._parseListeners.indexOf(listener);
  2177. if (idx >= 0) {
  2178. this._parseListeners.splice(idx, 1);
  2179. }
  2180. if (this._parseListeners.length === 0) {
  2181. this._parseListeners = null;
  2182. }
  2183. }
  2184. };
  2185. // Remove all parse listeners.
  2186. Parser.prototype.removeParseListeners = function() {
  2187. this._parseListeners = null;
  2188. };
  2189. // Notify any parse listeners of an enter rule event.
  2190. Parser.prototype.triggerEnterRuleEvent = function() {
  2191. if (this._parseListeners !== null) {
  2192. var ctx = this._ctx;
  2193. this._parseListeners.map(function(listener) {
  2194. listener.enterEveryRule(ctx);
  2195. ctx.enterRule(listener);
  2196. });
  2197. }
  2198. };
  2199. //
  2200. // Notify any parse listeners of an exit rule event.
  2201. //
  2202. // @see //addParseListener
  2203. //
  2204. Parser.prototype.triggerExitRuleEvent = function() {
  2205. if (this._parseListeners !== null) {
  2206. // reverse order walk of listeners
  2207. var ctx = this._ctx;
  2208. this._parseListeners.slice(0).reverse().map(function(listener) {
  2209. ctx.exitRule(listener);
  2210. listener.exitEveryRule(ctx);
  2211. });
  2212. }
  2213. };
  2214. Parser.prototype.getTokenFactory = function() {
  2215. return this._input.tokenSource._factory;
  2216. };
  2217. // Tell our token source and error strategy about a new way to create tokens.//
  2218. Parser.prototype.setTokenFactory = function(factory) {
  2219. this._input.tokenSource._factory = factory;
  2220. };
  2221. // The ATN with bypass alternatives is expensive to create so we create it
  2222. // lazily.
  2223. //
  2224. // @throws UnsupportedOperationException if the current parser does not
  2225. // implement the {@link //getSerializedATN()} method.
  2226. //
  2227. Parser.prototype.getATNWithBypassAlts = function() {
  2228. var serializedAtn = this.getSerializedATN();
  2229. if (serializedAtn === null) {
  2230. throw "The current parser does not support an ATN with bypass alternatives.";
  2231. }
  2232. var result = this.bypassAltsAtnCache[serializedAtn];
  2233. if (result === null) {
  2234. var deserializationOptions = new ATNDeserializationOptions();
  2235. deserializationOptions.generateRuleBypassTransitions = true;
  2236. result = new ATNDeserializer(deserializationOptions)
  2237. .deserialize(serializedAtn);
  2238. this.bypassAltsAtnCache[serializedAtn] = result;
  2239. }
  2240. return result;
  2241. };
  2242. // The preferred method of getting a tree pattern. For example, here's a
  2243. // sample use:
  2244. //
  2245. // <pre>
  2246. // ParseTree t = parser.expr();
  2247. // ParseTreePattern p = parser.compileParseTreePattern("&lt;ID&gt;+0",
  2248. // MyParser.RULE_expr);
  2249. // ParseTreeMatch m = p.match(t);
  2250. // String id = m.get("ID");
  2251. // </pre>
  2252. var Lexer = __webpack_require__(/*! ./Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
  2253. Parser.prototype.compileParseTreePattern = function(pattern, patternRuleIndex, lexer) {
  2254. lexer = lexer || null;
  2255. if (lexer === null) {
  2256. if (this.getTokenStream() !== null) {
  2257. var tokenSource = this.getTokenStream().tokenSource;
  2258. if (tokenSource instanceof Lexer) {
  2259. lexer = tokenSource;
  2260. }
  2261. }
  2262. }
  2263. if (lexer === null) {
  2264. throw "Parser can't discover a lexer to use";
  2265. }
  2266. var m = new ParseTreePatternMatcher(lexer, this);
  2267. return m.compile(pattern, patternRuleIndex);
  2268. };
  2269. Parser.prototype.getInputStream = function() {
  2270. return this.getTokenStream();
  2271. };
  2272. Parser.prototype.setInputStream = function(input) {
  2273. this.setTokenStream(input);
  2274. };
  2275. Parser.prototype.getTokenStream = function() {
  2276. return this._input;
  2277. };
  2278. // Set the token stream and reset the parser.//
  2279. Parser.prototype.setTokenStream = function(input) {
  2280. this._input = null;
  2281. this.reset();
  2282. this._input = input;
  2283. };
  2284. // Match needs to return the current input symbol, which gets put
  2285. // into the label for the associated token ref; e.g., x=ID.
  2286. //
  2287. Parser.prototype.getCurrentToken = function() {
  2288. return this._input.LT(1);
  2289. };
  2290. Parser.prototype.notifyErrorListeners = function(msg, offendingToken, err) {
  2291. offendingToken = offendingToken || null;
  2292. err = err || null;
  2293. if (offendingToken === null) {
  2294. offendingToken = this.getCurrentToken();
  2295. }
  2296. this._syntaxErrors += 1;
  2297. var line = offendingToken.line;
  2298. var column = offendingToken.column;
  2299. var listener = this.getErrorListenerDispatch();
  2300. listener.syntaxError(this, offendingToken, line, column, msg, err);
  2301. };
  2302. //
  2303. // Consume and return the {@linkplain //getCurrentToken current symbol}.
  2304. //
  2305. // <p>E.g., given the following input with {@code A} being the current
  2306. // lookahead symbol, this function moves the cursor to {@code B} and returns
  2307. // {@code A}.</p>
  2308. //
  2309. // <pre>
  2310. // A B
  2311. // ^
  2312. // </pre>
  2313. //
  2314. // If the parser is not in error recovery mode, the consumed symbol is added
  2315. // to the parse tree using {@link ParserRuleContext//addChild(Token)}, and
  2316. // {@link ParseTreeListener//visitTerminal} is called on any parse listeners.
  2317. // If the parser <em>is</em> in error recovery mode, the consumed symbol is
  2318. // added to the parse tree using
  2319. // {@link ParserRuleContext//addErrorNode(Token)}, and
  2320. // {@link ParseTreeListener//visitErrorNode} is called on any parse
  2321. // listeners.
  2322. //
  2323. Parser.prototype.consume = function() {
  2324. var o = this.getCurrentToken();
  2325. if (o.type !== Token.EOF) {
  2326. this.getInputStream().consume();
  2327. }
  2328. var hasListener = this._parseListeners !== null && this._parseListeners.length > 0;
  2329. if (this.buildParseTrees || hasListener) {
  2330. var node;
  2331. if (this._errHandler.inErrorRecoveryMode(this)) {
  2332. node = this._ctx.addErrorNode(o);
  2333. } else {
  2334. node = this._ctx.addTokenNode(o);
  2335. }
  2336. node.invokingState = this.state;
  2337. if (hasListener) {
  2338. this._parseListeners.map(function(listener) {
  2339. if (node instanceof ErrorNode || (node.isErrorNode !== undefined && node.isErrorNode())) {
  2340. listener.visitErrorNode(node);
  2341. } else if (node instanceof TerminalNode) {
  2342. listener.visitTerminal(node);
  2343. }
  2344. });
  2345. }
  2346. }
  2347. return o;
  2348. };
  2349. Parser.prototype.addContextToParseTree = function() {
  2350. // add current context to parent if we have a parent
  2351. if (this._ctx.parentCtx !== null) {
  2352. this._ctx.parentCtx.addChild(this._ctx);
  2353. }
  2354. };
  2355. // Always called by generated parsers upon entry to a rule. Access field
  2356. // {@link //_ctx} get the current context.
  2357. Parser.prototype.enterRule = function(localctx, state, ruleIndex) {
  2358. this.state = state;
  2359. this._ctx = localctx;
  2360. this._ctx.start = this._input.LT(1);
  2361. if (this.buildParseTrees) {
  2362. this.addContextToParseTree();
  2363. }
  2364. if (this._parseListeners !== null) {
  2365. this.triggerEnterRuleEvent();
  2366. }
  2367. };
  2368. Parser.prototype.exitRule = function() {
  2369. this._ctx.stop = this._input.LT(-1);
  2370. // trigger event on _ctx, before it reverts to parent
  2371. if (this._parseListeners !== null) {
  2372. this.triggerExitRuleEvent();
  2373. }
  2374. this.state = this._ctx.invokingState;
  2375. this._ctx = this._ctx.parentCtx;
  2376. };
  2377. Parser.prototype.enterOuterAlt = function(localctx, altNum) {
  2378. localctx.setAltNumber(altNum);
  2379. // if we have new localctx, make sure we replace existing ctx
  2380. // that is previous child of parse tree
  2381. if (this.buildParseTrees && this._ctx !== localctx) {
  2382. if (this._ctx.parentCtx !== null) {
  2383. this._ctx.parentCtx.removeLastChild();
  2384. this._ctx.parentCtx.addChild(localctx);
  2385. }
  2386. }
  2387. this._ctx = localctx;
  2388. };
  2389. // Get the precedence level for the top-most precedence rule.
  2390. //
  2391. // @return The precedence level for the top-most precedence rule, or -1 if
  2392. // the parser context is not nested within a precedence rule.
  2393. Parser.prototype.getPrecedence = function() {
  2394. if (this._precedenceStack.length === 0) {
  2395. return -1;
  2396. } else {
  2397. return this._precedenceStack[this._precedenceStack.length-1];
  2398. }
  2399. };
  2400. Parser.prototype.enterRecursionRule = function(localctx, state, ruleIndex,
  2401. precedence) {
  2402. this.state = state;
  2403. this._precedenceStack.push(precedence);
  2404. this._ctx = localctx;
  2405. this._ctx.start = this._input.LT(1);
  2406. if (this._parseListeners !== null) {
  2407. this.triggerEnterRuleEvent(); // simulates rule entry for
  2408. // left-recursive rules
  2409. }
  2410. };
  2411. //
  2412. // Like {@link //enterRule} but for recursive rules.
  2413. Parser.prototype.pushNewRecursionContext = function(localctx, state, ruleIndex) {
  2414. var previous = this._ctx;
  2415. previous.parentCtx = localctx;
  2416. previous.invokingState = state;
  2417. previous.stop = this._input.LT(-1);
  2418. this._ctx = localctx;
  2419. this._ctx.start = previous.start;
  2420. if (this.buildParseTrees) {
  2421. this._ctx.addChild(previous);
  2422. }
  2423. if (this._parseListeners !== null) {
  2424. this.triggerEnterRuleEvent(); // simulates rule entry for
  2425. // left-recursive rules
  2426. }
  2427. };
  2428. Parser.prototype.unrollRecursionContexts = function(parentCtx) {
  2429. this._precedenceStack.pop();
  2430. this._ctx.stop = this._input.LT(-1);
  2431. var retCtx = this._ctx; // save current ctx (return value)
  2432. // unroll so _ctx is as it was before call to recursive method
  2433. if (this._parseListeners !== null) {
  2434. while (this._ctx !== parentCtx) {
  2435. this.triggerExitRuleEvent();
  2436. this._ctx = this._ctx.parentCtx;
  2437. }
  2438. } else {
  2439. this._ctx = parentCtx;
  2440. }
  2441. // hook into tree
  2442. retCtx.parentCtx = parentCtx;
  2443. if (this.buildParseTrees && parentCtx !== null) {
  2444. // add return ctx into invoking rule's tree
  2445. parentCtx.addChild(retCtx);
  2446. }
  2447. };
  2448. Parser.prototype.getInvokingContext = function(ruleIndex) {
  2449. var ctx = this._ctx;
  2450. while (ctx !== null) {
  2451. if (ctx.ruleIndex === ruleIndex) {
  2452. return ctx;
  2453. }
  2454. ctx = ctx.parentCtx;
  2455. }
  2456. return null;
  2457. };
  2458. Parser.prototype.precpred = function(localctx, precedence) {
  2459. return precedence >= this._precedenceStack[this._precedenceStack.length-1];
  2460. };
  2461. Parser.prototype.inContext = function(context) {
  2462. // TODO: useful in parser?
  2463. return false;
  2464. };
  2465. //
  2466. // Checks whether or not {@code symbol} can follow the current state in the
  2467. // ATN. The behavior of this method is equivalent to the following, but is
  2468. // implemented such that the complete context-sensitive follow set does not
  2469. // need to be explicitly constructed.
  2470. //
  2471. // <pre>
  2472. // return getExpectedTokens().contains(symbol);
  2473. // </pre>
  2474. //
  2475. // @param symbol the symbol type to check
  2476. // @return {@code true} if {@code symbol} can follow the current state in
  2477. // the ATN, otherwise {@code false}.
  2478. Parser.prototype.isExpectedToken = function(symbol) {
  2479. var atn = this._interp.atn;
  2480. var ctx = this._ctx;
  2481. var s = atn.states[this.state];
  2482. var following = atn.nextTokens(s);
  2483. if (following.contains(symbol)) {
  2484. return true;
  2485. }
  2486. if (!following.contains(Token.EPSILON)) {
  2487. return false;
  2488. }
  2489. while (ctx !== null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) {
  2490. var invokingState = atn.states[ctx.invokingState];
  2491. var rt = invokingState.transitions[0];
  2492. following = atn.nextTokens(rt.followState);
  2493. if (following.contains(symbol)) {
  2494. return true;
  2495. }
  2496. ctx = ctx.parentCtx;
  2497. }
  2498. if (following.contains(Token.EPSILON) && symbol === Token.EOF) {
  2499. return true;
  2500. } else {
  2501. return false;
  2502. }
  2503. };
  2504. // Computes the set of input symbols which could follow the current parser
  2505. // state and context, as given by {@link //getState} and {@link //getContext},
  2506. // respectively.
  2507. //
  2508. // @see ATN//getExpectedTokens(int, RuleContext)
  2509. //
  2510. Parser.prototype.getExpectedTokens = function() {
  2511. return this._interp.atn.getExpectedTokens(this.state, this._ctx);
  2512. };
  2513. Parser.prototype.getExpectedTokensWithinCurrentRule = function() {
  2514. var atn = this._interp.atn;
  2515. var s = atn.states[this.state];
  2516. return atn.nextTokens(s);
  2517. };
  2518. // Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found.//
  2519. Parser.prototype.getRuleIndex = function(ruleName) {
  2520. var ruleIndex = this.getRuleIndexMap()[ruleName];
  2521. if (ruleIndex !== null) {
  2522. return ruleIndex;
  2523. } else {
  2524. return -1;
  2525. }
  2526. };
  2527. // Return List&lt;String&gt; of the rule names in your parser instance
  2528. // leading up to a call to the current rule. You could override if
  2529. // you want more details such as the file/line info of where
  2530. // in the ATN a rule is invoked.
  2531. //
  2532. // this is very useful for error messages.
  2533. //
  2534. Parser.prototype.getRuleInvocationStack = function(p) {
  2535. p = p || null;
  2536. if (p === null) {
  2537. p = this._ctx;
  2538. }
  2539. var stack = [];
  2540. while (p !== null) {
  2541. // compute what follows who invoked us
  2542. var ruleIndex = p.ruleIndex;
  2543. if (ruleIndex < 0) {
  2544. stack.push("n/a");
  2545. } else {
  2546. stack.push(this.ruleNames[ruleIndex]);
  2547. }
  2548. p = p.parentCtx;
  2549. }
  2550. return stack;
  2551. };
  2552. // For debugging and other purposes.//
  2553. Parser.prototype.getDFAStrings = function() {
  2554. return this._interp.decisionToDFA.toString();
  2555. };
  2556. // For debugging and other purposes.//
  2557. Parser.prototype.dumpDFA = function() {
  2558. var seenOne = false;
  2559. for (var i = 0; i < this._interp.decisionToDFA.length; i++) {
  2560. var dfa = this._interp.decisionToDFA[i];
  2561. if (dfa.states.length > 0) {
  2562. if (seenOne) {
  2563. console.log();
  2564. }
  2565. this.printer.println("Decision " + dfa.decision + ":");
  2566. this.printer.print(dfa.toString(this.literalNames, this.symbolicNames));
  2567. seenOne = true;
  2568. }
  2569. }
  2570. };
  2571. /*
  2572. " printer = function() {\r\n" +
  2573. " this.println = function(s) { document.getElementById('output') += s + '\\n'; }\r\n" +
  2574. " this.print = function(s) { document.getElementById('output') += s; }\r\n" +
  2575. " };\r\n" +
  2576. */
  2577. Parser.prototype.getSourceName = function() {
  2578. return this._input.sourceName;
  2579. };
  2580. // During a parse is sometimes useful to listen in on the rule entry and exit
  2581. // events as well as token matches. this is for quick and dirty debugging.
  2582. //
  2583. Parser.prototype.setTrace = function(trace) {
  2584. if (!trace) {
  2585. this.removeParseListener(this._tracer);
  2586. this._tracer = null;
  2587. } else {
  2588. if (this._tracer !== null) {
  2589. this.removeParseListener(this._tracer);
  2590. }
  2591. this._tracer = new TraceListener(this);
  2592. this.addParseListener(this._tracer);
  2593. }
  2594. };
  2595. exports.Parser = Parser;
  2596. /***/ }),
  2597. /***/ "./node_modules/antlr4/ParserRuleContext.js":
  2598. /*!**************************************************!*\
  2599. !*** ./node_modules/antlr4/ParserRuleContext.js ***!
  2600. \**************************************************/
  2601. /*! no static exports found */
  2602. /***/ (function(module, exports, __webpack_require__) {
  2603. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  2604. * Use of this file is governed by the BSD 3-clause license that
  2605. * can be found in the LICENSE.txt file in the project root.
  2606. */
  2607. //* A rule invocation record for parsing.
  2608. //
  2609. // Contains all of the information about the current rule not stored in the
  2610. // RuleContext. It handles parse tree children list, Any ATN state
  2611. // tracing, and the default values available for rule indications:
  2612. // start, stop, rule index, current alt number, current
  2613. // ATN state.
  2614. //
  2615. // Subclasses made for each rule and grammar track the parameters,
  2616. // return values, locals, and labels specific to that rule. These
  2617. // are the objects that are returned from rules.
  2618. //
  2619. // Note text is not an actual field of a rule return value; it is computed
  2620. // from start and stop using the input stream's toString() method. I
  2621. // could add a ctor to this so that we can pass in and store the input
  2622. // stream, but I'm not sure we want to do that. It would seem to be undefined
  2623. // to get the .text property anyway if the rule matches tokens from multiple
  2624. // input streams.
  2625. //
  2626. // I do not use getters for fields of objects that are used simply to
  2627. // group values such as this aggregate. The getters/setters are there to
  2628. // satisfy the superclass interface.
  2629. var RuleContext = __webpack_require__(/*! ./RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
  2630. var Tree = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js");
  2631. var INVALID_INTERVAL = Tree.INVALID_INTERVAL;
  2632. var TerminalNode = Tree.TerminalNode;
  2633. var TerminalNodeImpl = Tree.TerminalNodeImpl;
  2634. var ErrorNodeImpl = Tree.ErrorNodeImpl;
  2635. var Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  2636. function ParserRuleContext(parent, invokingStateNumber) {
  2637. parent = parent || null;
  2638. invokingStateNumber = invokingStateNumber || null;
  2639. RuleContext.call(this, parent, invokingStateNumber);
  2640. this.ruleIndex = -1;
  2641. // * If we are debugging or building a parse tree for a visitor,
  2642. // we need to track all of the tokens and rule invocations associated
  2643. // with this rule's context. This is empty for parsing w/o tree constr.
  2644. // operation because we don't the need to track the details about
  2645. // how we parse this rule.
  2646. // /
  2647. this.children = null;
  2648. this.start = null;
  2649. this.stop = null;
  2650. // The exception that forced this rule to return. If the rule successfully
  2651. // completed, this is {@code null}.
  2652. this.exception = null;
  2653. }
  2654. ParserRuleContext.prototype = Object.create(RuleContext.prototype);
  2655. ParserRuleContext.prototype.constructor = ParserRuleContext;
  2656. // * COPY a ctx (I'm deliberately not using copy constructor)///
  2657. ParserRuleContext.prototype.copyFrom = function(ctx) {
  2658. // from RuleContext
  2659. this.parentCtx = ctx.parentCtx;
  2660. this.invokingState = ctx.invokingState;
  2661. this.children = null;
  2662. this.start = ctx.start;
  2663. this.stop = ctx.stop;
  2664. // copy any error nodes to alt label node
  2665. if(ctx.children) {
  2666. this.children = [];
  2667. // reset parent pointer for any error nodes
  2668. ctx.children.map(function(child) {
  2669. if (child instanceof ErrorNodeImpl) {
  2670. this.children.push(child);
  2671. child.parentCtx = this;
  2672. }
  2673. }, this);
  2674. }
  2675. };
  2676. // Double dispatch methods for listeners
  2677. ParserRuleContext.prototype.enterRule = function(listener) {
  2678. };
  2679. ParserRuleContext.prototype.exitRule = function(listener) {
  2680. };
  2681. // * Does not set parent link; other add methods do that///
  2682. ParserRuleContext.prototype.addChild = function(child) {
  2683. if (this.children === null) {
  2684. this.children = [];
  2685. }
  2686. this.children.push(child);
  2687. return child;
  2688. };
  2689. // * Used by enterOuterAlt to toss out a RuleContext previously added as
  2690. // we entered a rule. If we have // label, we will need to remove
  2691. // generic ruleContext object.
  2692. // /
  2693. ParserRuleContext.prototype.removeLastChild = function() {
  2694. if (this.children !== null) {
  2695. this.children.pop();
  2696. }
  2697. };
  2698. ParserRuleContext.prototype.addTokenNode = function(token) {
  2699. var node = new TerminalNodeImpl(token);
  2700. this.addChild(node);
  2701. node.parentCtx = this;
  2702. return node;
  2703. };
  2704. ParserRuleContext.prototype.addErrorNode = function(badToken) {
  2705. var node = new ErrorNodeImpl(badToken);
  2706. this.addChild(node);
  2707. node.parentCtx = this;
  2708. return node;
  2709. };
  2710. ParserRuleContext.prototype.getChild = function(i, type) {
  2711. type = type || null;
  2712. if (this.children === null || i < 0 || i >= this.children.length) {
  2713. return null;
  2714. }
  2715. if (type === null) {
  2716. return this.children[i];
  2717. } else {
  2718. for(var j=0; j<this.children.length; j++) {
  2719. var child = this.children[j];
  2720. if(child instanceof type) {
  2721. if(i===0) {
  2722. return child;
  2723. } else {
  2724. i -= 1;
  2725. }
  2726. }
  2727. }
  2728. return null;
  2729. }
  2730. };
  2731. ParserRuleContext.prototype.getToken = function(ttype, i) {
  2732. if (this.children === null || i < 0 || i >= this.children.length) {
  2733. return null;
  2734. }
  2735. for(var j=0; j<this.children.length; j++) {
  2736. var child = this.children[j];
  2737. if (child instanceof TerminalNode) {
  2738. if (child.symbol.type === ttype) {
  2739. if(i===0) {
  2740. return child;
  2741. } else {
  2742. i -= 1;
  2743. }
  2744. }
  2745. }
  2746. }
  2747. return null;
  2748. };
  2749. ParserRuleContext.prototype.getTokens = function(ttype ) {
  2750. if (this.children=== null) {
  2751. return [];
  2752. } else {
  2753. var tokens = [];
  2754. for(var j=0; j<this.children.length; j++) {
  2755. var child = this.children[j];
  2756. if (child instanceof TerminalNode) {
  2757. if (child.symbol.type === ttype) {
  2758. tokens.push(child);
  2759. }
  2760. }
  2761. }
  2762. return tokens;
  2763. }
  2764. };
  2765. ParserRuleContext.prototype.getTypedRuleContext = function(ctxType, i) {
  2766. return this.getChild(i, ctxType);
  2767. };
  2768. ParserRuleContext.prototype.getTypedRuleContexts = function(ctxType) {
  2769. if (this.children=== null) {
  2770. return [];
  2771. } else {
  2772. var contexts = [];
  2773. for(var j=0; j<this.children.length; j++) {
  2774. var child = this.children[j];
  2775. if (child instanceof ctxType) {
  2776. contexts.push(child);
  2777. }
  2778. }
  2779. return contexts;
  2780. }
  2781. };
  2782. ParserRuleContext.prototype.getChildCount = function() {
  2783. if (this.children=== null) {
  2784. return 0;
  2785. } else {
  2786. return this.children.length;
  2787. }
  2788. };
  2789. ParserRuleContext.prototype.getSourceInterval = function() {
  2790. if( this.start === null || this.stop === null) {
  2791. return INVALID_INTERVAL;
  2792. } else {
  2793. return new Interval(this.start.tokenIndex, this.stop.tokenIndex);
  2794. }
  2795. };
  2796. RuleContext.EMPTY = new ParserRuleContext();
  2797. function InterpreterRuleContext(parent, invokingStateNumber, ruleIndex) {
  2798. ParserRuleContext.call(parent, invokingStateNumber);
  2799. this.ruleIndex = ruleIndex;
  2800. return this;
  2801. }
  2802. InterpreterRuleContext.prototype = Object.create(ParserRuleContext.prototype);
  2803. InterpreterRuleContext.prototype.constructor = InterpreterRuleContext;
  2804. exports.ParserRuleContext = ParserRuleContext;
  2805. /***/ }),
  2806. /***/ "./node_modules/antlr4/PredictionContext.js":
  2807. /*!**************************************************!*\
  2808. !*** ./node_modules/antlr4/PredictionContext.js ***!
  2809. \**************************************************/
  2810. /*! no static exports found */
  2811. /***/ (function(module, exports, __webpack_require__) {
  2812. //
  2813. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  2814. * Use of this file is governed by the BSD 3-clause license that
  2815. * can be found in the LICENSE.txt file in the project root.
  2816. */
  2817. ///
  2818. var RuleContext = __webpack_require__(/*! ./RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
  2819. var Hash = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").Hash;
  2820. var Map = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js").Map;
  2821. function PredictionContext(cachedHashCode) {
  2822. this.cachedHashCode = cachedHashCode;
  2823. }
  2824. // Represents {@code $} in local context prediction, which means wildcard.
  2825. // {@code//+x =//}.
  2826. // /
  2827. PredictionContext.EMPTY = null;
  2828. // Represents {@code $} in an array in full context mode, when {@code $}
  2829. // doesn't mean wildcard: {@code $ + x = [$,x]}. Here,
  2830. // {@code $} = {@link //EMPTY_RETURN_STATE}.
  2831. // /
  2832. PredictionContext.EMPTY_RETURN_STATE = 0x7FFFFFFF;
  2833. PredictionContext.globalNodeCount = 1;
  2834. PredictionContext.id = PredictionContext.globalNodeCount;
  2835. // Stores the computed hash code of this {@link PredictionContext}. The hash
  2836. // code is computed in parts to match the following reference algorithm.
  2837. //
  2838. // <pre>
  2839. // private int referenceHashCode() {
  2840. // int hash = {@link MurmurHash//initialize MurmurHash.initialize}({@link
  2841. // //INITIAL_HASH});
  2842. //
  2843. // for (int i = 0; i &lt; {@link //size()}; i++) {
  2844. // hash = {@link MurmurHash//update MurmurHash.update}(hash, {@link //getParent
  2845. // getParent}(i));
  2846. // }
  2847. //
  2848. // for (int i = 0; i &lt; {@link //size()}; i++) {
  2849. // hash = {@link MurmurHash//update MurmurHash.update}(hash, {@link
  2850. // //getReturnState getReturnState}(i));
  2851. // }
  2852. //
  2853. // hash = {@link MurmurHash//finish MurmurHash.finish}(hash, 2// {@link
  2854. // //size()});
  2855. // return hash;
  2856. // }
  2857. // </pre>
  2858. // /
  2859. // This means only the {@link //EMPTY} context is in set.
  2860. PredictionContext.prototype.isEmpty = function() {
  2861. return this === PredictionContext.EMPTY;
  2862. };
  2863. PredictionContext.prototype.hasEmptyPath = function() {
  2864. return this.getReturnState(this.length - 1) === PredictionContext.EMPTY_RETURN_STATE;
  2865. };
  2866. PredictionContext.prototype.hashCode = function() {
  2867. return this.cachedHashCode;
  2868. };
  2869. PredictionContext.prototype.updateHashCode = function(hash) {
  2870. hash.update(this.cachedHashCode);
  2871. };
  2872. /*
  2873. function calculateHashString(parent, returnState) {
  2874. return "" + parent + returnState;
  2875. }
  2876. */
  2877. // Used to cache {@link PredictionContext} objects. Its used for the shared
  2878. // context cash associated with contexts in DFA states. This cache
  2879. // can be used for both lexers and parsers.
  2880. function PredictionContextCache() {
  2881. this.cache = new Map();
  2882. return this;
  2883. }
  2884. // Add a context to the cache and return it. If the context already exists,
  2885. // return that one instead and do not add a new context to the cache.
  2886. // Protect shared cache from unsafe thread access.
  2887. //
  2888. PredictionContextCache.prototype.add = function(ctx) {
  2889. if (ctx === PredictionContext.EMPTY) {
  2890. return PredictionContext.EMPTY;
  2891. }
  2892. var existing = this.cache.get(ctx) || null;
  2893. if (existing !== null) {
  2894. return existing;
  2895. }
  2896. this.cache.put(ctx, ctx);
  2897. return ctx;
  2898. };
  2899. PredictionContextCache.prototype.get = function(ctx) {
  2900. return this.cache.get(ctx) || null;
  2901. };
  2902. Object.defineProperty(PredictionContextCache.prototype, "length", {
  2903. get : function() {
  2904. return this.cache.length;
  2905. }
  2906. });
  2907. function SingletonPredictionContext(parent, returnState) {
  2908. var hashCode = 0;
  2909. var hash = new Hash();
  2910. if(parent !== null) {
  2911. hash.update(parent, returnState);
  2912. } else {
  2913. hash.update(1);
  2914. }
  2915. hashCode = hash.finish();
  2916. PredictionContext.call(this, hashCode);
  2917. this.parentCtx = parent;
  2918. this.returnState = returnState;
  2919. }
  2920. SingletonPredictionContext.prototype = Object.create(PredictionContext.prototype);
  2921. SingletonPredictionContext.prototype.contructor = SingletonPredictionContext;
  2922. SingletonPredictionContext.create = function(parent, returnState) {
  2923. if (returnState === PredictionContext.EMPTY_RETURN_STATE && parent === null) {
  2924. // someone can pass in the bits of an array ctx that mean $
  2925. return PredictionContext.EMPTY;
  2926. } else {
  2927. return new SingletonPredictionContext(parent, returnState);
  2928. }
  2929. };
  2930. Object.defineProperty(SingletonPredictionContext.prototype, "length", {
  2931. get : function() {
  2932. return 1;
  2933. }
  2934. });
  2935. SingletonPredictionContext.prototype.getParent = function(index) {
  2936. return this.parentCtx;
  2937. };
  2938. SingletonPredictionContext.prototype.getReturnState = function(index) {
  2939. return this.returnState;
  2940. };
  2941. SingletonPredictionContext.prototype.equals = function(other) {
  2942. if (this === other) {
  2943. return true;
  2944. } else if (!(other instanceof SingletonPredictionContext)) {
  2945. return false;
  2946. } else if (this.hashCode() !== other.hashCode()) {
  2947. return false; // can't be same if hash is different
  2948. } else {
  2949. if(this.returnState !== other.returnState)
  2950. return false;
  2951. else if(this.parentCtx==null)
  2952. return other.parentCtx==null
  2953. else
  2954. return this.parentCtx.equals(other.parentCtx);
  2955. }
  2956. };
  2957. SingletonPredictionContext.prototype.toString = function() {
  2958. var up = this.parentCtx === null ? "" : this.parentCtx.toString();
  2959. if (up.length === 0) {
  2960. if (this.returnState === PredictionContext.EMPTY_RETURN_STATE) {
  2961. return "$";
  2962. } else {
  2963. return "" + this.returnState;
  2964. }
  2965. } else {
  2966. return "" + this.returnState + " " + up;
  2967. }
  2968. };
  2969. function EmptyPredictionContext() {
  2970. SingletonPredictionContext.call(this, null, PredictionContext.EMPTY_RETURN_STATE);
  2971. return this;
  2972. }
  2973. EmptyPredictionContext.prototype = Object.create(SingletonPredictionContext.prototype);
  2974. EmptyPredictionContext.prototype.constructor = EmptyPredictionContext;
  2975. EmptyPredictionContext.prototype.isEmpty = function() {
  2976. return true;
  2977. };
  2978. EmptyPredictionContext.prototype.getParent = function(index) {
  2979. return null;
  2980. };
  2981. EmptyPredictionContext.prototype.getReturnState = function(index) {
  2982. return this.returnState;
  2983. };
  2984. EmptyPredictionContext.prototype.equals = function(other) {
  2985. return this === other;
  2986. };
  2987. EmptyPredictionContext.prototype.toString = function() {
  2988. return "$";
  2989. };
  2990. PredictionContext.EMPTY = new EmptyPredictionContext();
  2991. function ArrayPredictionContext(parents, returnStates) {
  2992. // Parent can be null only if full ctx mode and we make an array
  2993. // from {@link //EMPTY} and non-empty. We merge {@link //EMPTY} by using
  2994. // null parent and
  2995. // returnState == {@link //EMPTY_RETURN_STATE}.
  2996. var h = new Hash();
  2997. h.update(parents, returnStates);
  2998. var hashCode = h.finish();
  2999. PredictionContext.call(this, hashCode);
  3000. this.parents = parents;
  3001. this.returnStates = returnStates;
  3002. return this;
  3003. }
  3004. ArrayPredictionContext.prototype = Object.create(PredictionContext.prototype);
  3005. ArrayPredictionContext.prototype.constructor = ArrayPredictionContext;
  3006. ArrayPredictionContext.prototype.isEmpty = function() {
  3007. // since EMPTY_RETURN_STATE can only appear in the last position, we
  3008. // don't need to verify that size==1
  3009. return this.returnStates[0] === PredictionContext.EMPTY_RETURN_STATE;
  3010. };
  3011. Object.defineProperty(ArrayPredictionContext.prototype, "length", {
  3012. get : function() {
  3013. return this.returnStates.length;
  3014. }
  3015. });
  3016. ArrayPredictionContext.prototype.getParent = function(index) {
  3017. return this.parents[index];
  3018. };
  3019. ArrayPredictionContext.prototype.getReturnState = function(index) {
  3020. return this.returnStates[index];
  3021. };
  3022. ArrayPredictionContext.prototype.equals = function(other) {
  3023. if (this === other) {
  3024. return true;
  3025. } else if (!(other instanceof ArrayPredictionContext)) {
  3026. return false;
  3027. } else if (this.hashCode() !== other.hashCode()) {
  3028. return false; // can't be same if hash is different
  3029. } else {
  3030. return this.returnStates === other.returnStates &&
  3031. this.parents === other.parents;
  3032. }
  3033. };
  3034. ArrayPredictionContext.prototype.toString = function() {
  3035. if (this.isEmpty()) {
  3036. return "[]";
  3037. } else {
  3038. var s = "[";
  3039. for (var i = 0; i < this.returnStates.length; i++) {
  3040. if (i > 0) {
  3041. s = s + ", ";
  3042. }
  3043. if (this.returnStates[i] === PredictionContext.EMPTY_RETURN_STATE) {
  3044. s = s + "$";
  3045. continue;
  3046. }
  3047. s = s + this.returnStates[i];
  3048. if (this.parents[i] !== null) {
  3049. s = s + " " + this.parents[i];
  3050. } else {
  3051. s = s + "null";
  3052. }
  3053. }
  3054. return s + "]";
  3055. }
  3056. };
  3057. // Convert a {@link RuleContext} tree to a {@link PredictionContext} graph.
  3058. // Return {@link //EMPTY} if {@code outerContext} is empty or null.
  3059. // /
  3060. function predictionContextFromRuleContext(atn, outerContext) {
  3061. if (outerContext === undefined || outerContext === null) {
  3062. outerContext = RuleContext.EMPTY;
  3063. }
  3064. // if we are in RuleContext of start rule, s, then PredictionContext
  3065. // is EMPTY. Nobody called us. (if we are empty, return empty)
  3066. if (outerContext.parentCtx === null || outerContext === RuleContext.EMPTY) {
  3067. return PredictionContext.EMPTY;
  3068. }
  3069. // If we have a parent, convert it to a PredictionContext graph
  3070. var parent = predictionContextFromRuleContext(atn, outerContext.parentCtx);
  3071. var state = atn.states[outerContext.invokingState];
  3072. var transition = state.transitions[0];
  3073. return SingletonPredictionContext.create(parent, transition.followState.stateNumber);
  3074. }
  3075. /*
  3076. function calculateListsHashString(parents, returnStates) {
  3077. var s = "";
  3078. parents.map(function(p) {
  3079. s = s + p;
  3080. });
  3081. returnStates.map(function(r) {
  3082. s = s + r;
  3083. });
  3084. return s;
  3085. }
  3086. */
  3087. function merge(a, b, rootIsWildcard, mergeCache) {
  3088. // share same graph if both same
  3089. if (a === b) {
  3090. return a;
  3091. }
  3092. if (a instanceof SingletonPredictionContext && b instanceof SingletonPredictionContext) {
  3093. return mergeSingletons(a, b, rootIsWildcard, mergeCache);
  3094. }
  3095. // At least one of a or b is array
  3096. // If one is $ and rootIsWildcard, return $ as// wildcard
  3097. if (rootIsWildcard) {
  3098. if (a instanceof EmptyPredictionContext) {
  3099. return a;
  3100. }
  3101. if (b instanceof EmptyPredictionContext) {
  3102. return b;
  3103. }
  3104. }
  3105. // convert singleton so both are arrays to normalize
  3106. if (a instanceof SingletonPredictionContext) {
  3107. a = new ArrayPredictionContext([a.getParent()], [a.returnState]);
  3108. }
  3109. if (b instanceof SingletonPredictionContext) {
  3110. b = new ArrayPredictionContext([b.getParent()], [b.returnState]);
  3111. }
  3112. return mergeArrays(a, b, rootIsWildcard, mergeCache);
  3113. }
  3114. //
  3115. // Merge two {@link SingletonPredictionContext} instances.
  3116. //
  3117. // <p>Stack tops equal, parents merge is same; return left graph.<br>
  3118. // <embed src="images/SingletonMerge_SameRootSamePar.svg"
  3119. // type="image/svg+xml"/></p>
  3120. //
  3121. // <p>Same stack top, parents differ; merge parents giving array node, then
  3122. // remainders of those graphs. A new root node is created to point to the
  3123. // merged parents.<br>
  3124. // <embed src="images/SingletonMerge_SameRootDiffPar.svg"
  3125. // type="image/svg+xml"/></p>
  3126. //
  3127. // <p>Different stack tops pointing to same parent. Make array node for the
  3128. // root where both element in the root point to the same (original)
  3129. // parent.<br>
  3130. // <embed src="images/SingletonMerge_DiffRootSamePar.svg"
  3131. // type="image/svg+xml"/></p>
  3132. //
  3133. // <p>Different stack tops pointing to different parents. Make array node for
  3134. // the root where each element points to the corresponding original
  3135. // parent.<br>
  3136. // <embed src="images/SingletonMerge_DiffRootDiffPar.svg"
  3137. // type="image/svg+xml"/></p>
  3138. //
  3139. // @param a the first {@link SingletonPredictionContext}
  3140. // @param b the second {@link SingletonPredictionContext}
  3141. // @param rootIsWildcard {@code true} if this is a local-context merge,
  3142. // otherwise false to indicate a full-context merge
  3143. // @param mergeCache
  3144. // /
  3145. function mergeSingletons(a, b, rootIsWildcard, mergeCache) {
  3146. if (mergeCache !== null) {
  3147. var previous = mergeCache.get(a, b);
  3148. if (previous !== null) {
  3149. return previous;
  3150. }
  3151. previous = mergeCache.get(b, a);
  3152. if (previous !== null) {
  3153. return previous;
  3154. }
  3155. }
  3156. var rootMerge = mergeRoot(a, b, rootIsWildcard);
  3157. if (rootMerge !== null) {
  3158. if (mergeCache !== null) {
  3159. mergeCache.set(a, b, rootMerge);
  3160. }
  3161. return rootMerge;
  3162. }
  3163. if (a.returnState === b.returnState) {
  3164. var parent = merge(a.parentCtx, b.parentCtx, rootIsWildcard, mergeCache);
  3165. // if parent is same as existing a or b parent or reduced to a parent,
  3166. // return it
  3167. if (parent === a.parentCtx) {
  3168. return a; // ax + bx = ax, if a=b
  3169. }
  3170. if (parent === b.parentCtx) {
  3171. return b; // ax + bx = bx, if a=b
  3172. }
  3173. // else: ax + ay = a'[x,y]
  3174. // merge parents x and y, giving array node with x,y then remainders
  3175. // of those graphs. dup a, a' points at merged array
  3176. // new joined parent so create new singleton pointing to it, a'
  3177. var spc = SingletonPredictionContext.create(parent, a.returnState);
  3178. if (mergeCache !== null) {
  3179. mergeCache.set(a, b, spc);
  3180. }
  3181. return spc;
  3182. } else { // a != b payloads differ
  3183. // see if we can collapse parents due to $+x parents if local ctx
  3184. var singleParent = null;
  3185. if (a === b || (a.parentCtx !== null && a.parentCtx === b.parentCtx)) { // ax +
  3186. // bx =
  3187. // [a,b]x
  3188. singleParent = a.parentCtx;
  3189. }
  3190. if (singleParent !== null) { // parents are same
  3191. // sort payloads and use same parent
  3192. var payloads = [ a.returnState, b.returnState ];
  3193. if (a.returnState > b.returnState) {
  3194. payloads[0] = b.returnState;
  3195. payloads[1] = a.returnState;
  3196. }
  3197. var parents = [ singleParent, singleParent ];
  3198. var apc = new ArrayPredictionContext(parents, payloads);
  3199. if (mergeCache !== null) {
  3200. mergeCache.set(a, b, apc);
  3201. }
  3202. return apc;
  3203. }
  3204. // parents differ and can't merge them. Just pack together
  3205. // into array; can't merge.
  3206. // ax + by = [ax,by]
  3207. var payloads = [ a.returnState, b.returnState ];
  3208. var parents = [ a.parentCtx, b.parentCtx ];
  3209. if (a.returnState > b.returnState) { // sort by payload
  3210. payloads[0] = b.returnState;
  3211. payloads[1] = a.returnState;
  3212. parents = [ b.parentCtx, a.parentCtx ];
  3213. }
  3214. var a_ = new ArrayPredictionContext(parents, payloads);
  3215. if (mergeCache !== null) {
  3216. mergeCache.set(a, b, a_);
  3217. }
  3218. return a_;
  3219. }
  3220. }
  3221. //
  3222. // Handle case where at least one of {@code a} or {@code b} is
  3223. // {@link //EMPTY}. In the following diagrams, the symbol {@code $} is used
  3224. // to represent {@link //EMPTY}.
  3225. //
  3226. // <h2>Local-Context Merges</h2>
  3227. //
  3228. // <p>These local-context merge operations are used when {@code rootIsWildcard}
  3229. // is true.</p>
  3230. //
  3231. // <p>{@link //EMPTY} is superset of any graph; return {@link //EMPTY}.<br>
  3232. // <embed src="images/LocalMerge_EmptyRoot.svg" type="image/svg+xml"/></p>
  3233. //
  3234. // <p>{@link //EMPTY} and anything is {@code //EMPTY}, so merged parent is
  3235. // {@code //EMPTY}; return left graph.<br>
  3236. // <embed src="images/LocalMerge_EmptyParent.svg" type="image/svg+xml"/></p>
  3237. //
  3238. // <p>Special case of last merge if local context.<br>
  3239. // <embed src="images/LocalMerge_DiffRoots.svg" type="image/svg+xml"/></p>
  3240. //
  3241. // <h2>Full-Context Merges</h2>
  3242. //
  3243. // <p>These full-context merge operations are used when {@code rootIsWildcard}
  3244. // is false.</p>
  3245. //
  3246. // <p><embed src="images/FullMerge_EmptyRoots.svg" type="image/svg+xml"/></p>
  3247. //
  3248. // <p>Must keep all contexts; {@link //EMPTY} in array is a special value (and
  3249. // null parent).<br>
  3250. // <embed src="images/FullMerge_EmptyRoot.svg" type="image/svg+xml"/></p>
  3251. //
  3252. // <p><embed src="images/FullMerge_SameRoot.svg" type="image/svg+xml"/></p>
  3253. //
  3254. // @param a the first {@link SingletonPredictionContext}
  3255. // @param b the second {@link SingletonPredictionContext}
  3256. // @param rootIsWildcard {@code true} if this is a local-context merge,
  3257. // otherwise false to indicate a full-context merge
  3258. // /
  3259. function mergeRoot(a, b, rootIsWildcard) {
  3260. if (rootIsWildcard) {
  3261. if (a === PredictionContext.EMPTY) {
  3262. return PredictionContext.EMPTY; // // + b =//
  3263. }
  3264. if (b === PredictionContext.EMPTY) {
  3265. return PredictionContext.EMPTY; // a +// =//
  3266. }
  3267. } else {
  3268. if (a === PredictionContext.EMPTY && b === PredictionContext.EMPTY) {
  3269. return PredictionContext.EMPTY; // $ + $ = $
  3270. } else if (a === PredictionContext.EMPTY) { // $ + x = [$,x]
  3271. var payloads = [ b.returnState,
  3272. PredictionContext.EMPTY_RETURN_STATE ];
  3273. var parents = [ b.parentCtx, null ];
  3274. return new ArrayPredictionContext(parents, payloads);
  3275. } else if (b === PredictionContext.EMPTY) { // x + $ = [$,x] ($ is always first if present)
  3276. var payloads = [ a.returnState, PredictionContext.EMPTY_RETURN_STATE ];
  3277. var parents = [ a.parentCtx, null ];
  3278. return new ArrayPredictionContext(parents, payloads);
  3279. }
  3280. }
  3281. return null;
  3282. }
  3283. //
  3284. // Merge two {@link ArrayPredictionContext} instances.
  3285. //
  3286. // <p>Different tops, different parents.<br>
  3287. // <embed src="images/ArrayMerge_DiffTopDiffPar.svg" type="image/svg+xml"/></p>
  3288. //
  3289. // <p>Shared top, same parents.<br>
  3290. // <embed src="images/ArrayMerge_ShareTopSamePar.svg" type="image/svg+xml"/></p>
  3291. //
  3292. // <p>Shared top, different parents.<br>
  3293. // <embed src="images/ArrayMerge_ShareTopDiffPar.svg" type="image/svg+xml"/></p>
  3294. //
  3295. // <p>Shared top, all shared parents.<br>
  3296. // <embed src="images/ArrayMerge_ShareTopSharePar.svg"
  3297. // type="image/svg+xml"/></p>
  3298. //
  3299. // <p>Equal tops, merge parents and reduce top to
  3300. // {@link SingletonPredictionContext}.<br>
  3301. // <embed src="images/ArrayMerge_EqualTop.svg" type="image/svg+xml"/></p>
  3302. // /
  3303. function mergeArrays(a, b, rootIsWildcard, mergeCache) {
  3304. if (mergeCache !== null) {
  3305. var previous = mergeCache.get(a, b);
  3306. if (previous !== null) {
  3307. return previous;
  3308. }
  3309. previous = mergeCache.get(b, a);
  3310. if (previous !== null) {
  3311. return previous;
  3312. }
  3313. }
  3314. // merge sorted payloads a + b => M
  3315. var i = 0; // walks a
  3316. var j = 0; // walks b
  3317. var k = 0; // walks target M array
  3318. var mergedReturnStates = [];
  3319. var mergedParents = [];
  3320. // walk and merge to yield mergedParents, mergedReturnStates
  3321. while (i < a.returnStates.length && j < b.returnStates.length) {
  3322. var a_parent = a.parents[i];
  3323. var b_parent = b.parents[j];
  3324. if (a.returnStates[i] === b.returnStates[j]) {
  3325. // same payload (stack tops are equal), must yield merged singleton
  3326. var payload = a.returnStates[i];
  3327. // $+$ = $
  3328. var bothDollars = payload === PredictionContext.EMPTY_RETURN_STATE &&
  3329. a_parent === null && b_parent === null;
  3330. var ax_ax = (a_parent !== null && b_parent !== null && a_parent === b_parent); // ax+ax
  3331. // ->
  3332. // ax
  3333. if (bothDollars || ax_ax) {
  3334. mergedParents[k] = a_parent; // choose left
  3335. mergedReturnStates[k] = payload;
  3336. } else { // ax+ay -> a'[x,y]
  3337. var mergedParent = merge(a_parent, b_parent, rootIsWildcard, mergeCache);
  3338. mergedParents[k] = mergedParent;
  3339. mergedReturnStates[k] = payload;
  3340. }
  3341. i += 1; // hop over left one as usual
  3342. j += 1; // but also skip one in right side since we merge
  3343. } else if (a.returnStates[i] < b.returnStates[j]) { // copy a[i] to M
  3344. mergedParents[k] = a_parent;
  3345. mergedReturnStates[k] = a.returnStates[i];
  3346. i += 1;
  3347. } else { // b > a, copy b[j] to M
  3348. mergedParents[k] = b_parent;
  3349. mergedReturnStates[k] = b.returnStates[j];
  3350. j += 1;
  3351. }
  3352. k += 1;
  3353. }
  3354. // copy over any payloads remaining in either array
  3355. if (i < a.returnStates.length) {
  3356. for (var p = i; p < a.returnStates.length; p++) {
  3357. mergedParents[k] = a.parents[p];
  3358. mergedReturnStates[k] = a.returnStates[p];
  3359. k += 1;
  3360. }
  3361. } else {
  3362. for (var p = j; p < b.returnStates.length; p++) {
  3363. mergedParents[k] = b.parents[p];
  3364. mergedReturnStates[k] = b.returnStates[p];
  3365. k += 1;
  3366. }
  3367. }
  3368. // trim merged if we combined a few that had same stack tops
  3369. if (k < mergedParents.length) { // write index < last position; trim
  3370. if (k === 1) { // for just one merged element, return singleton top
  3371. var a_ = SingletonPredictionContext.create(mergedParents[0],
  3372. mergedReturnStates[0]);
  3373. if (mergeCache !== null) {
  3374. mergeCache.set(a, b, a_);
  3375. }
  3376. return a_;
  3377. }
  3378. mergedParents = mergedParents.slice(0, k);
  3379. mergedReturnStates = mergedReturnStates.slice(0, k);
  3380. }
  3381. var M = new ArrayPredictionContext(mergedParents, mergedReturnStates);
  3382. // if we created same array as a or b, return that instead
  3383. // TODO: track whether this is possible above during merge sort for speed
  3384. if (M === a) {
  3385. if (mergeCache !== null) {
  3386. mergeCache.set(a, b, a);
  3387. }
  3388. return a;
  3389. }
  3390. if (M === b) {
  3391. if (mergeCache !== null) {
  3392. mergeCache.set(a, b, b);
  3393. }
  3394. return b;
  3395. }
  3396. combineCommonParents(mergedParents);
  3397. if (mergeCache !== null) {
  3398. mergeCache.set(a, b, M);
  3399. }
  3400. return M;
  3401. }
  3402. //
  3403. // Make pass over all <em>M</em> {@code parents}; merge any {@code equals()}
  3404. // ones.
  3405. // /
  3406. function combineCommonParents(parents) {
  3407. var uniqueParents = new Map();
  3408. for (var p = 0; p < parents.length; p++) {
  3409. var parent = parents[p];
  3410. if (!(uniqueParents.containsKey(parent))) {
  3411. uniqueParents.put(parent, parent);
  3412. }
  3413. }
  3414. for (var q = 0; q < parents.length; q++) {
  3415. parents[q] = uniqueParents.get(parents[q]);
  3416. }
  3417. }
  3418. function getCachedPredictionContext(context, contextCache, visited) {
  3419. if (context.isEmpty()) {
  3420. return context;
  3421. }
  3422. var existing = visited.get(context) || null;
  3423. if (existing !== null) {
  3424. return existing;
  3425. }
  3426. existing = contextCache.get(context);
  3427. if (existing !== null) {
  3428. visited.put(context, existing);
  3429. return existing;
  3430. }
  3431. var changed = false;
  3432. var parents = [];
  3433. for (var i = 0; i < parents.length; i++) {
  3434. var parent = getCachedPredictionContext(context.getParent(i), contextCache, visited);
  3435. if (changed || parent !== context.getParent(i)) {
  3436. if (!changed) {
  3437. parents = [];
  3438. for (var j = 0; j < context.length; j++) {
  3439. parents[j] = context.getParent(j);
  3440. }
  3441. changed = true;
  3442. }
  3443. parents[i] = parent;
  3444. }
  3445. }
  3446. if (!changed) {
  3447. contextCache.add(context);
  3448. visited.put(context, context);
  3449. return context;
  3450. }
  3451. var updated = null;
  3452. if (parents.length === 0) {
  3453. updated = PredictionContext.EMPTY;
  3454. } else if (parents.length === 1) {
  3455. updated = SingletonPredictionContext.create(parents[0], context
  3456. .getReturnState(0));
  3457. } else {
  3458. updated = new ArrayPredictionContext(parents, context.returnStates);
  3459. }
  3460. contextCache.add(updated);
  3461. visited.put(updated, updated);
  3462. visited.put(context, updated);
  3463. return updated;
  3464. }
  3465. // ter's recursive version of Sam's getAllNodes()
  3466. function getAllContextNodes(context, nodes, visited) {
  3467. if (nodes === null) {
  3468. nodes = [];
  3469. return getAllContextNodes(context, nodes, visited);
  3470. } else if (visited === null) {
  3471. visited = new Map();
  3472. return getAllContextNodes(context, nodes, visited);
  3473. } else {
  3474. if (context === null || visited.containsKey(context)) {
  3475. return nodes;
  3476. }
  3477. visited.put(context, context);
  3478. nodes.push(context);
  3479. for (var i = 0; i < context.length; i++) {
  3480. getAllContextNodes(context.getParent(i), nodes, visited);
  3481. }
  3482. return nodes;
  3483. }
  3484. }
  3485. exports.merge = merge;
  3486. exports.PredictionContext = PredictionContext;
  3487. exports.PredictionContextCache = PredictionContextCache;
  3488. exports.SingletonPredictionContext = SingletonPredictionContext;
  3489. exports.predictionContextFromRuleContext = predictionContextFromRuleContext;
  3490. exports.getCachedPredictionContext = getCachedPredictionContext;
  3491. /***/ }),
  3492. /***/ "./node_modules/antlr4/Recognizer.js":
  3493. /*!*******************************************!*\
  3494. !*** ./node_modules/antlr4/Recognizer.js ***!
  3495. \*******************************************/
  3496. /*! no static exports found */
  3497. /***/ (function(module, exports, __webpack_require__) {
  3498. //
  3499. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3500. * Use of this file is governed by the BSD 3-clause license that
  3501. * can be found in the LICENSE.txt file in the project root.
  3502. */
  3503. //
  3504. var Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  3505. var ConsoleErrorListener = __webpack_require__(/*! ./error/ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ConsoleErrorListener;
  3506. var ProxyErrorListener = __webpack_require__(/*! ./error/ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ProxyErrorListener;
  3507. function Recognizer() {
  3508. this._listeners = [ ConsoleErrorListener.INSTANCE ];
  3509. this._interp = null;
  3510. this._stateNumber = -1;
  3511. return this;
  3512. }
  3513. Recognizer.tokenTypeMapCache = {};
  3514. Recognizer.ruleIndexMapCache = {};
  3515. Recognizer.prototype.checkVersion = function(toolVersion) {
  3516. var runtimeVersion = "4.8";
  3517. if (runtimeVersion!==toolVersion) {
  3518. console.log("ANTLR runtime and generated code versions disagree: "+runtimeVersion+"!="+toolVersion);
  3519. }
  3520. };
  3521. Recognizer.prototype.addErrorListener = function(listener) {
  3522. this._listeners.push(listener);
  3523. };
  3524. Recognizer.prototype.removeErrorListeners = function() {
  3525. this._listeners = [];
  3526. };
  3527. Recognizer.prototype.getTokenTypeMap = function() {
  3528. var tokenNames = this.getTokenNames();
  3529. if (tokenNames===null) {
  3530. throw("The current recognizer does not provide a list of token names.");
  3531. }
  3532. var result = this.tokenTypeMapCache[tokenNames];
  3533. if(result===undefined) {
  3534. result = tokenNames.reduce(function(o, k, i) { o[k] = i; });
  3535. result.EOF = Token.EOF;
  3536. this.tokenTypeMapCache[tokenNames] = result;
  3537. }
  3538. return result;
  3539. };
  3540. // Get a map from rule names to rule indexes.
  3541. //
  3542. // <p>Used for XPath and tree pattern compilation.</p>
  3543. //
  3544. Recognizer.prototype.getRuleIndexMap = function() {
  3545. var ruleNames = this.ruleNames;
  3546. if (ruleNames===null) {
  3547. throw("The current recognizer does not provide a list of rule names.");
  3548. }
  3549. var result = this.ruleIndexMapCache[ruleNames];
  3550. if(result===undefined) {
  3551. result = ruleNames.reduce(function(o, k, i) { o[k] = i; });
  3552. this.ruleIndexMapCache[ruleNames] = result;
  3553. }
  3554. return result;
  3555. };
  3556. Recognizer.prototype.getTokenType = function(tokenName) {
  3557. var ttype = this.getTokenTypeMap()[tokenName];
  3558. if (ttype !==undefined) {
  3559. return ttype;
  3560. } else {
  3561. return Token.INVALID_TYPE;
  3562. }
  3563. };
  3564. // What is the error header, normally line/character position information?//
  3565. Recognizer.prototype.getErrorHeader = function(e) {
  3566. var line = e.getOffendingToken().line;
  3567. var column = e.getOffendingToken().column;
  3568. return "line " + line + ":" + column;
  3569. };
  3570. // How should a token be displayed in an error message? The default
  3571. // is to display just the text, but during development you might
  3572. // want to have a lot of information spit out. Override in that case
  3573. // to use t.toString() (which, for CommonToken, dumps everything about
  3574. // the token). This is better than forcing you to override a method in
  3575. // your token objects because you don't have to go modify your lexer
  3576. // so that it creates a new Java type.
  3577. //
  3578. // @deprecated This method is not called by the ANTLR 4 Runtime. Specific
  3579. // implementations of {@link ANTLRErrorStrategy} may provide a similar
  3580. // feature when necessary. For example, see
  3581. // {@link DefaultErrorStrategy//getTokenErrorDisplay}.
  3582. //
  3583. Recognizer.prototype.getTokenErrorDisplay = function(t) {
  3584. if (t===null) {
  3585. return "<no token>";
  3586. }
  3587. var s = t.text;
  3588. if (s===null) {
  3589. if (t.type===Token.EOF) {
  3590. s = "<EOF>";
  3591. } else {
  3592. s = "<" + t.type + ">";
  3593. }
  3594. }
  3595. s = s.replace("\n","\\n").replace("\r","\\r").replace("\t","\\t");
  3596. return "'" + s + "'";
  3597. };
  3598. Recognizer.prototype.getErrorListenerDispatch = function() {
  3599. return new ProxyErrorListener(this._listeners);
  3600. };
  3601. // subclass needs to override these if there are sempreds or actions
  3602. // that the ATN interp needs to execute
  3603. Recognizer.prototype.sempred = function(localctx, ruleIndex, actionIndex) {
  3604. return true;
  3605. };
  3606. Recognizer.prototype.precpred = function(localctx , precedence) {
  3607. return true;
  3608. };
  3609. //Indicate that the recognizer has changed internal state that is
  3610. //consistent with the ATN state passed in. This way we always know
  3611. //where we are in the ATN as the parser goes along. The rule
  3612. //context objects form a stack that lets us see the stack of
  3613. //invoking rules. Combine this and we have complete ATN
  3614. //configuration information.
  3615. Object.defineProperty(Recognizer.prototype, "state", {
  3616. get : function() {
  3617. return this._stateNumber;
  3618. },
  3619. set : function(state) {
  3620. this._stateNumber = state;
  3621. }
  3622. });
  3623. exports.Recognizer = Recognizer;
  3624. /***/ }),
  3625. /***/ "./node_modules/antlr4/RuleContext.js":
  3626. /*!********************************************!*\
  3627. !*** ./node_modules/antlr4/RuleContext.js ***!
  3628. \********************************************/
  3629. /*! no static exports found */
  3630. /***/ (function(module, exports, __webpack_require__) {
  3631. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3632. * Use of this file is governed by the BSD 3-clause license that
  3633. * can be found in the LICENSE.txt file in the project root.
  3634. */
  3635. ///
  3636. // A rule context is a record of a single rule invocation. It knows
  3637. // which context invoked it, if any. If there is no parent context, then
  3638. // naturally the invoking state is not valid. The parent link
  3639. // provides a chain upwards from the current rule invocation to the root
  3640. // of the invocation tree, forming a stack. We actually carry no
  3641. // information about the rule associated with this context (except
  3642. // when parsing). We keep only the state number of the invoking state from
  3643. // the ATN submachine that invoked this. Contrast this with the s
  3644. // pointer inside ParserRuleContext that tracks the current state
  3645. // being "executed" for the current rule.
  3646. //
  3647. // The parent contexts are useful for computing lookahead sets and
  3648. // getting error information.
  3649. //
  3650. // These objects are used during parsing and prediction.
  3651. // For the special case of parsers, we use the subclass
  3652. // ParserRuleContext.
  3653. //
  3654. // @see ParserRuleContext
  3655. ///
  3656. var RuleNode = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").RuleNode;
  3657. var INVALID_INTERVAL = __webpack_require__(/*! ./tree/Tree */ "./node_modules/antlr4/tree/Tree.js").INVALID_INTERVAL;
  3658. var INVALID_ALT_NUMBER = __webpack_require__(/*! ./atn/ATN */ "./node_modules/antlr4/atn/ATN.js").INVALID_ALT_NUMBER;
  3659. function RuleContext(parent, invokingState) {
  3660. RuleNode.call(this);
  3661. // What context invoked this rule?
  3662. this.parentCtx = parent || null;
  3663. // What state invoked the rule associated with this context?
  3664. // The "return address" is the followState of invokingState
  3665. // If parent is null, this should be -1.
  3666. this.invokingState = invokingState || -1;
  3667. return this;
  3668. }
  3669. RuleContext.prototype = Object.create(RuleNode.prototype);
  3670. RuleContext.prototype.constructor = RuleContext;
  3671. RuleContext.prototype.depth = function() {
  3672. var n = 0;
  3673. var p = this;
  3674. while (p !== null) {
  3675. p = p.parentCtx;
  3676. n += 1;
  3677. }
  3678. return n;
  3679. };
  3680. // A context is empty if there is no invoking state; meaning nobody call
  3681. // current context.
  3682. RuleContext.prototype.isEmpty = function() {
  3683. return this.invokingState === -1;
  3684. };
  3685. // satisfy the ParseTree / SyntaxTree interface
  3686. RuleContext.prototype.getSourceInterval = function() {
  3687. return INVALID_INTERVAL;
  3688. };
  3689. RuleContext.prototype.getRuleContext = function() {
  3690. return this;
  3691. };
  3692. RuleContext.prototype.getPayload = function() {
  3693. return this;
  3694. };
  3695. // Return the combined text of all child nodes. This method only considers
  3696. // tokens which have been added to the parse tree.
  3697. // <p>
  3698. // Since tokens on hidden channels (e.g. whitespace or comments) are not
  3699. // added to the parse trees, they will not appear in the output of this
  3700. // method.
  3701. // /
  3702. RuleContext.prototype.getText = function() {
  3703. if (this.getChildCount() === 0) {
  3704. return "";
  3705. } else {
  3706. return this.children.map(function(child) {
  3707. return child.getText();
  3708. }).join("");
  3709. }
  3710. };
  3711. // For rule associated with this parse tree internal node, return
  3712. // the outer alternative number used to match the input. Default
  3713. // implementation does not compute nor store this alt num. Create
  3714. // a subclass of ParserRuleContext with backing field and set
  3715. // option contextSuperClass.
  3716. // to set it.
  3717. RuleContext.prototype.getAltNumber = function() { return INVALID_ALT_NUMBER; }
  3718. // Set the outer alternative number for this context node. Default
  3719. // implementation does nothing to avoid backing field overhead for
  3720. // trees that don't need it. Create
  3721. // a subclass of ParserRuleContext with backing field and set
  3722. // option contextSuperClass.
  3723. RuleContext.prototype.setAltNumber = function(altNumber) { }
  3724. RuleContext.prototype.getChild = function(i) {
  3725. return null;
  3726. };
  3727. RuleContext.prototype.getChildCount = function() {
  3728. return 0;
  3729. };
  3730. RuleContext.prototype.accept = function(visitor) {
  3731. return visitor.visitChildren(this);
  3732. };
  3733. //need to manage circular dependencies, so export now
  3734. exports.RuleContext = RuleContext;
  3735. var Trees = __webpack_require__(/*! ./tree/Trees */ "./node_modules/antlr4/tree/Trees.js").Trees;
  3736. // Print out a whole tree, not just a node, in LISP format
  3737. // (root child1 .. childN). Print just a node if this is a leaf.
  3738. //
  3739. RuleContext.prototype.toStringTree = function(ruleNames, recog) {
  3740. return Trees.toStringTree(this, ruleNames, recog);
  3741. };
  3742. RuleContext.prototype.toString = function(ruleNames, stop) {
  3743. ruleNames = ruleNames || null;
  3744. stop = stop || null;
  3745. var p = this;
  3746. var s = "[";
  3747. while (p !== null && p !== stop) {
  3748. if (ruleNames === null) {
  3749. if (!p.isEmpty()) {
  3750. s += p.invokingState;
  3751. }
  3752. } else {
  3753. var ri = p.ruleIndex;
  3754. var ruleName = (ri >= 0 && ri < ruleNames.length) ? ruleNames[ri]
  3755. : "" + ri;
  3756. s += ruleName;
  3757. }
  3758. if (p.parentCtx !== null && (ruleNames !== null || !p.parentCtx.isEmpty())) {
  3759. s += " ";
  3760. }
  3761. p = p.parentCtx;
  3762. }
  3763. s += "]";
  3764. return s;
  3765. };
  3766. /***/ }),
  3767. /***/ "./node_modules/antlr4/Token.js":
  3768. /*!**************************************!*\
  3769. !*** ./node_modules/antlr4/Token.js ***!
  3770. \**************************************/
  3771. /*! no static exports found */
  3772. /***/ (function(module, exports) {
  3773. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3774. * Use of this file is governed by the BSD 3-clause license that
  3775. * can be found in the LICENSE.txt file in the project root.
  3776. */
  3777. //
  3778. // A token has properties: text, type, line, character position in the line
  3779. // (so we can ignore tabs), token channel, index, and source from which
  3780. // we obtained this token.
  3781. function Token() {
  3782. this.source = null;
  3783. this.type = null; // token type of the token
  3784. this.channel = null; // The parser ignores everything not on DEFAULT_CHANNEL
  3785. this.start = null; // optional; return -1 if not implemented.
  3786. this.stop = null; // optional; return -1 if not implemented.
  3787. this.tokenIndex = null; // from 0..n-1 of the token object in the input stream
  3788. this.line = null; // line=1..n of the 1st character
  3789. this.column = null; // beginning of the line at which it occurs, 0..n-1
  3790. this._text = null; // text of the token.
  3791. return this;
  3792. }
  3793. Token.INVALID_TYPE = 0;
  3794. // During lookahead operations, this "token" signifies we hit rule end ATN state
  3795. // and did not follow it despite needing to.
  3796. Token.EPSILON = -2;
  3797. Token.MIN_USER_TOKEN_TYPE = 1;
  3798. Token.EOF = -1;
  3799. // All tokens go to the parser (unless skip() is called in that rule)
  3800. // on a particular "channel". The parser tunes to a particular channel
  3801. // so that whitespace etc... can go to the parser on a "hidden" channel.
  3802. Token.DEFAULT_CHANNEL = 0;
  3803. // Anything on different channel than DEFAULT_CHANNEL is not parsed
  3804. // by parser.
  3805. Token.HIDDEN_CHANNEL = 1;
  3806. // Explicitly set the text for this token. If {code text} is not
  3807. // {@code null}, then {@link //getText} will return this value rather than
  3808. // extracting the text from the input.
  3809. //
  3810. // @param text The explicit text of the token, or {@code null} if the text
  3811. // should be obtained from the input along with the start and stop indexes
  3812. // of the token.
  3813. Object.defineProperty(Token.prototype, "text", {
  3814. get : function() {
  3815. return this._text;
  3816. },
  3817. set : function(text) {
  3818. this._text = text;
  3819. }
  3820. });
  3821. Token.prototype.getTokenSource = function() {
  3822. return this.source[0];
  3823. };
  3824. Token.prototype.getInputStream = function() {
  3825. return this.source[1];
  3826. };
  3827. function CommonToken(source, type, channel, start, stop) {
  3828. Token.call(this);
  3829. this.source = source !== undefined ? source : CommonToken.EMPTY_SOURCE;
  3830. this.type = type !== undefined ? type : null;
  3831. this.channel = channel !== undefined ? channel : Token.DEFAULT_CHANNEL;
  3832. this.start = start !== undefined ? start : -1;
  3833. this.stop = stop !== undefined ? stop : -1;
  3834. this.tokenIndex = -1;
  3835. if (this.source[0] !== null) {
  3836. this.line = source[0].line;
  3837. this.column = source[0].column;
  3838. } else {
  3839. this.column = -1;
  3840. }
  3841. return this;
  3842. }
  3843. CommonToken.prototype = Object.create(Token.prototype);
  3844. CommonToken.prototype.constructor = CommonToken;
  3845. // An empty {@link Pair} which is used as the default value of
  3846. // {@link //source} for tokens that do not have a source.
  3847. CommonToken.EMPTY_SOURCE = [ null, null ];
  3848. // Constructs a new {@link CommonToken} as a copy of another {@link Token}.
  3849. //
  3850. // <p>
  3851. // If {@code oldToken} is also a {@link CommonToken} instance, the newly
  3852. // constructed token will share a reference to the {@link //text} field and
  3853. // the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will
  3854. // be assigned the result of calling {@link //getText}, and {@link //source}
  3855. // will be constructed from the result of {@link Token//getTokenSource} and
  3856. // {@link Token//getInputStream}.</p>
  3857. //
  3858. // @param oldToken The token to copy.
  3859. //
  3860. CommonToken.prototype.clone = function() {
  3861. var t = new CommonToken(this.source, this.type, this.channel, this.start,
  3862. this.stop);
  3863. t.tokenIndex = this.tokenIndex;
  3864. t.line = this.line;
  3865. t.column = this.column;
  3866. t.text = this.text;
  3867. return t;
  3868. };
  3869. Object.defineProperty(CommonToken.prototype, "text", {
  3870. get : function() {
  3871. if (this._text !== null) {
  3872. return this._text;
  3873. }
  3874. var input = this.getInputStream();
  3875. if (input === null) {
  3876. return null;
  3877. }
  3878. var n = input.size;
  3879. if (this.start < n && this.stop < n) {
  3880. return input.getText(this.start, this.stop);
  3881. } else {
  3882. return "<EOF>";
  3883. }
  3884. },
  3885. set : function(text) {
  3886. this._text = text;
  3887. }
  3888. });
  3889. CommonToken.prototype.toString = function() {
  3890. var txt = this.text;
  3891. if (txt !== null) {
  3892. txt = txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
  3893. } else {
  3894. txt = "<no text>";
  3895. }
  3896. return "[@" + this.tokenIndex + "," + this.start + ":" + this.stop + "='" +
  3897. txt + "',<" + this.type + ">" +
  3898. (this.channel > 0 ? ",channel=" + this.channel : "") + "," +
  3899. this.line + ":" + this.column + "]";
  3900. };
  3901. exports.Token = Token;
  3902. exports.CommonToken = CommonToken;
  3903. /***/ }),
  3904. /***/ "./node_modules/antlr4/Utils.js":
  3905. /*!**************************************!*\
  3906. !*** ./node_modules/antlr4/Utils.js ***!
  3907. \**************************************/
  3908. /*! no static exports found */
  3909. /***/ (function(module, exports) {
  3910. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  3911. * Use of this file is governed by the BSD 3-clause license that
  3912. * can be found in the LICENSE.txt file in the project root.
  3913. */
  3914. function arrayToString(a) {
  3915. return "[" + a.join(", ") + "]";
  3916. }
  3917. String.prototype.seed = String.prototype.seed || Math.round(Math.random() * Math.pow(2, 32));
  3918. String.prototype.hashCode = function () {
  3919. var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i,
  3920. key = this.toString();
  3921. remainder = key.length & 3; // key.length % 4
  3922. bytes = key.length - remainder;
  3923. h1 = String.prototype.seed;
  3924. c1 = 0xcc9e2d51;
  3925. c2 = 0x1b873593;
  3926. i = 0;
  3927. while (i < bytes) {
  3928. k1 =
  3929. ((key.charCodeAt(i) & 0xff)) |
  3930. ((key.charCodeAt(++i) & 0xff) << 8) |
  3931. ((key.charCodeAt(++i) & 0xff) << 16) |
  3932. ((key.charCodeAt(++i) & 0xff) << 24);
  3933. ++i;
  3934. k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
  3935. k1 = (k1 << 15) | (k1 >>> 17);
  3936. k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
  3937. h1 ^= k1;
  3938. h1 = (h1 << 13) | (h1 >>> 19);
  3939. h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
  3940. h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
  3941. }
  3942. k1 = 0;
  3943. switch (remainder) {
  3944. case 3:
  3945. k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
  3946. case 2:
  3947. k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
  3948. case 1:
  3949. k1 ^= (key.charCodeAt(i) & 0xff);
  3950. k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
  3951. k1 = (k1 << 15) | (k1 >>> 17);
  3952. k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
  3953. h1 ^= k1;
  3954. }
  3955. h1 ^= key.length;
  3956. h1 ^= h1 >>> 16;
  3957. h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
  3958. h1 ^= h1 >>> 13;
  3959. h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
  3960. h1 ^= h1 >>> 16;
  3961. return h1 >>> 0;
  3962. };
  3963. function standardEqualsFunction(a, b) {
  3964. return a.equals(b);
  3965. }
  3966. function standardHashCodeFunction(a) {
  3967. return a.hashCode();
  3968. }
  3969. function Set(hashFunction, equalsFunction) {
  3970. this.data = {};
  3971. this.hashFunction = hashFunction || standardHashCodeFunction;
  3972. this.equalsFunction = equalsFunction || standardEqualsFunction;
  3973. return this;
  3974. }
  3975. Object.defineProperty(Set.prototype, "length", {
  3976. get: function () {
  3977. var l = 0;
  3978. for (var key in this.data) {
  3979. if (key.indexOf("hash_") === 0) {
  3980. l = l + this.data[key].length;
  3981. }
  3982. }
  3983. return l;
  3984. }
  3985. });
  3986. Set.prototype.add = function (value) {
  3987. var hash = this.hashFunction(value);
  3988. var key = "hash_" + hash;
  3989. if (key in this.data) {
  3990. var values = this.data[key];
  3991. for (var i = 0; i < values.length; i++) {
  3992. if (this.equalsFunction(value, values[i])) {
  3993. return values[i];
  3994. }
  3995. }
  3996. values.push(value);
  3997. return value;
  3998. } else {
  3999. this.data[key] = [value];
  4000. return value;
  4001. }
  4002. };
  4003. Set.prototype.contains = function (value) {
  4004. return this.get(value) != null;
  4005. };
  4006. Set.prototype.get = function (value) {
  4007. var hash = this.hashFunction(value);
  4008. var key = "hash_" + hash;
  4009. if (key in this.data) {
  4010. var values = this.data[key];
  4011. for (var i = 0; i < values.length; i++) {
  4012. if (this.equalsFunction(value, values[i])) {
  4013. return values[i];
  4014. }
  4015. }
  4016. }
  4017. return null;
  4018. };
  4019. Set.prototype.values = function () {
  4020. var l = [];
  4021. for (var key in this.data) {
  4022. if (key.indexOf("hash_") === 0) {
  4023. l = l.concat(this.data[key]);
  4024. }
  4025. }
  4026. return l;
  4027. };
  4028. Set.prototype.toString = function () {
  4029. return arrayToString(this.values());
  4030. };
  4031. function BitSet() {
  4032. this.data = [];
  4033. return this;
  4034. }
  4035. BitSet.prototype.add = function (value) {
  4036. this.data[value] = true;
  4037. };
  4038. BitSet.prototype.or = function (set) {
  4039. var bits = this;
  4040. Object.keys(set.data).map(function (alt) {
  4041. bits.add(alt);
  4042. });
  4043. };
  4044. BitSet.prototype.remove = function (value) {
  4045. delete this.data[value];
  4046. };
  4047. BitSet.prototype.contains = function (value) {
  4048. return this.data[value] === true;
  4049. };
  4050. BitSet.prototype.values = function () {
  4051. return Object.keys(this.data);
  4052. };
  4053. BitSet.prototype.minValue = function () {
  4054. return Math.min.apply(null, this.values());
  4055. };
  4056. BitSet.prototype.hashCode = function () {
  4057. var hash = new Hash();
  4058. hash.update(this.values());
  4059. return hash.finish();
  4060. };
  4061. BitSet.prototype.equals = function (other) {
  4062. if (!(other instanceof BitSet)) {
  4063. return false;
  4064. }
  4065. return this.hashCode() === other.hashCode();
  4066. };
  4067. Object.defineProperty(BitSet.prototype, "length", {
  4068. get: function () {
  4069. return this.values().length;
  4070. }
  4071. });
  4072. BitSet.prototype.toString = function () {
  4073. return "{" + this.values().join(", ") + "}";
  4074. };
  4075. function Map(hashFunction, equalsFunction) {
  4076. this.data = {};
  4077. this.hashFunction = hashFunction || standardHashCodeFunction;
  4078. this.equalsFunction = equalsFunction || standardEqualsFunction;
  4079. return this;
  4080. }
  4081. Object.defineProperty(Map.prototype, "length", {
  4082. get: function () {
  4083. var l = 0;
  4084. for (var hashKey in this.data) {
  4085. if (hashKey.indexOf("hash_") === 0) {
  4086. l = l + this.data[hashKey].length;
  4087. }
  4088. }
  4089. return l;
  4090. }
  4091. });
  4092. Map.prototype.put = function (key, value) {
  4093. var hashKey = "hash_" + this.hashFunction(key);
  4094. if (hashKey in this.data) {
  4095. var entries = this.data[hashKey];
  4096. for (var i = 0; i < entries.length; i++) {
  4097. var entry = entries[i];
  4098. if (this.equalsFunction(key, entry.key)) {
  4099. var oldValue = entry.value;
  4100. entry.value = value;
  4101. return oldValue;
  4102. }
  4103. }
  4104. entries.push({key:key, value:value});
  4105. return value;
  4106. } else {
  4107. this.data[hashKey] = [{key:key, value:value}];
  4108. return value;
  4109. }
  4110. };
  4111. Map.prototype.containsKey = function (key) {
  4112. var hashKey = "hash_" + this.hashFunction(key);
  4113. if(hashKey in this.data) {
  4114. var entries = this.data[hashKey];
  4115. for (var i = 0; i < entries.length; i++) {
  4116. var entry = entries[i];
  4117. if (this.equalsFunction(key, entry.key))
  4118. return true;
  4119. }
  4120. }
  4121. return false;
  4122. };
  4123. Map.prototype.get = function (key) {
  4124. var hashKey = "hash_" + this.hashFunction(key);
  4125. if(hashKey in this.data) {
  4126. var entries = this.data[hashKey];
  4127. for (var i = 0; i < entries.length; i++) {
  4128. var entry = entries[i];
  4129. if (this.equalsFunction(key, entry.key))
  4130. return entry.value;
  4131. }
  4132. }
  4133. return null;
  4134. };
  4135. Map.prototype.entries = function () {
  4136. var l = [];
  4137. for (var key in this.data) {
  4138. if (key.indexOf("hash_") === 0) {
  4139. l = l.concat(this.data[key]);
  4140. }
  4141. }
  4142. return l;
  4143. };
  4144. Map.prototype.getKeys = function () {
  4145. return this.entries().map(function(e) {
  4146. return e.key;
  4147. });
  4148. };
  4149. Map.prototype.getValues = function () {
  4150. return this.entries().map(function(e) {
  4151. return e.value;
  4152. });
  4153. };
  4154. Map.prototype.toString = function () {
  4155. var ss = this.entries().map(function(entry) {
  4156. return '{' + entry.key + ':' + entry.value + '}';
  4157. });
  4158. return '[' + ss.join(", ") + ']';
  4159. };
  4160. function AltDict() {
  4161. this.data = {};
  4162. return this;
  4163. }
  4164. AltDict.prototype.get = function (key) {
  4165. key = "k-" + key;
  4166. if (key in this.data) {
  4167. return this.data[key];
  4168. } else {
  4169. return null;
  4170. }
  4171. };
  4172. AltDict.prototype.put = function (key, value) {
  4173. key = "k-" + key;
  4174. this.data[key] = value;
  4175. };
  4176. AltDict.prototype.values = function () {
  4177. var data = this.data;
  4178. var keys = Object.keys(this.data);
  4179. return keys.map(function (key) {
  4180. return data[key];
  4181. });
  4182. };
  4183. function DoubleDict(defaultMapCtor) {
  4184. this.defaultMapCtor = defaultMapCtor || Map;
  4185. this.cacheMap = new this.defaultMapCtor();
  4186. return this;
  4187. }
  4188. function Hash() {
  4189. this.count = 0;
  4190. this.hash = 0;
  4191. return this;
  4192. }
  4193. Hash.prototype.update = function () {
  4194. for(var i=0;i<arguments.length;i++) {
  4195. var value = arguments[i];
  4196. if (value == null)
  4197. continue;
  4198. if(Array.isArray(value))
  4199. this.update.apply(this, value);
  4200. else {
  4201. var k = 0;
  4202. switch (typeof(value)) {
  4203. case 'undefined':
  4204. case 'function':
  4205. continue;
  4206. case 'number':
  4207. case 'boolean':
  4208. k = value;
  4209. break;
  4210. case 'string':
  4211. k = value.hashCode();
  4212. break;
  4213. default:
  4214. if(value.updateHashCode)
  4215. value.updateHashCode(this);
  4216. else
  4217. console.log("No updateHashCode for " + value.toString())
  4218. continue;
  4219. }
  4220. k = k * 0xCC9E2D51;
  4221. k = (k << 15) | (k >>> (32 - 15));
  4222. k = k * 0x1B873593;
  4223. this.count = this.count + 1;
  4224. var hash = this.hash ^ k;
  4225. hash = (hash << 13) | (hash >>> (32 - 13));
  4226. hash = hash * 5 + 0xE6546B64;
  4227. this.hash = hash;
  4228. }
  4229. }
  4230. };
  4231. Hash.prototype.finish = function () {
  4232. var hash = this.hash ^ (this.count * 4);
  4233. hash = hash ^ (hash >>> 16);
  4234. hash = hash * 0x85EBCA6B;
  4235. hash = hash ^ (hash >>> 13);
  4236. hash = hash * 0xC2B2AE35;
  4237. hash = hash ^ (hash >>> 16);
  4238. return hash;
  4239. };
  4240. function hashStuff() {
  4241. var hash = new Hash();
  4242. hash.update.apply(hash, arguments);
  4243. return hash.finish();
  4244. }
  4245. DoubleDict.prototype.get = function (a, b) {
  4246. var d = this.cacheMap.get(a) || null;
  4247. return d === null ? null : (d.get(b) || null);
  4248. };
  4249. DoubleDict.prototype.set = function (a, b, o) {
  4250. var d = this.cacheMap.get(a) || null;
  4251. if (d === null) {
  4252. d = new this.defaultMapCtor();
  4253. this.cacheMap.put(a, d);
  4254. }
  4255. d.put(b, o);
  4256. };
  4257. function escapeWhitespace(s, escapeSpaces) {
  4258. s = s.replace(/\t/g, "\\t")
  4259. .replace(/\n/g, "\\n")
  4260. .replace(/\r/g, "\\r");
  4261. if (escapeSpaces) {
  4262. s = s.replace(/ /g, "\u00B7");
  4263. }
  4264. return s;
  4265. }
  4266. function titleCase(str) {
  4267. return str.replace(/\w\S*/g, function (txt) {
  4268. return txt.charAt(0).toUpperCase() + txt.substr(1);
  4269. });
  4270. };
  4271. function equalArrays(a, b)
  4272. {
  4273. if (!Array.isArray(a) || !Array.isArray(b))
  4274. return false;
  4275. if (a == b)
  4276. return true;
  4277. if (a.length != b.length)
  4278. return false;
  4279. for (var i = 0; i < a.length; i++) {
  4280. if (a[i] == b[i])
  4281. continue;
  4282. if (!a[i].equals(b[i]))
  4283. return false;
  4284. }
  4285. return true;
  4286. };
  4287. exports.Hash = Hash;
  4288. exports.Set = Set;
  4289. exports.Map = Map;
  4290. exports.BitSet = BitSet;
  4291. exports.AltDict = AltDict;
  4292. exports.DoubleDict = DoubleDict;
  4293. exports.hashStuff = hashStuff;
  4294. exports.escapeWhitespace = escapeWhitespace;
  4295. exports.arrayToString = arrayToString;
  4296. exports.titleCase = titleCase;
  4297. exports.equalArrays = equalArrays;
  4298. /***/ }),
  4299. /***/ "./node_modules/antlr4/atn/ATN.js":
  4300. /*!****************************************!*\
  4301. !*** ./node_modules/antlr4/atn/ATN.js ***!
  4302. \****************************************/
  4303. /*! no static exports found */
  4304. /***/ (function(module, exports, __webpack_require__) {
  4305. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  4306. * Use of this file is governed by the BSD 3-clause license that
  4307. * can be found in the LICENSE.txt file in the project root.
  4308. */
  4309. var LL1Analyzer = __webpack_require__(/*! ./../LL1Analyzer */ "./node_modules/antlr4/LL1Analyzer.js").LL1Analyzer;
  4310. var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  4311. function ATN(grammarType , maxTokenType) {
  4312. // Used for runtime deserialization of ATNs from strings///
  4313. // The type of the ATN.
  4314. this.grammarType = grammarType;
  4315. // The maximum value for any symbol recognized by a transition in the ATN.
  4316. this.maxTokenType = maxTokenType;
  4317. this.states = [];
  4318. // Each subrule/rule is a decision point and we must track them so we
  4319. // can go back later and build DFA predictors for them. This includes
  4320. // all the rules, subrules, optional blocks, ()+, ()* etc...
  4321. this.decisionToState = [];
  4322. // Maps from rule index to starting state number.
  4323. this.ruleToStartState = [];
  4324. // Maps from rule index to stop state number.
  4325. this.ruleToStopState = null;
  4326. this.modeNameToStartState = {};
  4327. // For lexer ATNs, this maps the rule index to the resulting token type.
  4328. // For parser ATNs, this maps the rule index to the generated bypass token
  4329. // type if the
  4330. // {@link ATNDeserializationOptions//isGenerateRuleBypassTransitions}
  4331. // deserialization option was specified; otherwise, this is {@code null}.
  4332. this.ruleToTokenType = null;
  4333. // For lexer ATNs, this is an array of {@link LexerAction} objects which may
  4334. // be referenced by action transitions in the ATN.
  4335. this.lexerActions = null;
  4336. this.modeToStartState = [];
  4337. return this;
  4338. }
  4339. // Compute the set of valid tokens that can occur starting in state {@code s}.
  4340. // If {@code ctx} is null, the set of tokens will not include what can follow
  4341. // the rule surrounding {@code s}. In other words, the set will be
  4342. // restricted to tokens reachable staying within {@code s}'s rule.
  4343. ATN.prototype.nextTokensInContext = function(s, ctx) {
  4344. var anal = new LL1Analyzer(this);
  4345. return anal.LOOK(s, null, ctx);
  4346. };
  4347. // Compute the set of valid tokens that can occur starting in {@code s} and
  4348. // staying in same rule. {@link Token//EPSILON} is in set if we reach end of
  4349. // rule.
  4350. ATN.prototype.nextTokensNoContext = function(s) {
  4351. if (s.nextTokenWithinRule !== null ) {
  4352. return s.nextTokenWithinRule;
  4353. }
  4354. s.nextTokenWithinRule = this.nextTokensInContext(s, null);
  4355. s.nextTokenWithinRule.readOnly = true;
  4356. return s.nextTokenWithinRule;
  4357. };
  4358. ATN.prototype.nextTokens = function(s, ctx) {
  4359. if ( ctx===undefined ) {
  4360. return this.nextTokensNoContext(s);
  4361. } else {
  4362. return this.nextTokensInContext(s, ctx);
  4363. }
  4364. };
  4365. ATN.prototype.addState = function( state) {
  4366. if ( state !== null ) {
  4367. state.atn = this;
  4368. state.stateNumber = this.states.length;
  4369. }
  4370. this.states.push(state);
  4371. };
  4372. ATN.prototype.removeState = function( state) {
  4373. this.states[state.stateNumber] = null; // just free mem, don't shift states in list
  4374. };
  4375. ATN.prototype.defineDecisionState = function( s) {
  4376. this.decisionToState.push(s);
  4377. s.decision = this.decisionToState.length-1;
  4378. return s.decision;
  4379. };
  4380. ATN.prototype.getDecisionState = function( decision) {
  4381. if (this.decisionToState.length===0) {
  4382. return null;
  4383. } else {
  4384. return this.decisionToState[decision];
  4385. }
  4386. };
  4387. // Computes the set of input symbols which could follow ATN state number
  4388. // {@code stateNumber} in the specified full {@code context}. This method
  4389. // considers the complete parser context, but does not evaluate semantic
  4390. // predicates (i.e. all predicates encountered during the calculation are
  4391. // assumed true). If a path in the ATN exists from the starting state to the
  4392. // {@link RuleStopState} of the outermost context without matching any
  4393. // symbols, {@link Token//EOF} is added to the returned set.
  4394. //
  4395. // <p>If {@code context} is {@code null}, it is treated as
  4396. // {@link ParserRuleContext//EMPTY}.</p>
  4397. //
  4398. // @param stateNumber the ATN state number
  4399. // @param context the full parse context
  4400. // @return The set of potentially valid input symbols which could follow the
  4401. // specified state in the specified context.
  4402. // @throws IllegalArgumentException if the ATN does not contain a state with
  4403. // number {@code stateNumber}
  4404. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  4405. ATN.prototype.getExpectedTokens = function( stateNumber, ctx ) {
  4406. if ( stateNumber < 0 || stateNumber >= this.states.length ) {
  4407. throw("Invalid state number.");
  4408. }
  4409. var s = this.states[stateNumber];
  4410. var following = this.nextTokens(s);
  4411. if (!following.contains(Token.EPSILON)) {
  4412. return following;
  4413. }
  4414. var expected = new IntervalSet();
  4415. expected.addSet(following);
  4416. expected.removeOne(Token.EPSILON);
  4417. while (ctx !== null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) {
  4418. var invokingState = this.states[ctx.invokingState];
  4419. var rt = invokingState.transitions[0];
  4420. following = this.nextTokens(rt.followState);
  4421. expected.addSet(following);
  4422. expected.removeOne(Token.EPSILON);
  4423. ctx = ctx.parentCtx;
  4424. }
  4425. if (following.contains(Token.EPSILON)) {
  4426. expected.addOne(Token.EOF);
  4427. }
  4428. return expected;
  4429. };
  4430. ATN.INVALID_ALT_NUMBER = 0;
  4431. exports.ATN = ATN;
  4432. /***/ }),
  4433. /***/ "./node_modules/antlr4/atn/ATNConfig.js":
  4434. /*!**********************************************!*\
  4435. !*** ./node_modules/antlr4/atn/ATNConfig.js ***!
  4436. \**********************************************/
  4437. /*! no static exports found */
  4438. /***/ (function(module, exports, __webpack_require__) {
  4439. //
  4440. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  4441. * Use of this file is governed by the BSD 3-clause license that
  4442. * can be found in the LICENSE.txt file in the project root.
  4443. */
  4444. ///
  4445. // A tuple: (ATN state, predicted alt, syntactic, semantic context).
  4446. // The syntactic context is a graph-structured stack node whose
  4447. // path(s) to the root is the rule invocation(s)
  4448. // chain used to arrive at the state. The semantic context is
  4449. // the tree of semantic predicates encountered before reaching
  4450. // an ATN state.
  4451. ///
  4452. var DecisionState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").DecisionState;
  4453. var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
  4454. var Hash = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").Hash;
  4455. function checkParams(params, isCfg) {
  4456. if(params===null) {
  4457. var result = { state:null, alt:null, context:null, semanticContext:null };
  4458. if(isCfg) {
  4459. result.reachesIntoOuterContext = 0;
  4460. }
  4461. return result;
  4462. } else {
  4463. var props = {};
  4464. props.state = params.state || null;
  4465. props.alt = (params.alt === undefined) ? null : params.alt;
  4466. props.context = params.context || null;
  4467. props.semanticContext = params.semanticContext || null;
  4468. if(isCfg) {
  4469. props.reachesIntoOuterContext = params.reachesIntoOuterContext || 0;
  4470. props.precedenceFilterSuppressed = params.precedenceFilterSuppressed || false;
  4471. }
  4472. return props;
  4473. }
  4474. }
  4475. function ATNConfig(params, config) {
  4476. this.checkContext(params, config);
  4477. params = checkParams(params);
  4478. config = checkParams(config, true);
  4479. // The ATN state associated with this configuration///
  4480. this.state = params.state!==null ? params.state : config.state;
  4481. // What alt (or lexer rule) is predicted by this configuration///
  4482. this.alt = params.alt!==null ? params.alt : config.alt;
  4483. // The stack of invoking states leading to the rule/states associated
  4484. // with this config. We track only those contexts pushed during
  4485. // execution of the ATN simulator.
  4486. this.context = params.context!==null ? params.context : config.context;
  4487. this.semanticContext = params.semanticContext!==null ? params.semanticContext :
  4488. (config.semanticContext!==null ? config.semanticContext : SemanticContext.NONE);
  4489. // We cannot execute predicates dependent upon local context unless
  4490. // we know for sure we are in the correct context. Because there is
  4491. // no way to do this efficiently, we simply cannot evaluate
  4492. // dependent predicates unless we are in the rule that initially
  4493. // invokes the ATN simulator.
  4494. //
  4495. // closure() tracks the depth of how far we dip into the
  4496. // outer context: depth &gt; 0. Note that it may not be totally
  4497. // accurate depth since I don't ever decrement. TODO: make it a boolean then
  4498. this.reachesIntoOuterContext = config.reachesIntoOuterContext;
  4499. this.precedenceFilterSuppressed = config.precedenceFilterSuppressed;
  4500. return this;
  4501. }
  4502. ATNConfig.prototype.checkContext = function(params, config) {
  4503. if((params.context===null || params.context===undefined) &&
  4504. (config===null || config.context===null || config.context===undefined)) {
  4505. this.context = null;
  4506. }
  4507. };
  4508. ATNConfig.prototype.hashCode = function() {
  4509. var hash = new Hash();
  4510. this.updateHashCode(hash);
  4511. return hash.finish();
  4512. };
  4513. ATNConfig.prototype.updateHashCode = function(hash) {
  4514. hash.update(this.state.stateNumber, this.alt, this.context, this.semanticContext);
  4515. };
  4516. // An ATN configuration is equal to another if both have
  4517. // the same state, they predict the same alternative, and
  4518. // syntactic/semantic contexts are the same.
  4519. ATNConfig.prototype.equals = function(other) {
  4520. if (this === other) {
  4521. return true;
  4522. } else if (! (other instanceof ATNConfig)) {
  4523. return false;
  4524. } else {
  4525. return this.state.stateNumber===other.state.stateNumber &&
  4526. this.alt===other.alt &&
  4527. (this.context===null ? other.context===null : this.context.equals(other.context)) &&
  4528. this.semanticContext.equals(other.semanticContext) &&
  4529. this.precedenceFilterSuppressed===other.precedenceFilterSuppressed;
  4530. }
  4531. };
  4532. ATNConfig.prototype.hashCodeForConfigSet = function() {
  4533. var hash = new Hash();
  4534. hash.update(this.state.stateNumber, this.alt, this.semanticContext);
  4535. return hash.finish();
  4536. };
  4537. ATNConfig.prototype.equalsForConfigSet = function(other) {
  4538. if (this === other) {
  4539. return true;
  4540. } else if (! (other instanceof ATNConfig)) {
  4541. return false;
  4542. } else {
  4543. return this.state.stateNumber===other.state.stateNumber &&
  4544. this.alt===other.alt &&
  4545. this.semanticContext.equals(other.semanticContext);
  4546. }
  4547. };
  4548. ATNConfig.prototype.toString = function() {
  4549. return "(" + this.state + "," + this.alt +
  4550. (this.context!==null ? ",[" + this.context.toString() + "]" : "") +
  4551. (this.semanticContext !== SemanticContext.NONE ?
  4552. ("," + this.semanticContext.toString())
  4553. : "") +
  4554. (this.reachesIntoOuterContext>0 ?
  4555. (",up=" + this.reachesIntoOuterContext)
  4556. : "") + ")";
  4557. };
  4558. function LexerATNConfig(params, config) {
  4559. ATNConfig.call(this, params, config);
  4560. // This is the backing field for {@link //getLexerActionExecutor}.
  4561. var lexerActionExecutor = params.lexerActionExecutor || null;
  4562. this.lexerActionExecutor = lexerActionExecutor || (config!==null ? config.lexerActionExecutor : null);
  4563. this.passedThroughNonGreedyDecision = config!==null ? this.checkNonGreedyDecision(config, this.state) : false;
  4564. return this;
  4565. }
  4566. LexerATNConfig.prototype = Object.create(ATNConfig.prototype);
  4567. LexerATNConfig.prototype.constructor = LexerATNConfig;
  4568. LexerATNConfig.prototype.updateHashCode = function(hash) {
  4569. hash.update(this.state.stateNumber, this.alt, this.context, this.semanticContext, this.passedThroughNonGreedyDecision, this.lexerActionExecutor);
  4570. };
  4571. LexerATNConfig.prototype.equals = function(other) {
  4572. return this === other ||
  4573. (other instanceof LexerATNConfig &&
  4574. this.passedThroughNonGreedyDecision == other.passedThroughNonGreedyDecision &&
  4575. (this.lexerActionExecutor ? this.lexerActionExecutor.equals(other.lexerActionExecutor) : !other.lexerActionExecutor) &&
  4576. ATNConfig.prototype.equals.call(this, other));
  4577. };
  4578. LexerATNConfig.prototype.hashCodeForConfigSet = LexerATNConfig.prototype.hashCode;
  4579. LexerATNConfig.prototype.equalsForConfigSet = LexerATNConfig.prototype.equals;
  4580. LexerATNConfig.prototype.checkNonGreedyDecision = function(source, target) {
  4581. return source.passedThroughNonGreedyDecision ||
  4582. (target instanceof DecisionState) && target.nonGreedy;
  4583. };
  4584. exports.ATNConfig = ATNConfig;
  4585. exports.LexerATNConfig = LexerATNConfig;
  4586. /***/ }),
  4587. /***/ "./node_modules/antlr4/atn/ATNConfigSet.js":
  4588. /*!*************************************************!*\
  4589. !*** ./node_modules/antlr4/atn/ATNConfigSet.js ***!
  4590. \*************************************************/
  4591. /*! no static exports found */
  4592. /***/ (function(module, exports, __webpack_require__) {
  4593. //
  4594. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  4595. * Use of this file is governed by the BSD 3-clause license that
  4596. * can be found in the LICENSE.txt file in the project root.
  4597. */
  4598. //
  4599. // Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track
  4600. // info about the set, with support for combining similar configurations using a
  4601. // graph-structured stack.
  4602. ///
  4603. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  4604. var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
  4605. var Hash = Utils.Hash;
  4606. var Set = Utils.Set;
  4607. var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
  4608. var merge = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").merge;
  4609. function hashATNConfig(c) {
  4610. return c.hashCodeForConfigSet();
  4611. }
  4612. function equalATNConfigs(a, b) {
  4613. if ( a===b ) {
  4614. return true;
  4615. } else if ( a===null || b===null ) {
  4616. return false;
  4617. } else
  4618. return a.equalsForConfigSet(b);
  4619. }
  4620. function ATNConfigSet(fullCtx) {
  4621. //
  4622. // The reason that we need this is because we don't want the hash map to use
  4623. // the standard hash code and equals. We need all configurations with the
  4624. // same
  4625. // {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively
  4626. // doubles
  4627. // the number of objects associated with ATNConfigs. The other solution is
  4628. // to
  4629. // use a hash table that lets us specify the equals/hashcode operation.
  4630. // All configs but hashed by (s, i, _, pi) not including context. Wiped out
  4631. // when we go readonly as this set becomes a DFA state.
  4632. this.configLookup = new Set(hashATNConfig, equalATNConfigs);
  4633. // Indicates that this configuration set is part of a full context
  4634. // LL prediction. It will be used to determine how to merge $. With SLL
  4635. // it's a wildcard whereas it is not for LL context merge.
  4636. this.fullCtx = fullCtx === undefined ? true : fullCtx;
  4637. // Indicates that the set of configurations is read-only. Do not
  4638. // allow any code to manipulate the set; DFA states will point at
  4639. // the sets and they must not change. This does not protect the other
  4640. // fields; in particular, conflictingAlts is set after
  4641. // we've made this readonly.
  4642. this.readOnly = false;
  4643. // Track the elements as they are added to the set; supports get(i)///
  4644. this.configs = [];
  4645. // TODO: these fields make me pretty uncomfortable but nice to pack up info
  4646. // together, saves recomputation
  4647. // TODO: can we track conflicts as they are added to save scanning configs
  4648. // later?
  4649. this.uniqueAlt = 0;
  4650. this.conflictingAlts = null;
  4651. // Used in parser and lexer. In lexer, it indicates we hit a pred
  4652. // while computing a closure operation. Don't make a DFA state from this.
  4653. this.hasSemanticContext = false;
  4654. this.dipsIntoOuterContext = false;
  4655. this.cachedHashCode = -1;
  4656. return this;
  4657. }
  4658. // Adding a new config means merging contexts with existing configs for
  4659. // {@code (s, i, pi, _)}, where {@code s} is the
  4660. // {@link ATNConfig//state}, {@code i} is the {@link ATNConfig//alt}, and
  4661. // {@code pi} is the {@link ATNConfig//semanticContext}. We use
  4662. // {@code (s,i,pi)} as key.
  4663. //
  4664. // <p>This method updates {@link //dipsIntoOuterContext} and
  4665. // {@link //hasSemanticContext} when necessary.</p>
  4666. // /
  4667. ATNConfigSet.prototype.add = function(config, mergeCache) {
  4668. if (mergeCache === undefined) {
  4669. mergeCache = null;
  4670. }
  4671. if (this.readOnly) {
  4672. throw "This set is readonly";
  4673. }
  4674. if (config.semanticContext !== SemanticContext.NONE) {
  4675. this.hasSemanticContext = true;
  4676. }
  4677. if (config.reachesIntoOuterContext > 0) {
  4678. this.dipsIntoOuterContext = true;
  4679. }
  4680. var existing = this.configLookup.add(config);
  4681. if (existing === config) {
  4682. this.cachedHashCode = -1;
  4683. this.configs.push(config); // track order here
  4684. return true;
  4685. }
  4686. // a previous (s,i,pi,_), merge with it and save result
  4687. var rootIsWildcard = !this.fullCtx;
  4688. var merged = merge(existing.context, config.context, rootIsWildcard, mergeCache);
  4689. // no need to check for existing.context, config.context in cache
  4690. // since only way to create new graphs is "call rule" and here. We
  4691. // cache at both places.
  4692. existing.reachesIntoOuterContext = Math.max( existing.reachesIntoOuterContext, config.reachesIntoOuterContext);
  4693. // make sure to preserve the precedence filter suppression during the merge
  4694. if (config.precedenceFilterSuppressed) {
  4695. existing.precedenceFilterSuppressed = true;
  4696. }
  4697. existing.context = merged; // replace context; no need to alt mapping
  4698. return true;
  4699. };
  4700. ATNConfigSet.prototype.getStates = function() {
  4701. var states = new Set();
  4702. for (var i = 0; i < this.configs.length; i++) {
  4703. states.add(this.configs[i].state);
  4704. }
  4705. return states;
  4706. };
  4707. ATNConfigSet.prototype.getPredicates = function() {
  4708. var preds = [];
  4709. for (var i = 0; i < this.configs.length; i++) {
  4710. var c = this.configs[i].semanticContext;
  4711. if (c !== SemanticContext.NONE) {
  4712. preds.push(c.semanticContext);
  4713. }
  4714. }
  4715. return preds;
  4716. };
  4717. Object.defineProperty(ATNConfigSet.prototype, "items", {
  4718. get : function() {
  4719. return this.configs;
  4720. }
  4721. });
  4722. ATNConfigSet.prototype.optimizeConfigs = function(interpreter) {
  4723. if (this.readOnly) {
  4724. throw "This set is readonly";
  4725. }
  4726. if (this.configLookup.length === 0) {
  4727. return;
  4728. }
  4729. for (var i = 0; i < this.configs.length; i++) {
  4730. var config = this.configs[i];
  4731. config.context = interpreter.getCachedContext(config.context);
  4732. }
  4733. };
  4734. ATNConfigSet.prototype.addAll = function(coll) {
  4735. for (var i = 0; i < coll.length; i++) {
  4736. this.add(coll[i]);
  4737. }
  4738. return false;
  4739. };
  4740. ATNConfigSet.prototype.equals = function(other) {
  4741. return this === other ||
  4742. (other instanceof ATNConfigSet &&
  4743. Utils.equalArrays(this.configs, other.configs) &&
  4744. this.fullCtx === other.fullCtx &&
  4745. this.uniqueAlt === other.uniqueAlt &&
  4746. this.conflictingAlts === other.conflictingAlts &&
  4747. this.hasSemanticContext === other.hasSemanticContext &&
  4748. this.dipsIntoOuterContext === other.dipsIntoOuterContext);
  4749. };
  4750. ATNConfigSet.prototype.hashCode = function() {
  4751. var hash = new Hash();
  4752. hash.update(this.configs);
  4753. return hash.finish();
  4754. };
  4755. ATNConfigSet.prototype.updateHashCode = function(hash) {
  4756. if (this.readOnly) {
  4757. if (this.cachedHashCode === -1) {
  4758. this.cachedHashCode = this.hashCode();
  4759. }
  4760. hash.update(this.cachedHashCode);
  4761. } else {
  4762. hash.update(this.hashCode());
  4763. }
  4764. };
  4765. Object.defineProperty(ATNConfigSet.prototype, "length", {
  4766. get : function() {
  4767. return this.configs.length;
  4768. }
  4769. });
  4770. ATNConfigSet.prototype.isEmpty = function() {
  4771. return this.configs.length === 0;
  4772. };
  4773. ATNConfigSet.prototype.contains = function(item) {
  4774. if (this.configLookup === null) {
  4775. throw "This method is not implemented for readonly sets.";
  4776. }
  4777. return this.configLookup.contains(item);
  4778. };
  4779. ATNConfigSet.prototype.containsFast = function(item) {
  4780. if (this.configLookup === null) {
  4781. throw "This method is not implemented for readonly sets.";
  4782. }
  4783. return this.configLookup.containsFast(item);
  4784. };
  4785. ATNConfigSet.prototype.clear = function() {
  4786. if (this.readOnly) {
  4787. throw "This set is readonly";
  4788. }
  4789. this.configs = [];
  4790. this.cachedHashCode = -1;
  4791. this.configLookup = new Set();
  4792. };
  4793. ATNConfigSet.prototype.setReadonly = function(readOnly) {
  4794. this.readOnly = readOnly;
  4795. if (readOnly) {
  4796. this.configLookup = null; // can't mod, no need for lookup cache
  4797. }
  4798. };
  4799. ATNConfigSet.prototype.toString = function() {
  4800. return Utils.arrayToString(this.configs) +
  4801. (this.hasSemanticContext ? ",hasSemanticContext=" + this.hasSemanticContext : "") +
  4802. (this.uniqueAlt !== ATN.INVALID_ALT_NUMBER ? ",uniqueAlt=" + this.uniqueAlt : "") +
  4803. (this.conflictingAlts !== null ? ",conflictingAlts=" + this.conflictingAlts : "") +
  4804. (this.dipsIntoOuterContext ? ",dipsIntoOuterContext" : "");
  4805. };
  4806. function OrderedATNConfigSet() {
  4807. ATNConfigSet.call(this);
  4808. this.configLookup = new Set();
  4809. return this;
  4810. }
  4811. OrderedATNConfigSet.prototype = Object.create(ATNConfigSet.prototype);
  4812. OrderedATNConfigSet.prototype.constructor = OrderedATNConfigSet;
  4813. exports.ATNConfigSet = ATNConfigSet;
  4814. exports.OrderedATNConfigSet = OrderedATNConfigSet;
  4815. /***/ }),
  4816. /***/ "./node_modules/antlr4/atn/ATNDeserializationOptions.js":
  4817. /*!**************************************************************!*\
  4818. !*** ./node_modules/antlr4/atn/ATNDeserializationOptions.js ***!
  4819. \**************************************************************/
  4820. /*! no static exports found */
  4821. /***/ (function(module, exports) {
  4822. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  4823. * Use of this file is governed by the BSD 3-clause license that
  4824. * can be found in the LICENSE.txt file in the project root.
  4825. */
  4826. function ATNDeserializationOptions(copyFrom) {
  4827. if(copyFrom===undefined) {
  4828. copyFrom = null;
  4829. }
  4830. this.readOnly = false;
  4831. this.verifyATN = copyFrom===null ? true : copyFrom.verifyATN;
  4832. this.generateRuleBypassTransitions = copyFrom===null ? false : copyFrom.generateRuleBypassTransitions;
  4833. return this;
  4834. }
  4835. ATNDeserializationOptions.defaultOptions = new ATNDeserializationOptions();
  4836. ATNDeserializationOptions.defaultOptions.readOnly = true;
  4837. // def __setattr__(self, key, value):
  4838. // if key!="readOnly" and self.readOnly:
  4839. // raise Exception("The object is read only.")
  4840. // super(type(self), self).__setattr__(key,value)
  4841. exports.ATNDeserializationOptions = ATNDeserializationOptions;
  4842. /***/ }),
  4843. /***/ "./node_modules/antlr4/atn/ATNDeserializer.js":
  4844. /*!****************************************************!*\
  4845. !*** ./node_modules/antlr4/atn/ATNDeserializer.js ***!
  4846. \****************************************************/
  4847. /*! no static exports found */
  4848. /***/ (function(module, exports, __webpack_require__) {
  4849. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  4850. * Use of this file is governed by the BSD 3-clause license that
  4851. * can be found in the LICENSE.txt file in the project root.
  4852. */
  4853. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  4854. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  4855. var ATNType = __webpack_require__(/*! ./ATNType */ "./node_modules/antlr4/atn/ATNType.js").ATNType;
  4856. var ATNStates = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js");
  4857. var ATNState = ATNStates.ATNState;
  4858. var BasicState = ATNStates.BasicState;
  4859. var DecisionState = ATNStates.DecisionState;
  4860. var BlockStartState = ATNStates.BlockStartState;
  4861. var BlockEndState = ATNStates.BlockEndState;
  4862. var LoopEndState = ATNStates.LoopEndState;
  4863. var RuleStartState = ATNStates.RuleStartState;
  4864. var RuleStopState = ATNStates.RuleStopState;
  4865. var TokensStartState = ATNStates.TokensStartState;
  4866. var PlusLoopbackState = ATNStates.PlusLoopbackState;
  4867. var StarLoopbackState = ATNStates.StarLoopbackState;
  4868. var StarLoopEntryState = ATNStates.StarLoopEntryState;
  4869. var PlusBlockStartState = ATNStates.PlusBlockStartState;
  4870. var StarBlockStartState = ATNStates.StarBlockStartState;
  4871. var BasicBlockStartState = ATNStates.BasicBlockStartState;
  4872. var Transitions = __webpack_require__(/*! ./Transition */ "./node_modules/antlr4/atn/Transition.js");
  4873. var Transition = Transitions.Transition;
  4874. var AtomTransition = Transitions.AtomTransition;
  4875. var SetTransition = Transitions.SetTransition;
  4876. var NotSetTransition = Transitions.NotSetTransition;
  4877. var RuleTransition = Transitions.RuleTransition;
  4878. var RangeTransition = Transitions.RangeTransition;
  4879. var ActionTransition = Transitions.ActionTransition;
  4880. var EpsilonTransition = Transitions.EpsilonTransition;
  4881. var WildcardTransition = Transitions.WildcardTransition;
  4882. var PredicateTransition = Transitions.PredicateTransition;
  4883. var PrecedencePredicateTransition = Transitions.PrecedencePredicateTransition;
  4884. var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  4885. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  4886. var ATNDeserializationOptions = __webpack_require__(/*! ./ATNDeserializationOptions */ "./node_modules/antlr4/atn/ATNDeserializationOptions.js").ATNDeserializationOptions;
  4887. var LexerActions = __webpack_require__(/*! ./LexerAction */ "./node_modules/antlr4/atn/LexerAction.js");
  4888. var LexerActionType = LexerActions.LexerActionType;
  4889. var LexerSkipAction = LexerActions.LexerSkipAction;
  4890. var LexerChannelAction = LexerActions.LexerChannelAction;
  4891. var LexerCustomAction = LexerActions.LexerCustomAction;
  4892. var LexerMoreAction = LexerActions.LexerMoreAction;
  4893. var LexerTypeAction = LexerActions.LexerTypeAction;
  4894. var LexerPushModeAction = LexerActions.LexerPushModeAction;
  4895. var LexerPopModeAction = LexerActions.LexerPopModeAction;
  4896. var LexerModeAction = LexerActions.LexerModeAction;
  4897. // This is the earliest supported serialized UUID.
  4898. // stick to serialized version for now, we don't need a UUID instance
  4899. var BASE_SERIALIZED_UUID = "AADB8D7E-AEEF-4415-AD2B-8204D6CF042E";
  4900. //
  4901. // This UUID indicates the serialized ATN contains two sets of
  4902. // IntervalSets, where the second set's values are encoded as
  4903. // 32-bit integers to support the full Unicode SMP range up to U+10FFFF.
  4904. //
  4905. var ADDED_UNICODE_SMP = "59627784-3BE5-417A-B9EB-8131A7286089";
  4906. // This list contains all of the currently supported UUIDs, ordered by when
  4907. // the feature first appeared in this branch.
  4908. var SUPPORTED_UUIDS = [ BASE_SERIALIZED_UUID, ADDED_UNICODE_SMP ];
  4909. var SERIALIZED_VERSION = 3;
  4910. // This is the current serialized UUID.
  4911. var SERIALIZED_UUID = ADDED_UNICODE_SMP;
  4912. function initArray( length, value) {
  4913. var tmp = [];
  4914. tmp[length-1] = value;
  4915. return tmp.map(function(i) {return value;});
  4916. }
  4917. function ATNDeserializer (options) {
  4918. if ( options=== undefined || options === null ) {
  4919. options = ATNDeserializationOptions.defaultOptions;
  4920. }
  4921. this.deserializationOptions = options;
  4922. this.stateFactories = null;
  4923. this.actionFactories = null;
  4924. return this;
  4925. }
  4926. // Determines if a particular serialized representation of an ATN supports
  4927. // a particular feature, identified by the {@link UUID} used for serializing
  4928. // the ATN at the time the feature was first introduced.
  4929. //
  4930. // @param feature The {@link UUID} marking the first time the feature was
  4931. // supported in the serialized ATN.
  4932. // @param actualUuid The {@link UUID} of the actual serialized ATN which is
  4933. // currently being deserialized.
  4934. // @return {@code true} if the {@code actualUuid} value represents a
  4935. // serialized ATN at or after the feature identified by {@code feature} was
  4936. // introduced; otherwise, {@code false}.
  4937. ATNDeserializer.prototype.isFeatureSupported = function(feature, actualUuid) {
  4938. var idx1 = SUPPORTED_UUIDS.indexOf(feature);
  4939. if (idx1<0) {
  4940. return false;
  4941. }
  4942. var idx2 = SUPPORTED_UUIDS.indexOf(actualUuid);
  4943. return idx2 >= idx1;
  4944. };
  4945. ATNDeserializer.prototype.deserialize = function(data) {
  4946. this.reset(data);
  4947. this.checkVersion();
  4948. this.checkUUID();
  4949. var atn = this.readATN();
  4950. this.readStates(atn);
  4951. this.readRules(atn);
  4952. this.readModes(atn);
  4953. var sets = [];
  4954. // First, deserialize sets with 16-bit arguments <= U+FFFF.
  4955. this.readSets(atn, sets, this.readInt.bind(this));
  4956. // Next, if the ATN was serialized with the Unicode SMP feature,
  4957. // deserialize sets with 32-bit arguments <= U+10FFFF.
  4958. if (this.isFeatureSupported(ADDED_UNICODE_SMP, this.uuid)) {
  4959. this.readSets(atn, sets, this.readInt32.bind(this));
  4960. }
  4961. this.readEdges(atn, sets);
  4962. this.readDecisions(atn);
  4963. this.readLexerActions(atn);
  4964. this.markPrecedenceDecisions(atn);
  4965. this.verifyATN(atn);
  4966. if (this.deserializationOptions.generateRuleBypassTransitions && atn.grammarType === ATNType.PARSER ) {
  4967. this.generateRuleBypassTransitions(atn);
  4968. // re-verify after modification
  4969. this.verifyATN(atn);
  4970. }
  4971. return atn;
  4972. };
  4973. ATNDeserializer.prototype.reset = function(data) {
  4974. var adjust = function(c) {
  4975. var v = c.charCodeAt(0);
  4976. return v>1 ? v-2 : v + 65534;
  4977. };
  4978. var temp = data.split("").map(adjust);
  4979. // don't adjust the first value since that's the version number
  4980. temp[0] = data.charCodeAt(0);
  4981. this.data = temp;
  4982. this.pos = 0;
  4983. };
  4984. ATNDeserializer.prototype.checkVersion = function() {
  4985. var version = this.readInt();
  4986. if ( version !== SERIALIZED_VERSION ) {
  4987. throw ("Could not deserialize ATN with version " + version + " (expected " + SERIALIZED_VERSION + ").");
  4988. }
  4989. };
  4990. ATNDeserializer.prototype.checkUUID = function() {
  4991. var uuid = this.readUUID();
  4992. if (SUPPORTED_UUIDS.indexOf(uuid)<0) {
  4993. throw ("Could not deserialize ATN with UUID: " + uuid +
  4994. " (expected " + SERIALIZED_UUID + " or a legacy UUID).", uuid, SERIALIZED_UUID);
  4995. }
  4996. this.uuid = uuid;
  4997. };
  4998. ATNDeserializer.prototype.readATN = function() {
  4999. var grammarType = this.readInt();
  5000. var maxTokenType = this.readInt();
  5001. return new ATN(grammarType, maxTokenType);
  5002. };
  5003. ATNDeserializer.prototype.readStates = function(atn) {
  5004. var j, pair, stateNumber;
  5005. var loopBackStateNumbers = [];
  5006. var endStateNumbers = [];
  5007. var nstates = this.readInt();
  5008. for(var i=0; i<nstates; i++) {
  5009. var stype = this.readInt();
  5010. // ignore bad type of states
  5011. if (stype===ATNState.INVALID_TYPE) {
  5012. atn.addState(null);
  5013. continue;
  5014. }
  5015. var ruleIndex = this.readInt();
  5016. if (ruleIndex === 0xFFFF) {
  5017. ruleIndex = -1;
  5018. }
  5019. var s = this.stateFactory(stype, ruleIndex);
  5020. if (stype === ATNState.LOOP_END) { // special case
  5021. var loopBackStateNumber = this.readInt();
  5022. loopBackStateNumbers.push([s, loopBackStateNumber]);
  5023. } else if(s instanceof BlockStartState) {
  5024. var endStateNumber = this.readInt();
  5025. endStateNumbers.push([s, endStateNumber]);
  5026. }
  5027. atn.addState(s);
  5028. }
  5029. // delay the assignment of loop back and end states until we know all the
  5030. // state instances have been initialized
  5031. for (j=0; j<loopBackStateNumbers.length; j++) {
  5032. pair = loopBackStateNumbers[j];
  5033. pair[0].loopBackState = atn.states[pair[1]];
  5034. }
  5035. for (j=0; j<endStateNumbers.length; j++) {
  5036. pair = endStateNumbers[j];
  5037. pair[0].endState = atn.states[pair[1]];
  5038. }
  5039. var numNonGreedyStates = this.readInt();
  5040. for (j=0; j<numNonGreedyStates; j++) {
  5041. stateNumber = this.readInt();
  5042. atn.states[stateNumber].nonGreedy = true;
  5043. }
  5044. var numPrecedenceStates = this.readInt();
  5045. for (j=0; j<numPrecedenceStates; j++) {
  5046. stateNumber = this.readInt();
  5047. atn.states[stateNumber].isPrecedenceRule = true;
  5048. }
  5049. };
  5050. ATNDeserializer.prototype.readRules = function(atn) {
  5051. var i;
  5052. var nrules = this.readInt();
  5053. if (atn.grammarType === ATNType.LEXER ) {
  5054. atn.ruleToTokenType = initArray(nrules, 0);
  5055. }
  5056. atn.ruleToStartState = initArray(nrules, 0);
  5057. for (i=0; i<nrules; i++) {
  5058. var s = this.readInt();
  5059. var startState = atn.states[s];
  5060. atn.ruleToStartState[i] = startState;
  5061. if ( atn.grammarType === ATNType.LEXER ) {
  5062. var tokenType = this.readInt();
  5063. if (tokenType === 0xFFFF) {
  5064. tokenType = Token.EOF;
  5065. }
  5066. atn.ruleToTokenType[i] = tokenType;
  5067. }
  5068. }
  5069. atn.ruleToStopState = initArray(nrules, 0);
  5070. for (i=0; i<atn.states.length; i++) {
  5071. var state = atn.states[i];
  5072. if (!(state instanceof RuleStopState)) {
  5073. continue;
  5074. }
  5075. atn.ruleToStopState[state.ruleIndex] = state;
  5076. atn.ruleToStartState[state.ruleIndex].stopState = state;
  5077. }
  5078. };
  5079. ATNDeserializer.prototype.readModes = function(atn) {
  5080. var nmodes = this.readInt();
  5081. for (var i=0; i<nmodes; i++) {
  5082. var s = this.readInt();
  5083. atn.modeToStartState.push(atn.states[s]);
  5084. }
  5085. };
  5086. ATNDeserializer.prototype.readSets = function(atn, sets, readUnicode) {
  5087. var m = this.readInt();
  5088. for (var i=0; i<m; i++) {
  5089. var iset = new IntervalSet();
  5090. sets.push(iset);
  5091. var n = this.readInt();
  5092. var containsEof = this.readInt();
  5093. if (containsEof!==0) {
  5094. iset.addOne(-1);
  5095. }
  5096. for (var j=0; j<n; j++) {
  5097. var i1 = readUnicode();
  5098. var i2 = readUnicode();
  5099. iset.addRange(i1, i2);
  5100. }
  5101. }
  5102. };
  5103. ATNDeserializer.prototype.readEdges = function(atn, sets) {
  5104. var i, j, state, trans, target;
  5105. var nedges = this.readInt();
  5106. for (i=0; i<nedges; i++) {
  5107. var src = this.readInt();
  5108. var trg = this.readInt();
  5109. var ttype = this.readInt();
  5110. var arg1 = this.readInt();
  5111. var arg2 = this.readInt();
  5112. var arg3 = this.readInt();
  5113. trans = this.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets);
  5114. var srcState = atn.states[src];
  5115. srcState.addTransition(trans);
  5116. }
  5117. // edges for rule stop states can be derived, so they aren't serialized
  5118. for (i=0; i<atn.states.length; i++) {
  5119. state = atn.states[i];
  5120. for (j=0; j<state.transitions.length; j++) {
  5121. var t = state.transitions[j];
  5122. if (!(t instanceof RuleTransition)) {
  5123. continue;
  5124. }
  5125. var outermostPrecedenceReturn = -1;
  5126. if (atn.ruleToStartState[t.target.ruleIndex].isPrecedenceRule) {
  5127. if (t.precedence === 0) {
  5128. outermostPrecedenceReturn = t.target.ruleIndex;
  5129. }
  5130. }
  5131. trans = new EpsilonTransition(t.followState, outermostPrecedenceReturn);
  5132. atn.ruleToStopState[t.target.ruleIndex].addTransition(trans);
  5133. }
  5134. }
  5135. for (i=0; i<atn.states.length; i++) {
  5136. state = atn.states[i];
  5137. if (state instanceof BlockStartState) {
  5138. // we need to know the end state to set its start state
  5139. if (state.endState === null) {
  5140. throw ("IllegalState");
  5141. }
  5142. // block end states can only be associated to a single block start
  5143. // state
  5144. if ( state.endState.startState !== null) {
  5145. throw ("IllegalState");
  5146. }
  5147. state.endState.startState = state;
  5148. }
  5149. if (state instanceof PlusLoopbackState) {
  5150. for (j=0; j<state.transitions.length; j++) {
  5151. target = state.transitions[j].target;
  5152. if (target instanceof PlusBlockStartState) {
  5153. target.loopBackState = state;
  5154. }
  5155. }
  5156. } else if (state instanceof StarLoopbackState) {
  5157. for (j=0; j<state.transitions.length; j++) {
  5158. target = state.transitions[j].target;
  5159. if (target instanceof StarLoopEntryState) {
  5160. target.loopBackState = state;
  5161. }
  5162. }
  5163. }
  5164. }
  5165. };
  5166. ATNDeserializer.prototype.readDecisions = function(atn) {
  5167. var ndecisions = this.readInt();
  5168. for (var i=0; i<ndecisions; i++) {
  5169. var s = this.readInt();
  5170. var decState = atn.states[s];
  5171. atn.decisionToState.push(decState);
  5172. decState.decision = i;
  5173. }
  5174. };
  5175. ATNDeserializer.prototype.readLexerActions = function(atn) {
  5176. if (atn.grammarType === ATNType.LEXER) {
  5177. var count = this.readInt();
  5178. atn.lexerActions = initArray(count, null);
  5179. for (var i=0; i<count; i++) {
  5180. var actionType = this.readInt();
  5181. var data1 = this.readInt();
  5182. if (data1 === 0xFFFF) {
  5183. data1 = -1;
  5184. }
  5185. var data2 = this.readInt();
  5186. if (data2 === 0xFFFF) {
  5187. data2 = -1;
  5188. }
  5189. var lexerAction = this.lexerActionFactory(actionType, data1, data2);
  5190. atn.lexerActions[i] = lexerAction;
  5191. }
  5192. }
  5193. };
  5194. ATNDeserializer.prototype.generateRuleBypassTransitions = function(atn) {
  5195. var i;
  5196. var count = atn.ruleToStartState.length;
  5197. for(i=0; i<count; i++) {
  5198. atn.ruleToTokenType[i] = atn.maxTokenType + i + 1;
  5199. }
  5200. for(i=0; i<count; i++) {
  5201. this.generateRuleBypassTransition(atn, i);
  5202. }
  5203. };
  5204. ATNDeserializer.prototype.generateRuleBypassTransition = function(atn, idx) {
  5205. var i, state;
  5206. var bypassStart = new BasicBlockStartState();
  5207. bypassStart.ruleIndex = idx;
  5208. atn.addState(bypassStart);
  5209. var bypassStop = new BlockEndState();
  5210. bypassStop.ruleIndex = idx;
  5211. atn.addState(bypassStop);
  5212. bypassStart.endState = bypassStop;
  5213. atn.defineDecisionState(bypassStart);
  5214. bypassStop.startState = bypassStart;
  5215. var excludeTransition = null;
  5216. var endState = null;
  5217. if (atn.ruleToStartState[idx].isPrecedenceRule) {
  5218. // wrap from the beginning of the rule to the StarLoopEntryState
  5219. endState = null;
  5220. for(i=0; i<atn.states.length; i++) {
  5221. state = atn.states[i];
  5222. if (this.stateIsEndStateFor(state, idx)) {
  5223. endState = state;
  5224. excludeTransition = state.loopBackState.transitions[0];
  5225. break;
  5226. }
  5227. }
  5228. if (excludeTransition === null) {
  5229. throw ("Couldn't identify final state of the precedence rule prefix section.");
  5230. }
  5231. } else {
  5232. endState = atn.ruleToStopState[idx];
  5233. }
  5234. // all non-excluded transitions that currently target end state need to
  5235. // target blockEnd instead
  5236. for(i=0; i<atn.states.length; i++) {
  5237. state = atn.states[i];
  5238. for(var j=0; j<state.transitions.length; j++) {
  5239. var transition = state.transitions[j];
  5240. if (transition === excludeTransition) {
  5241. continue;
  5242. }
  5243. if (transition.target === endState) {
  5244. transition.target = bypassStop;
  5245. }
  5246. }
  5247. }
  5248. // all transitions leaving the rule start state need to leave blockStart
  5249. // instead
  5250. var ruleToStartState = atn.ruleToStartState[idx];
  5251. var count = ruleToStartState.transitions.length;
  5252. while ( count > 0) {
  5253. bypassStart.addTransition(ruleToStartState.transitions[count-1]);
  5254. ruleToStartState.transitions = ruleToStartState.transitions.slice(-1);
  5255. }
  5256. // link the new states
  5257. atn.ruleToStartState[idx].addTransition(new EpsilonTransition(bypassStart));
  5258. bypassStop.addTransition(new EpsilonTransition(endState));
  5259. var matchState = new BasicState();
  5260. atn.addState(matchState);
  5261. matchState.addTransition(new AtomTransition(bypassStop, atn.ruleToTokenType[idx]));
  5262. bypassStart.addTransition(new EpsilonTransition(matchState));
  5263. };
  5264. ATNDeserializer.prototype.stateIsEndStateFor = function(state, idx) {
  5265. if ( state.ruleIndex !== idx) {
  5266. return null;
  5267. }
  5268. if (!( state instanceof StarLoopEntryState)) {
  5269. return null;
  5270. }
  5271. var maybeLoopEndState = state.transitions[state.transitions.length - 1].target;
  5272. if (!( maybeLoopEndState instanceof LoopEndState)) {
  5273. return null;
  5274. }
  5275. if (maybeLoopEndState.epsilonOnlyTransitions &&
  5276. (maybeLoopEndState.transitions[0].target instanceof RuleStopState)) {
  5277. return state;
  5278. } else {
  5279. return null;
  5280. }
  5281. };
  5282. //
  5283. // Analyze the {@link StarLoopEntryState} states in the specified ATN to set
  5284. // the {@link StarLoopEntryState//isPrecedenceDecision} field to the
  5285. // correct value.
  5286. //
  5287. // @param atn The ATN.
  5288. //
  5289. ATNDeserializer.prototype.markPrecedenceDecisions = function(atn) {
  5290. for(var i=0; i<atn.states.length; i++) {
  5291. var state = atn.states[i];
  5292. if (!( state instanceof StarLoopEntryState)) {
  5293. continue;
  5294. }
  5295. // We analyze the ATN to determine if this ATN decision state is the
  5296. // decision for the closure block that determines whether a
  5297. // precedence rule should continue or complete.
  5298. //
  5299. if ( atn.ruleToStartState[state.ruleIndex].isPrecedenceRule) {
  5300. var maybeLoopEndState = state.transitions[state.transitions.length - 1].target;
  5301. if (maybeLoopEndState instanceof LoopEndState) {
  5302. if ( maybeLoopEndState.epsilonOnlyTransitions &&
  5303. (maybeLoopEndState.transitions[0].target instanceof RuleStopState)) {
  5304. state.isPrecedenceDecision = true;
  5305. }
  5306. }
  5307. }
  5308. }
  5309. };
  5310. ATNDeserializer.prototype.verifyATN = function(atn) {
  5311. if (!this.deserializationOptions.verifyATN) {
  5312. return;
  5313. }
  5314. // verify assumptions
  5315. for(var i=0; i<atn.states.length; i++) {
  5316. var state = atn.states[i];
  5317. if (state === null) {
  5318. continue;
  5319. }
  5320. this.checkCondition(state.epsilonOnlyTransitions || state.transitions.length <= 1);
  5321. if (state instanceof PlusBlockStartState) {
  5322. this.checkCondition(state.loopBackState !== null);
  5323. } else if (state instanceof StarLoopEntryState) {
  5324. this.checkCondition(state.loopBackState !== null);
  5325. this.checkCondition(state.transitions.length === 2);
  5326. if (state.transitions[0].target instanceof StarBlockStartState) {
  5327. this.checkCondition(state.transitions[1].target instanceof LoopEndState);
  5328. this.checkCondition(!state.nonGreedy);
  5329. } else if (state.transitions[0].target instanceof LoopEndState) {
  5330. this.checkCondition(state.transitions[1].target instanceof StarBlockStartState);
  5331. this.checkCondition(state.nonGreedy);
  5332. } else {
  5333. throw("IllegalState");
  5334. }
  5335. } else if (state instanceof StarLoopbackState) {
  5336. this.checkCondition(state.transitions.length === 1);
  5337. this.checkCondition(state.transitions[0].target instanceof StarLoopEntryState);
  5338. } else if (state instanceof LoopEndState) {
  5339. this.checkCondition(state.loopBackState !== null);
  5340. } else if (state instanceof RuleStartState) {
  5341. this.checkCondition(state.stopState !== null);
  5342. } else if (state instanceof BlockStartState) {
  5343. this.checkCondition(state.endState !== null);
  5344. } else if (state instanceof BlockEndState) {
  5345. this.checkCondition(state.startState !== null);
  5346. } else if (state instanceof DecisionState) {
  5347. this.checkCondition(state.transitions.length <= 1 || state.decision >= 0);
  5348. } else {
  5349. this.checkCondition(state.transitions.length <= 1 || (state instanceof RuleStopState));
  5350. }
  5351. }
  5352. };
  5353. ATNDeserializer.prototype.checkCondition = function(condition, message) {
  5354. if (!condition) {
  5355. if (message === undefined || message===null) {
  5356. message = "IllegalState";
  5357. }
  5358. throw (message);
  5359. }
  5360. };
  5361. ATNDeserializer.prototype.readInt = function() {
  5362. return this.data[this.pos++];
  5363. };
  5364. ATNDeserializer.prototype.readInt32 = function() {
  5365. var low = this.readInt();
  5366. var high = this.readInt();
  5367. return low | (high << 16);
  5368. };
  5369. ATNDeserializer.prototype.readLong = function() {
  5370. var low = this.readInt32();
  5371. var high = this.readInt32();
  5372. return (low & 0x00000000FFFFFFFF) | (high << 32);
  5373. };
  5374. function createByteToHex() {
  5375. var bth = [];
  5376. for (var i = 0; i < 256; i++) {
  5377. bth[i] = (i + 0x100).toString(16).substr(1).toUpperCase();
  5378. }
  5379. return bth;
  5380. }
  5381. var byteToHex = createByteToHex();
  5382. ATNDeserializer.prototype.readUUID = function() {
  5383. var bb = [];
  5384. for(var i=7;i>=0;i--) {
  5385. var int = this.readInt();
  5386. /* jshint bitwise: false */
  5387. bb[(2*i)+1] = int & 0xFF;
  5388. bb[2*i] = (int >> 8) & 0xFF;
  5389. }
  5390. return byteToHex[bb[0]] + byteToHex[bb[1]] +
  5391. byteToHex[bb[2]] + byteToHex[bb[3]] + '-' +
  5392. byteToHex[bb[4]] + byteToHex[bb[5]] + '-' +
  5393. byteToHex[bb[6]] + byteToHex[bb[7]] + '-' +
  5394. byteToHex[bb[8]] + byteToHex[bb[9]] + '-' +
  5395. byteToHex[bb[10]] + byteToHex[bb[11]] +
  5396. byteToHex[bb[12]] + byteToHex[bb[13]] +
  5397. byteToHex[bb[14]] + byteToHex[bb[15]];
  5398. };
  5399. ATNDeserializer.prototype.edgeFactory = function(atn, type, src, trg, arg1, arg2, arg3, sets) {
  5400. var target = atn.states[trg];
  5401. switch(type) {
  5402. case Transition.EPSILON:
  5403. return new EpsilonTransition(target);
  5404. case Transition.RANGE:
  5405. return arg3 !== 0 ? new RangeTransition(target, Token.EOF, arg2) : new RangeTransition(target, arg1, arg2);
  5406. case Transition.RULE:
  5407. return new RuleTransition(atn.states[arg1], arg2, arg3, target);
  5408. case Transition.PREDICATE:
  5409. return new PredicateTransition(target, arg1, arg2, arg3 !== 0);
  5410. case Transition.PRECEDENCE:
  5411. return new PrecedencePredicateTransition(target, arg1);
  5412. case Transition.ATOM:
  5413. return arg3 !== 0 ? new AtomTransition(target, Token.EOF) : new AtomTransition(target, arg1);
  5414. case Transition.ACTION:
  5415. return new ActionTransition(target, arg1, arg2, arg3 !== 0);
  5416. case Transition.SET:
  5417. return new SetTransition(target, sets[arg1]);
  5418. case Transition.NOT_SET:
  5419. return new NotSetTransition(target, sets[arg1]);
  5420. case Transition.WILDCARD:
  5421. return new WildcardTransition(target);
  5422. default:
  5423. throw "The specified transition type: " + type + " is not valid.";
  5424. }
  5425. };
  5426. ATNDeserializer.prototype.stateFactory = function(type, ruleIndex) {
  5427. if (this.stateFactories === null) {
  5428. var sf = [];
  5429. sf[ATNState.INVALID_TYPE] = null;
  5430. sf[ATNState.BASIC] = function() { return new BasicState(); };
  5431. sf[ATNState.RULE_START] = function() { return new RuleStartState(); };
  5432. sf[ATNState.BLOCK_START] = function() { return new BasicBlockStartState(); };
  5433. sf[ATNState.PLUS_BLOCK_START] = function() { return new PlusBlockStartState(); };
  5434. sf[ATNState.STAR_BLOCK_START] = function() { return new StarBlockStartState(); };
  5435. sf[ATNState.TOKEN_START] = function() { return new TokensStartState(); };
  5436. sf[ATNState.RULE_STOP] = function() { return new RuleStopState(); };
  5437. sf[ATNState.BLOCK_END] = function() { return new BlockEndState(); };
  5438. sf[ATNState.STAR_LOOP_BACK] = function() { return new StarLoopbackState(); };
  5439. sf[ATNState.STAR_LOOP_ENTRY] = function() { return new StarLoopEntryState(); };
  5440. sf[ATNState.PLUS_LOOP_BACK] = function() { return new PlusLoopbackState(); };
  5441. sf[ATNState.LOOP_END] = function() { return new LoopEndState(); };
  5442. this.stateFactories = sf;
  5443. }
  5444. if (type>this.stateFactories.length || this.stateFactories[type] === null) {
  5445. throw("The specified state type " + type + " is not valid.");
  5446. } else {
  5447. var s = this.stateFactories[type]();
  5448. if (s!==null) {
  5449. s.ruleIndex = ruleIndex;
  5450. return s;
  5451. }
  5452. }
  5453. };
  5454. ATNDeserializer.prototype.lexerActionFactory = function(type, data1, data2) {
  5455. if (this.actionFactories === null) {
  5456. var af = [];
  5457. af[LexerActionType.CHANNEL] = function(data1, data2) { return new LexerChannelAction(data1); };
  5458. af[LexerActionType.CUSTOM] = function(data1, data2) { return new LexerCustomAction(data1, data2); };
  5459. af[LexerActionType.MODE] = function(data1, data2) { return new LexerModeAction(data1); };
  5460. af[LexerActionType.MORE] = function(data1, data2) { return LexerMoreAction.INSTANCE; };
  5461. af[LexerActionType.POP_MODE] = function(data1, data2) { return LexerPopModeAction.INSTANCE; };
  5462. af[LexerActionType.PUSH_MODE] = function(data1, data2) { return new LexerPushModeAction(data1); };
  5463. af[LexerActionType.SKIP] = function(data1, data2) { return LexerSkipAction.INSTANCE; };
  5464. af[LexerActionType.TYPE] = function(data1, data2) { return new LexerTypeAction(data1); };
  5465. this.actionFactories = af;
  5466. }
  5467. if (type>this.actionFactories.length || this.actionFactories[type] === null) {
  5468. throw("The specified lexer action type " + type + " is not valid.");
  5469. } else {
  5470. return this.actionFactories[type](data1, data2);
  5471. }
  5472. };
  5473. exports.ATNDeserializer = ATNDeserializer;
  5474. /***/ }),
  5475. /***/ "./node_modules/antlr4/atn/ATNSimulator.js":
  5476. /*!*************************************************!*\
  5477. !*** ./node_modules/antlr4/atn/ATNSimulator.js ***!
  5478. \*************************************************/
  5479. /*! no static exports found */
  5480. /***/ (function(module, exports, __webpack_require__) {
  5481. //
  5482. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  5483. * Use of this file is governed by the BSD 3-clause license that
  5484. * can be found in the LICENSE.txt file in the project root.
  5485. */
  5486. ///
  5487. var DFAState = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
  5488. var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  5489. var getCachedPredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").getCachedPredictionContext;
  5490. var Map = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Map;
  5491. function ATNSimulator(atn, sharedContextCache) {
  5492. // The context cache maps all PredictionContext objects that are ==
  5493. // to a single cached copy. This cache is shared across all contexts
  5494. // in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet
  5495. // to use only cached nodes/graphs in addDFAState(). We don't want to
  5496. // fill this during closure() since there are lots of contexts that
  5497. // pop up but are not used ever again. It also greatly slows down closure().
  5498. //
  5499. // <p>This cache makes a huge difference in memory and a little bit in speed.
  5500. // For the Java grammar on java.*, it dropped the memory requirements
  5501. // at the end from 25M to 16M. We don't store any of the full context
  5502. // graphs in the DFA because they are limited to local context only,
  5503. // but apparently there's a lot of repetition there as well. We optimize
  5504. // the config contexts before storing the config set in the DFA states
  5505. // by literally rebuilding them with cached subgraphs only.</p>
  5506. //
  5507. // <p>I tried a cache for use during closure operations, that was
  5508. // whacked after each adaptivePredict(). It cost a little bit
  5509. // more time I think and doesn't save on the overall footprint
  5510. // so it's not worth the complexity.</p>
  5511. ///
  5512. this.atn = atn;
  5513. this.sharedContextCache = sharedContextCache;
  5514. return this;
  5515. }
  5516. // Must distinguish between missing edge and edge we know leads nowhere///
  5517. ATNSimulator.ERROR = new DFAState(0x7FFFFFFF, new ATNConfigSet());
  5518. ATNSimulator.prototype.getCachedContext = function(context) {
  5519. if (this.sharedContextCache ===null) {
  5520. return context;
  5521. }
  5522. var visited = new Map();
  5523. return getCachedPredictionContext(context, this.sharedContextCache, visited);
  5524. };
  5525. exports.ATNSimulator = ATNSimulator;
  5526. /***/ }),
  5527. /***/ "./node_modules/antlr4/atn/ATNState.js":
  5528. /*!*********************************************!*\
  5529. !*** ./node_modules/antlr4/atn/ATNState.js ***!
  5530. \*********************************************/
  5531. /*! no static exports found */
  5532. /***/ (function(module, exports) {
  5533. //
  5534. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  5535. * Use of this file is governed by the BSD 3-clause license that
  5536. * can be found in the LICENSE.txt file in the project root.
  5537. */
  5538. //
  5539. // The following images show the relation of states and
  5540. // {@link ATNState//transitions} for various grammar constructs.
  5541. //
  5542. // <ul>
  5543. //
  5544. // <li>Solid edges marked with an &//0949; indicate a required
  5545. // {@link EpsilonTransition}.</li>
  5546. //
  5547. // <li>Dashed edges indicate locations where any transition derived from
  5548. // {@link Transition} might appear.</li>
  5549. //
  5550. // <li>Dashed nodes are place holders for either a sequence of linked
  5551. // {@link BasicState} states or the inclusion of a block representing a nested
  5552. // construct in one of the forms below.</li>
  5553. //
  5554. // <li>Nodes showing multiple outgoing alternatives with a {@code ...} support
  5555. // any number of alternatives (one or more). Nodes without the {@code ...} only
  5556. // support the exact number of alternatives shown in the diagram.</li>
  5557. //
  5558. // </ul>
  5559. //
  5560. // <h2>Basic Blocks</h2>
  5561. //
  5562. // <h3>Rule</h3>
  5563. //
  5564. // <embed src="images/Rule.svg" type="image/svg+xml"/>
  5565. //
  5566. // <h3>Block of 1 or more alternatives</h3>
  5567. //
  5568. // <embed src="images/Block.svg" type="image/svg+xml"/>
  5569. //
  5570. // <h2>Greedy Loops</h2>
  5571. //
  5572. // <h3>Greedy Closure: {@code (...)*}</h3>
  5573. //
  5574. // <embed src="images/ClosureGreedy.svg" type="image/svg+xml"/>
  5575. //
  5576. // <h3>Greedy Positive Closure: {@code (...)+}</h3>
  5577. //
  5578. // <embed src="images/PositiveClosureGreedy.svg" type="image/svg+xml"/>
  5579. //
  5580. // <h3>Greedy Optional: {@code (...)?}</h3>
  5581. //
  5582. // <embed src="images/OptionalGreedy.svg" type="image/svg+xml"/>
  5583. //
  5584. // <h2>Non-Greedy Loops</h2>
  5585. //
  5586. // <h3>Non-Greedy Closure: {@code (...)*?}</h3>
  5587. //
  5588. // <embed src="images/ClosureNonGreedy.svg" type="image/svg+xml"/>
  5589. //
  5590. // <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>
  5591. //
  5592. // <embed src="images/PositiveClosureNonGreedy.svg" type="image/svg+xml"/>
  5593. //
  5594. // <h3>Non-Greedy Optional: {@code (...)??}</h3>
  5595. //
  5596. // <embed src="images/OptionalNonGreedy.svg" type="image/svg+xml"/>
  5597. //
  5598. var INITIAL_NUM_TRANSITIONS = 4;
  5599. function ATNState() {
  5600. // Which ATN are we in?
  5601. this.atn = null;
  5602. this.stateNumber = ATNState.INVALID_STATE_NUMBER;
  5603. this.stateType = null;
  5604. this.ruleIndex = 0; // at runtime, we don't have Rule objects
  5605. this.epsilonOnlyTransitions = false;
  5606. // Track the transitions emanating from this ATN state.
  5607. this.transitions = [];
  5608. // Used to cache lookahead during parsing, not used during construction
  5609. this.nextTokenWithinRule = null;
  5610. return this;
  5611. }
  5612. // constants for serialization
  5613. ATNState.INVALID_TYPE = 0;
  5614. ATNState.BASIC = 1;
  5615. ATNState.RULE_START = 2;
  5616. ATNState.BLOCK_START = 3;
  5617. ATNState.PLUS_BLOCK_START = 4;
  5618. ATNState.STAR_BLOCK_START = 5;
  5619. ATNState.TOKEN_START = 6;
  5620. ATNState.RULE_STOP = 7;
  5621. ATNState.BLOCK_END = 8;
  5622. ATNState.STAR_LOOP_BACK = 9;
  5623. ATNState.STAR_LOOP_ENTRY = 10;
  5624. ATNState.PLUS_LOOP_BACK = 11;
  5625. ATNState.LOOP_END = 12;
  5626. ATNState.serializationNames = [
  5627. "INVALID",
  5628. "BASIC",
  5629. "RULE_START",
  5630. "BLOCK_START",
  5631. "PLUS_BLOCK_START",
  5632. "STAR_BLOCK_START",
  5633. "TOKEN_START",
  5634. "RULE_STOP",
  5635. "BLOCK_END",
  5636. "STAR_LOOP_BACK",
  5637. "STAR_LOOP_ENTRY",
  5638. "PLUS_LOOP_BACK",
  5639. "LOOP_END" ];
  5640. ATNState.INVALID_STATE_NUMBER = -1;
  5641. ATNState.prototype.toString = function() {
  5642. return this.stateNumber;
  5643. };
  5644. ATNState.prototype.equals = function(other) {
  5645. if (other instanceof ATNState) {
  5646. return this.stateNumber===other.stateNumber;
  5647. } else {
  5648. return false;
  5649. }
  5650. };
  5651. ATNState.prototype.isNonGreedyExitState = function() {
  5652. return false;
  5653. };
  5654. ATNState.prototype.addTransition = function(trans, index) {
  5655. if(index===undefined) {
  5656. index = -1;
  5657. }
  5658. if (this.transitions.length===0) {
  5659. this.epsilonOnlyTransitions = trans.isEpsilon;
  5660. } else if(this.epsilonOnlyTransitions !== trans.isEpsilon) {
  5661. this.epsilonOnlyTransitions = false;
  5662. }
  5663. if (index===-1) {
  5664. this.transitions.push(trans);
  5665. } else {
  5666. this.transitions.splice(index, 1, trans);
  5667. }
  5668. };
  5669. function BasicState() {
  5670. ATNState.call(this);
  5671. this.stateType = ATNState.BASIC;
  5672. return this;
  5673. }
  5674. BasicState.prototype = Object.create(ATNState.prototype);
  5675. BasicState.prototype.constructor = BasicState;
  5676. function DecisionState() {
  5677. ATNState.call(this);
  5678. this.decision = -1;
  5679. this.nonGreedy = false;
  5680. return this;
  5681. }
  5682. DecisionState.prototype = Object.create(ATNState.prototype);
  5683. DecisionState.prototype.constructor = DecisionState;
  5684. // The start of a regular {@code (...)} block.
  5685. function BlockStartState() {
  5686. DecisionState.call(this);
  5687. this.endState = null;
  5688. return this;
  5689. }
  5690. BlockStartState.prototype = Object.create(DecisionState.prototype);
  5691. BlockStartState.prototype.constructor = BlockStartState;
  5692. function BasicBlockStartState() {
  5693. BlockStartState.call(this);
  5694. this.stateType = ATNState.BLOCK_START;
  5695. return this;
  5696. }
  5697. BasicBlockStartState.prototype = Object.create(BlockStartState.prototype);
  5698. BasicBlockStartState.prototype.constructor = BasicBlockStartState;
  5699. // Terminal node of a simple {@code (a|b|c)} block.
  5700. function BlockEndState() {
  5701. ATNState.call(this);
  5702. this.stateType = ATNState.BLOCK_END;
  5703. this.startState = null;
  5704. return this;
  5705. }
  5706. BlockEndState.prototype = Object.create(ATNState.prototype);
  5707. BlockEndState.prototype.constructor = BlockEndState;
  5708. // The last node in the ATN for a rule, unless that rule is the start symbol.
  5709. // In that case, there is one transition to EOF. Later, we might encode
  5710. // references to all calls to this rule to compute FOLLOW sets for
  5711. // error handling.
  5712. //
  5713. function RuleStopState() {
  5714. ATNState.call(this);
  5715. this.stateType = ATNState.RULE_STOP;
  5716. return this;
  5717. }
  5718. RuleStopState.prototype = Object.create(ATNState.prototype);
  5719. RuleStopState.prototype.constructor = RuleStopState;
  5720. function RuleStartState() {
  5721. ATNState.call(this);
  5722. this.stateType = ATNState.RULE_START;
  5723. this.stopState = null;
  5724. this.isPrecedenceRule = false;
  5725. return this;
  5726. }
  5727. RuleStartState.prototype = Object.create(ATNState.prototype);
  5728. RuleStartState.prototype.constructor = RuleStartState;
  5729. // Decision state for {@code A+} and {@code (A|B)+}. It has two transitions:
  5730. // one to the loop back to start of the block and one to exit.
  5731. //
  5732. function PlusLoopbackState() {
  5733. DecisionState.call(this);
  5734. this.stateType = ATNState.PLUS_LOOP_BACK;
  5735. return this;
  5736. }
  5737. PlusLoopbackState.prototype = Object.create(DecisionState.prototype);
  5738. PlusLoopbackState.prototype.constructor = PlusLoopbackState;
  5739. // Start of {@code (A|B|...)+} loop. Technically a decision state, but
  5740. // we don't use for code generation; somebody might need it, so I'm defining
  5741. // it for completeness. In reality, the {@link PlusLoopbackState} node is the
  5742. // real decision-making note for {@code A+}.
  5743. //
  5744. function PlusBlockStartState() {
  5745. BlockStartState.call(this);
  5746. this.stateType = ATNState.PLUS_BLOCK_START;
  5747. this.loopBackState = null;
  5748. return this;
  5749. }
  5750. PlusBlockStartState.prototype = Object.create(BlockStartState.prototype);
  5751. PlusBlockStartState.prototype.constructor = PlusBlockStartState;
  5752. // The block that begins a closure loop.
  5753. function StarBlockStartState() {
  5754. BlockStartState.call(this);
  5755. this.stateType = ATNState.STAR_BLOCK_START;
  5756. return this;
  5757. }
  5758. StarBlockStartState.prototype = Object.create(BlockStartState.prototype);
  5759. StarBlockStartState.prototype.constructor = StarBlockStartState;
  5760. function StarLoopbackState() {
  5761. ATNState.call(this);
  5762. this.stateType = ATNState.STAR_LOOP_BACK;
  5763. return this;
  5764. }
  5765. StarLoopbackState.prototype = Object.create(ATNState.prototype);
  5766. StarLoopbackState.prototype.constructor = StarLoopbackState;
  5767. function StarLoopEntryState() {
  5768. DecisionState.call(this);
  5769. this.stateType = ATNState.STAR_LOOP_ENTRY;
  5770. this.loopBackState = null;
  5771. // Indicates whether this state can benefit from a precedence DFA during SLL decision making.
  5772. this.isPrecedenceDecision = null;
  5773. return this;
  5774. }
  5775. StarLoopEntryState.prototype = Object.create(DecisionState.prototype);
  5776. StarLoopEntryState.prototype.constructor = StarLoopEntryState;
  5777. // Mark the end of a * or + loop.
  5778. function LoopEndState() {
  5779. ATNState.call(this);
  5780. this.stateType = ATNState.LOOP_END;
  5781. this.loopBackState = null;
  5782. return this;
  5783. }
  5784. LoopEndState.prototype = Object.create(ATNState.prototype);
  5785. LoopEndState.prototype.constructor = LoopEndState;
  5786. // The Tokens rule start state linking to each lexer rule start state */
  5787. function TokensStartState() {
  5788. DecisionState.call(this);
  5789. this.stateType = ATNState.TOKEN_START;
  5790. return this;
  5791. }
  5792. TokensStartState.prototype = Object.create(DecisionState.prototype);
  5793. TokensStartState.prototype.constructor = TokensStartState;
  5794. exports.ATNState = ATNState;
  5795. exports.BasicState = BasicState;
  5796. exports.DecisionState = DecisionState;
  5797. exports.BlockStartState = BlockStartState;
  5798. exports.BlockEndState = BlockEndState;
  5799. exports.LoopEndState = LoopEndState;
  5800. exports.RuleStartState = RuleStartState;
  5801. exports.RuleStopState = RuleStopState;
  5802. exports.TokensStartState = TokensStartState;
  5803. exports.PlusLoopbackState = PlusLoopbackState;
  5804. exports.StarLoopbackState = StarLoopbackState;
  5805. exports.StarLoopEntryState = StarLoopEntryState;
  5806. exports.PlusBlockStartState = PlusBlockStartState;
  5807. exports.StarBlockStartState = StarBlockStartState;
  5808. exports.BasicBlockStartState = BasicBlockStartState;
  5809. /***/ }),
  5810. /***/ "./node_modules/antlr4/atn/ATNType.js":
  5811. /*!********************************************!*\
  5812. !*** ./node_modules/antlr4/atn/ATNType.js ***!
  5813. \********************************************/
  5814. /*! no static exports found */
  5815. /***/ (function(module, exports) {
  5816. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  5817. * Use of this file is governed by the BSD 3-clause license that
  5818. * can be found in the LICENSE.txt file in the project root.
  5819. */
  5820. ///
  5821. // Represents the type of recognizer an ATN applies to.
  5822. function ATNType() {
  5823. }
  5824. ATNType.LEXER = 0;
  5825. ATNType.PARSER = 1;
  5826. exports.ATNType = ATNType;
  5827. /***/ }),
  5828. /***/ "./node_modules/antlr4/atn/LexerATNSimulator.js":
  5829. /*!******************************************************!*\
  5830. !*** ./node_modules/antlr4/atn/LexerATNSimulator.js ***!
  5831. \******************************************************/
  5832. /*! no static exports found */
  5833. /***/ (function(module, exports, __webpack_require__) {
  5834. //
  5835. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  5836. * Use of this file is governed by the BSD 3-clause license that
  5837. * can be found in the LICENSE.txt file in the project root.
  5838. */
  5839. ///
  5840. // When we hit an accept state in either the DFA or the ATN, we
  5841. // have to notify the character stream to start buffering characters
  5842. // via {@link IntStream//mark} and record the current state. The current sim state
  5843. // includes the current index into the input, the current line,
  5844. // and current character position in that line. Note that the Lexer is
  5845. // tracking the starting line and characterization of the token. These
  5846. // variables track the "state" of the simulator when it hits an accept state.
  5847. //
  5848. // <p>We track these variables separately for the DFA and ATN simulation
  5849. // because the DFA simulation often has to fail over to the ATN
  5850. // simulation. If the ATN simulation fails, we need the DFA to fall
  5851. // back to its previously accepted state, if any. If the ATN succeeds,
  5852. // then the ATN does the accept and the DFA simulator that invoked it
  5853. // can simply return the predicted token type.</p>
  5854. ///
  5855. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  5856. var Lexer = __webpack_require__(/*! ./../Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
  5857. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  5858. var ATNSimulator = __webpack_require__(/*! ./ATNSimulator */ "./node_modules/antlr4/atn/ATNSimulator.js").ATNSimulator;
  5859. var DFAState = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
  5860. var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  5861. var OrderedATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").OrderedATNConfigSet;
  5862. var PredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").PredictionContext;
  5863. var SingletonPredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").SingletonPredictionContext;
  5864. var RuleStopState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
  5865. var LexerATNConfig = __webpack_require__(/*! ./ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").LexerATNConfig;
  5866. var Transition = __webpack_require__(/*! ./Transition */ "./node_modules/antlr4/atn/Transition.js").Transition;
  5867. var LexerActionExecutor = __webpack_require__(/*! ./LexerActionExecutor */ "./node_modules/antlr4/atn/LexerActionExecutor.js").LexerActionExecutor;
  5868. var LexerNoViableAltException = __webpack_require__(/*! ./../error/Errors */ "./node_modules/antlr4/error/Errors.js").LexerNoViableAltException;
  5869. function resetSimState(sim) {
  5870. sim.index = -1;
  5871. sim.line = 0;
  5872. sim.column = -1;
  5873. sim.dfaState = null;
  5874. }
  5875. function SimState() {
  5876. resetSimState(this);
  5877. return this;
  5878. }
  5879. SimState.prototype.reset = function() {
  5880. resetSimState(this);
  5881. };
  5882. function LexerATNSimulator(recog, atn, decisionToDFA, sharedContextCache) {
  5883. ATNSimulator.call(this, atn, sharedContextCache);
  5884. this.decisionToDFA = decisionToDFA;
  5885. this.recog = recog;
  5886. // The current token's starting index into the character stream.
  5887. // Shared across DFA to ATN simulation in case the ATN fails and the
  5888. // DFA did not have a previous accept state. In this case, we use the
  5889. // ATN-generated exception object.
  5890. this.startIndex = -1;
  5891. // line number 1..n within the input///
  5892. this.line = 1;
  5893. // The index of the character relative to the beginning of the line
  5894. // 0..n-1///
  5895. this.column = 0;
  5896. this.mode = Lexer.DEFAULT_MODE;
  5897. // Used during DFA/ATN exec to record the most recent accept configuration
  5898. // info
  5899. this.prevAccept = new SimState();
  5900. // done
  5901. return this;
  5902. }
  5903. LexerATNSimulator.prototype = Object.create(ATNSimulator.prototype);
  5904. LexerATNSimulator.prototype.constructor = LexerATNSimulator;
  5905. LexerATNSimulator.debug = false;
  5906. LexerATNSimulator.dfa_debug = false;
  5907. LexerATNSimulator.MIN_DFA_EDGE = 0;
  5908. LexerATNSimulator.MAX_DFA_EDGE = 127; // forces unicode to stay in ATN
  5909. LexerATNSimulator.match_calls = 0;
  5910. LexerATNSimulator.prototype.copyState = function(simulator) {
  5911. this.column = simulator.column;
  5912. this.line = simulator.line;
  5913. this.mode = simulator.mode;
  5914. this.startIndex = simulator.startIndex;
  5915. };
  5916. LexerATNSimulator.prototype.match = function(input, mode) {
  5917. this.match_calls += 1;
  5918. this.mode = mode;
  5919. var mark = input.mark();
  5920. try {
  5921. this.startIndex = input.index;
  5922. this.prevAccept.reset();
  5923. var dfa = this.decisionToDFA[mode];
  5924. if (dfa.s0 === null) {
  5925. return this.matchATN(input);
  5926. } else {
  5927. return this.execATN(input, dfa.s0);
  5928. }
  5929. } finally {
  5930. input.release(mark);
  5931. }
  5932. };
  5933. LexerATNSimulator.prototype.reset = function() {
  5934. this.prevAccept.reset();
  5935. this.startIndex = -1;
  5936. this.line = 1;
  5937. this.column = 0;
  5938. this.mode = Lexer.DEFAULT_MODE;
  5939. };
  5940. LexerATNSimulator.prototype.matchATN = function(input) {
  5941. var startState = this.atn.modeToStartState[this.mode];
  5942. if (LexerATNSimulator.debug) {
  5943. console.log("matchATN mode " + this.mode + " start: " + startState);
  5944. }
  5945. var old_mode = this.mode;
  5946. var s0_closure = this.computeStartState(input, startState);
  5947. var suppressEdge = s0_closure.hasSemanticContext;
  5948. s0_closure.hasSemanticContext = false;
  5949. var next = this.addDFAState(s0_closure);
  5950. if (!suppressEdge) {
  5951. this.decisionToDFA[this.mode].s0 = next;
  5952. }
  5953. var predict = this.execATN(input, next);
  5954. if (LexerATNSimulator.debug) {
  5955. console.log("DFA after matchATN: " + this.decisionToDFA[old_mode].toLexerString());
  5956. }
  5957. return predict;
  5958. };
  5959. LexerATNSimulator.prototype.execATN = function(input, ds0) {
  5960. if (LexerATNSimulator.debug) {
  5961. console.log("start state closure=" + ds0.configs);
  5962. }
  5963. if (ds0.isAcceptState) {
  5964. // allow zero-length tokens
  5965. this.captureSimState(this.prevAccept, input, ds0);
  5966. }
  5967. var t = input.LA(1);
  5968. var s = ds0; // s is current/from DFA state
  5969. while (true) { // while more work
  5970. if (LexerATNSimulator.debug) {
  5971. console.log("execATN loop starting closure: " + s.configs);
  5972. }
  5973. // As we move src->trg, src->trg, we keep track of the previous trg to
  5974. // avoid looking up the DFA state again, which is expensive.
  5975. // If the previous target was already part of the DFA, we might
  5976. // be able to avoid doing a reach operation upon t. If s!=null,
  5977. // it means that semantic predicates didn't prevent us from
  5978. // creating a DFA state. Once we know s!=null, we check to see if
  5979. // the DFA state has an edge already for t. If so, we can just reuse
  5980. // it's configuration set; there's no point in re-computing it.
  5981. // This is kind of like doing DFA simulation within the ATN
  5982. // simulation because DFA simulation is really just a way to avoid
  5983. // computing reach/closure sets. Technically, once we know that
  5984. // we have a previously added DFA state, we could jump over to
  5985. // the DFA simulator. But, that would mean popping back and forth
  5986. // a lot and making things more complicated algorithmically.
  5987. // This optimization makes a lot of sense for loops within DFA.
  5988. // A character will take us back to an existing DFA state
  5989. // that already has lots of edges out of it. e.g., .* in comments.
  5990. // print("Target for:" + str(s) + " and:" + str(t))
  5991. var target = this.getExistingTargetState(s, t);
  5992. // print("Existing:" + str(target))
  5993. if (target === null) {
  5994. target = this.computeTargetState(input, s, t);
  5995. // print("Computed:" + str(target))
  5996. }
  5997. if (target === ATNSimulator.ERROR) {
  5998. break;
  5999. }
  6000. // If this is a consumable input element, make sure to consume before
  6001. // capturing the accept state so the input index, line, and char
  6002. // position accurately reflect the state of the interpreter at the
  6003. // end of the token.
  6004. if (t !== Token.EOF) {
  6005. this.consume(input);
  6006. }
  6007. if (target.isAcceptState) {
  6008. this.captureSimState(this.prevAccept, input, target);
  6009. if (t === Token.EOF) {
  6010. break;
  6011. }
  6012. }
  6013. t = input.LA(1);
  6014. s = target; // flip; current DFA target becomes new src/from state
  6015. }
  6016. return this.failOrAccept(this.prevAccept, input, s.configs, t);
  6017. };
  6018. // Get an existing target state for an edge in the DFA. If the target state
  6019. // for the edge has not yet been computed or is otherwise not available,
  6020. // this method returns {@code null}.
  6021. //
  6022. // @param s The current DFA state
  6023. // @param t The next input symbol
  6024. // @return The existing target DFA state for the given input symbol
  6025. // {@code t}, or {@code null} if the target state for this edge is not
  6026. // already cached
  6027. LexerATNSimulator.prototype.getExistingTargetState = function(s, t) {
  6028. if (s.edges === null || t < LexerATNSimulator.MIN_DFA_EDGE || t > LexerATNSimulator.MAX_DFA_EDGE) {
  6029. return null;
  6030. }
  6031. var target = s.edges[t - LexerATNSimulator.MIN_DFA_EDGE];
  6032. if(target===undefined) {
  6033. target = null;
  6034. }
  6035. if (LexerATNSimulator.debug && target !== null) {
  6036. console.log("reuse state " + s.stateNumber + " edge to " + target.stateNumber);
  6037. }
  6038. return target;
  6039. };
  6040. // Compute a target state for an edge in the DFA, and attempt to add the
  6041. // computed state and corresponding edge to the DFA.
  6042. //
  6043. // @param input The input stream
  6044. // @param s The current DFA state
  6045. // @param t The next input symbol
  6046. //
  6047. // @return The computed target DFA state for the given input symbol
  6048. // {@code t}. If {@code t} does not lead to a valid DFA state, this method
  6049. // returns {@link //ERROR}.
  6050. LexerATNSimulator.prototype.computeTargetState = function(input, s, t) {
  6051. var reach = new OrderedATNConfigSet();
  6052. // if we don't find an existing DFA state
  6053. // Fill reach starting from closure, following t transitions
  6054. this.getReachableConfigSet(input, s.configs, reach, t);
  6055. if (reach.items.length === 0) { // we got nowhere on t from s
  6056. if (!reach.hasSemanticContext) {
  6057. // we got nowhere on t, don't throw out this knowledge; it'd
  6058. // cause a failover from DFA later.
  6059. this.addDFAEdge(s, t, ATNSimulator.ERROR);
  6060. }
  6061. // stop when we can't match any more char
  6062. return ATNSimulator.ERROR;
  6063. }
  6064. // Add an edge from s to target DFA found/created for reach
  6065. return this.addDFAEdge(s, t, null, reach);
  6066. };
  6067. LexerATNSimulator.prototype.failOrAccept = function(prevAccept, input, reach, t) {
  6068. if (this.prevAccept.dfaState !== null) {
  6069. var lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor;
  6070. this.accept(input, lexerActionExecutor, this.startIndex,
  6071. prevAccept.index, prevAccept.line, prevAccept.column);
  6072. return prevAccept.dfaState.prediction;
  6073. } else {
  6074. // if no accept and EOF is first char, return EOF
  6075. if (t === Token.EOF && input.index === this.startIndex) {
  6076. return Token.EOF;
  6077. }
  6078. throw new LexerNoViableAltException(this.recog, input, this.startIndex, reach);
  6079. }
  6080. };
  6081. // Given a starting configuration set, figure out all ATN configurations
  6082. // we can reach upon input {@code t}. Parameter {@code reach} is a return
  6083. // parameter.
  6084. LexerATNSimulator.prototype.getReachableConfigSet = function(input, closure,
  6085. reach, t) {
  6086. // this is used to skip processing for configs which have a lower priority
  6087. // than a config that already reached an accept state for the same rule
  6088. var skipAlt = ATN.INVALID_ALT_NUMBER;
  6089. for (var i = 0; i < closure.items.length; i++) {
  6090. var cfg = closure.items[i];
  6091. var currentAltReachedAcceptState = (cfg.alt === skipAlt);
  6092. if (currentAltReachedAcceptState && cfg.passedThroughNonGreedyDecision) {
  6093. continue;
  6094. }
  6095. if (LexerATNSimulator.debug) {
  6096. console.log("testing %s at %s\n", this.getTokenName(t), cfg
  6097. .toString(this.recog, true));
  6098. }
  6099. for (var j = 0; j < cfg.state.transitions.length; j++) {
  6100. var trans = cfg.state.transitions[j]; // for each transition
  6101. var target = this.getReachableTarget(trans, t);
  6102. if (target !== null) {
  6103. var lexerActionExecutor = cfg.lexerActionExecutor;
  6104. if (lexerActionExecutor !== null) {
  6105. lexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.index - this.startIndex);
  6106. }
  6107. var treatEofAsEpsilon = (t === Token.EOF);
  6108. var config = new LexerATNConfig({state:target, lexerActionExecutor:lexerActionExecutor}, cfg);
  6109. if (this.closure(input, config, reach,
  6110. currentAltReachedAcceptState, true, treatEofAsEpsilon)) {
  6111. // any remaining configs for this alt have a lower priority
  6112. // than the one that just reached an accept state.
  6113. skipAlt = cfg.alt;
  6114. }
  6115. }
  6116. }
  6117. }
  6118. };
  6119. LexerATNSimulator.prototype.accept = function(input, lexerActionExecutor,
  6120. startIndex, index, line, charPos) {
  6121. if (LexerATNSimulator.debug) {
  6122. console.log("ACTION %s\n", lexerActionExecutor);
  6123. }
  6124. // seek to after last char in token
  6125. input.seek(index);
  6126. this.line = line;
  6127. this.column = charPos;
  6128. if (lexerActionExecutor !== null && this.recog !== null) {
  6129. lexerActionExecutor.execute(this.recog, input, startIndex);
  6130. }
  6131. };
  6132. LexerATNSimulator.prototype.getReachableTarget = function(trans, t) {
  6133. if (trans.matches(t, 0, Lexer.MAX_CHAR_VALUE)) {
  6134. return trans.target;
  6135. } else {
  6136. return null;
  6137. }
  6138. };
  6139. LexerATNSimulator.prototype.computeStartState = function(input, p) {
  6140. var initialContext = PredictionContext.EMPTY;
  6141. var configs = new OrderedATNConfigSet();
  6142. for (var i = 0; i < p.transitions.length; i++) {
  6143. var target = p.transitions[i].target;
  6144. var cfg = new LexerATNConfig({state:target, alt:i+1, context:initialContext}, null);
  6145. this.closure(input, cfg, configs, false, false, false);
  6146. }
  6147. return configs;
  6148. };
  6149. // Since the alternatives within any lexer decision are ordered by
  6150. // preference, this method stops pursuing the closure as soon as an accept
  6151. // state is reached. After the first accept state is reached by depth-first
  6152. // search from {@code config}, all other (potentially reachable) states for
  6153. // this rule would have a lower priority.
  6154. //
  6155. // @return {@code true} if an accept state is reached, otherwise
  6156. // {@code false}.
  6157. LexerATNSimulator.prototype.closure = function(input, config, configs,
  6158. currentAltReachedAcceptState, speculative, treatEofAsEpsilon) {
  6159. var cfg = null;
  6160. if (LexerATNSimulator.debug) {
  6161. console.log("closure(" + config.toString(this.recog, true) + ")");
  6162. }
  6163. if (config.state instanceof RuleStopState) {
  6164. if (LexerATNSimulator.debug) {
  6165. if (this.recog !== null) {
  6166. console.log("closure at %s rule stop %s\n", this.recog.ruleNames[config.state.ruleIndex], config);
  6167. } else {
  6168. console.log("closure at rule stop %s\n", config);
  6169. }
  6170. }
  6171. if (config.context === null || config.context.hasEmptyPath()) {
  6172. if (config.context === null || config.context.isEmpty()) {
  6173. configs.add(config);
  6174. return true;
  6175. } else {
  6176. configs.add(new LexerATNConfig({ state:config.state, context:PredictionContext.EMPTY}, config));
  6177. currentAltReachedAcceptState = true;
  6178. }
  6179. }
  6180. if (config.context !== null && !config.context.isEmpty()) {
  6181. for (var i = 0; i < config.context.length; i++) {
  6182. if (config.context.getReturnState(i) !== PredictionContext.EMPTY_RETURN_STATE) {
  6183. var newContext = config.context.getParent(i); // "pop" return state
  6184. var returnState = this.atn.states[config.context.getReturnState(i)];
  6185. cfg = new LexerATNConfig({ state:returnState, context:newContext }, config);
  6186. currentAltReachedAcceptState = this.closure(input, cfg,
  6187. configs, currentAltReachedAcceptState, speculative,
  6188. treatEofAsEpsilon);
  6189. }
  6190. }
  6191. }
  6192. return currentAltReachedAcceptState;
  6193. }
  6194. // optimization
  6195. if (!config.state.epsilonOnlyTransitions) {
  6196. if (!currentAltReachedAcceptState || !config.passedThroughNonGreedyDecision) {
  6197. configs.add(config);
  6198. }
  6199. }
  6200. for (var j = 0; j < config.state.transitions.length; j++) {
  6201. var trans = config.state.transitions[j];
  6202. cfg = this.getEpsilonTarget(input, config, trans, configs, speculative, treatEofAsEpsilon);
  6203. if (cfg !== null) {
  6204. currentAltReachedAcceptState = this.closure(input, cfg, configs,
  6205. currentAltReachedAcceptState, speculative, treatEofAsEpsilon);
  6206. }
  6207. }
  6208. return currentAltReachedAcceptState;
  6209. };
  6210. // side-effect: can alter configs.hasSemanticContext
  6211. LexerATNSimulator.prototype.getEpsilonTarget = function(input, config, trans,
  6212. configs, speculative, treatEofAsEpsilon) {
  6213. var cfg = null;
  6214. if (trans.serializationType === Transition.RULE) {
  6215. var newContext = SingletonPredictionContext.create(config.context, trans.followState.stateNumber);
  6216. cfg = new LexerATNConfig( { state:trans.target, context:newContext}, config);
  6217. } else if (trans.serializationType === Transition.PRECEDENCE) {
  6218. throw "Precedence predicates are not supported in lexers.";
  6219. } else if (trans.serializationType === Transition.PREDICATE) {
  6220. // Track traversing semantic predicates. If we traverse,
  6221. // we cannot add a DFA state for this "reach" computation
  6222. // because the DFA would not test the predicate again in the
  6223. // future. Rather than creating collections of semantic predicates
  6224. // like v3 and testing them on prediction, v4 will test them on the
  6225. // fly all the time using the ATN not the DFA. This is slower but
  6226. // semantically it's not used that often. One of the key elements to
  6227. // this predicate mechanism is not adding DFA states that see
  6228. // predicates immediately afterwards in the ATN. For example,
  6229. // a : ID {p1}? | ID {p2}? ;
  6230. // should create the start state for rule 'a' (to save start state
  6231. // competition), but should not create target of ID state. The
  6232. // collection of ATN states the following ID references includes
  6233. // states reached by traversing predicates. Since this is when we
  6234. // test them, we cannot cash the DFA state target of ID.
  6235. if (LexerATNSimulator.debug) {
  6236. console.log("EVAL rule " + trans.ruleIndex + ":" + trans.predIndex);
  6237. }
  6238. configs.hasSemanticContext = true;
  6239. if (this.evaluatePredicate(input, trans.ruleIndex, trans.predIndex, speculative)) {
  6240. cfg = new LexerATNConfig({ state:trans.target}, config);
  6241. }
  6242. } else if (trans.serializationType === Transition.ACTION) {
  6243. if (config.context === null || config.context.hasEmptyPath()) {
  6244. // execute actions anywhere in the start rule for a token.
  6245. //
  6246. // TODO: if the entry rule is invoked recursively, some
  6247. // actions may be executed during the recursive call. The
  6248. // problem can appear when hasEmptyPath() is true but
  6249. // isEmpty() is false. In this case, the config needs to be
  6250. // split into two contexts - one with just the empty path
  6251. // and another with everything but the empty path.
  6252. // Unfortunately, the current algorithm does not allow
  6253. // getEpsilonTarget to return two configurations, so
  6254. // additional modifications are needed before we can support
  6255. // the split operation.
  6256. var lexerActionExecutor = LexerActionExecutor.append(config.lexerActionExecutor,
  6257. this.atn.lexerActions[trans.actionIndex]);
  6258. cfg = new LexerATNConfig({ state:trans.target, lexerActionExecutor:lexerActionExecutor }, config);
  6259. } else {
  6260. // ignore actions in referenced rules
  6261. cfg = new LexerATNConfig( { state:trans.target}, config);
  6262. }
  6263. } else if (trans.serializationType === Transition.EPSILON) {
  6264. cfg = new LexerATNConfig({ state:trans.target}, config);
  6265. } else if (trans.serializationType === Transition.ATOM ||
  6266. trans.serializationType === Transition.RANGE ||
  6267. trans.serializationType === Transition.SET) {
  6268. if (treatEofAsEpsilon) {
  6269. if (trans.matches(Token.EOF, 0, Lexer.MAX_CHAR_VALUE)) {
  6270. cfg = new LexerATNConfig( { state:trans.target }, config);
  6271. }
  6272. }
  6273. }
  6274. return cfg;
  6275. };
  6276. // Evaluate a predicate specified in the lexer.
  6277. //
  6278. // <p>If {@code speculative} is {@code true}, this method was called before
  6279. // {@link //consume} for the matched character. This method should call
  6280. // {@link //consume} before evaluating the predicate to ensure position
  6281. // sensitive values, including {@link Lexer//getText}, {@link Lexer//getLine},
  6282. // and {@link Lexer//getcolumn}, properly reflect the current
  6283. // lexer state. This method should restore {@code input} and the simulator
  6284. // to the original state before returning (i.e. undo the actions made by the
  6285. // call to {@link //consume}.</p>
  6286. //
  6287. // @param input The input stream.
  6288. // @param ruleIndex The rule containing the predicate.
  6289. // @param predIndex The index of the predicate within the rule.
  6290. // @param speculative {@code true} if the current index in {@code input} is
  6291. // one character before the predicate's location.
  6292. //
  6293. // @return {@code true} if the specified predicate evaluates to
  6294. // {@code true}.
  6295. // /
  6296. LexerATNSimulator.prototype.evaluatePredicate = function(input, ruleIndex,
  6297. predIndex, speculative) {
  6298. // assume true if no recognizer was provided
  6299. if (this.recog === null) {
  6300. return true;
  6301. }
  6302. if (!speculative) {
  6303. return this.recog.sempred(null, ruleIndex, predIndex);
  6304. }
  6305. var savedcolumn = this.column;
  6306. var savedLine = this.line;
  6307. var index = input.index;
  6308. var marker = input.mark();
  6309. try {
  6310. this.consume(input);
  6311. return this.recog.sempred(null, ruleIndex, predIndex);
  6312. } finally {
  6313. this.column = savedcolumn;
  6314. this.line = savedLine;
  6315. input.seek(index);
  6316. input.release(marker);
  6317. }
  6318. };
  6319. LexerATNSimulator.prototype.captureSimState = function(settings, input, dfaState) {
  6320. settings.index = input.index;
  6321. settings.line = this.line;
  6322. settings.column = this.column;
  6323. settings.dfaState = dfaState;
  6324. };
  6325. LexerATNSimulator.prototype.addDFAEdge = function(from_, tk, to, cfgs) {
  6326. if (to === undefined) {
  6327. to = null;
  6328. }
  6329. if (cfgs === undefined) {
  6330. cfgs = null;
  6331. }
  6332. if (to === null && cfgs !== null) {
  6333. // leading to this call, ATNConfigSet.hasSemanticContext is used as a
  6334. // marker indicating dynamic predicate evaluation makes this edge
  6335. // dependent on the specific input sequence, so the static edge in the
  6336. // DFA should be omitted. The target DFAState is still created since
  6337. // execATN has the ability to resynchronize with the DFA state cache
  6338. // following the predicate evaluation step.
  6339. //
  6340. // TJP notes: next time through the DFA, we see a pred again and eval.
  6341. // If that gets us to a previously created (but dangling) DFA
  6342. // state, we can continue in pure DFA mode from there.
  6343. // /
  6344. var suppressEdge = cfgs.hasSemanticContext;
  6345. cfgs.hasSemanticContext = false;
  6346. to = this.addDFAState(cfgs);
  6347. if (suppressEdge) {
  6348. return to;
  6349. }
  6350. }
  6351. // add the edge
  6352. if (tk < LexerATNSimulator.MIN_DFA_EDGE || tk > LexerATNSimulator.MAX_DFA_EDGE) {
  6353. // Only track edges within the DFA bounds
  6354. return to;
  6355. }
  6356. if (LexerATNSimulator.debug) {
  6357. console.log("EDGE " + from_ + " -> " + to + " upon " + tk);
  6358. }
  6359. if (from_.edges === null) {
  6360. // make room for tokens 1..n and -1 masquerading as index 0
  6361. from_.edges = [];
  6362. }
  6363. from_.edges[tk - LexerATNSimulator.MIN_DFA_EDGE] = to; // connect
  6364. return to;
  6365. };
  6366. // Add a new DFA state if there isn't one with this set of
  6367. // configurations already. This method also detects the first
  6368. // configuration containing an ATN rule stop state. Later, when
  6369. // traversing the DFA, we will know which rule to accept.
  6370. LexerATNSimulator.prototype.addDFAState = function(configs) {
  6371. var proposed = new DFAState(null, configs);
  6372. var firstConfigWithRuleStopState = null;
  6373. for (var i = 0; i < configs.items.length; i++) {
  6374. var cfg = configs.items[i];
  6375. if (cfg.state instanceof RuleStopState) {
  6376. firstConfigWithRuleStopState = cfg;
  6377. break;
  6378. }
  6379. }
  6380. if (firstConfigWithRuleStopState !== null) {
  6381. proposed.isAcceptState = true;
  6382. proposed.lexerActionExecutor = firstConfigWithRuleStopState.lexerActionExecutor;
  6383. proposed.prediction = this.atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex];
  6384. }
  6385. var dfa = this.decisionToDFA[this.mode];
  6386. var existing = dfa.states.get(proposed);
  6387. if (existing!==null) {
  6388. return existing;
  6389. }
  6390. var newState = proposed;
  6391. newState.stateNumber = dfa.states.length;
  6392. configs.setReadonly(true);
  6393. newState.configs = configs;
  6394. dfa.states.add(newState);
  6395. return newState;
  6396. };
  6397. LexerATNSimulator.prototype.getDFA = function(mode) {
  6398. return this.decisionToDFA[mode];
  6399. };
  6400. // Get the text matched so far for the current token.
  6401. LexerATNSimulator.prototype.getText = function(input) {
  6402. // index is first lookahead char, don't include.
  6403. return input.getText(this.startIndex, input.index - 1);
  6404. };
  6405. LexerATNSimulator.prototype.consume = function(input) {
  6406. var curChar = input.LA(1);
  6407. if (curChar === "\n".charCodeAt(0)) {
  6408. this.line += 1;
  6409. this.column = 0;
  6410. } else {
  6411. this.column += 1;
  6412. }
  6413. input.consume();
  6414. };
  6415. LexerATNSimulator.prototype.getTokenName = function(tt) {
  6416. if (tt === -1) {
  6417. return "EOF";
  6418. } else {
  6419. return "'" + String.fromCharCode(tt) + "'";
  6420. }
  6421. };
  6422. exports.LexerATNSimulator = LexerATNSimulator;
  6423. /***/ }),
  6424. /***/ "./node_modules/antlr4/atn/LexerAction.js":
  6425. /*!************************************************!*\
  6426. !*** ./node_modules/antlr4/atn/LexerAction.js ***!
  6427. \************************************************/
  6428. /*! no static exports found */
  6429. /***/ (function(module, exports) {
  6430. //
  6431. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  6432. * Use of this file is governed by the BSD 3-clause license that
  6433. * can be found in the LICENSE.txt file in the project root.
  6434. */
  6435. //
  6436. function LexerActionType() {
  6437. }
  6438. LexerActionType.CHANNEL = 0; //The type of a {@link LexerChannelAction} action.
  6439. LexerActionType.CUSTOM = 1; //The type of a {@link LexerCustomAction} action.
  6440. LexerActionType.MODE = 2; //The type of a {@link LexerModeAction} action.
  6441. LexerActionType.MORE = 3; //The type of a {@link LexerMoreAction} action.
  6442. LexerActionType.POP_MODE = 4; //The type of a {@link LexerPopModeAction} action.
  6443. LexerActionType.PUSH_MODE = 5; //The type of a {@link LexerPushModeAction} action.
  6444. LexerActionType.SKIP = 6; //The type of a {@link LexerSkipAction} action.
  6445. LexerActionType.TYPE = 7; //The type of a {@link LexerTypeAction} action.
  6446. function LexerAction(action) {
  6447. this.actionType = action;
  6448. this.isPositionDependent = false;
  6449. return this;
  6450. }
  6451. LexerAction.prototype.hashCode = function() {
  6452. var hash = new Hash();
  6453. this.updateHashCode(hash);
  6454. return hash.finish()
  6455. };
  6456. LexerAction.prototype.updateHashCode = function(hash) {
  6457. hash.update(this.actionType);
  6458. };
  6459. LexerAction.prototype.equals = function(other) {
  6460. return this === other;
  6461. };
  6462. //
  6463. // Implements the {@code skip} lexer action by calling {@link Lexer//skip}.
  6464. //
  6465. // <p>The {@code skip} command does not have any parameters, so this action is
  6466. // implemented as a singleton instance exposed by {@link //INSTANCE}.</p>
  6467. function LexerSkipAction() {
  6468. LexerAction.call(this, LexerActionType.SKIP);
  6469. return this;
  6470. }
  6471. LexerSkipAction.prototype = Object.create(LexerAction.prototype);
  6472. LexerSkipAction.prototype.constructor = LexerSkipAction;
  6473. // Provides a singleton instance of this parameterless lexer action.
  6474. LexerSkipAction.INSTANCE = new LexerSkipAction();
  6475. LexerSkipAction.prototype.execute = function(lexer) {
  6476. lexer.skip();
  6477. };
  6478. LexerSkipAction.prototype.toString = function() {
  6479. return "skip";
  6480. };
  6481. // Implements the {@code type} lexer action by calling {@link Lexer//setType}
  6482. // with the assigned type.
  6483. function LexerTypeAction(type) {
  6484. LexerAction.call(this, LexerActionType.TYPE);
  6485. this.type = type;
  6486. return this;
  6487. }
  6488. LexerTypeAction.prototype = Object.create(LexerAction.prototype);
  6489. LexerTypeAction.prototype.constructor = LexerTypeAction;
  6490. LexerTypeAction.prototype.execute = function(lexer) {
  6491. lexer.type = this.type;
  6492. };
  6493. LexerTypeAction.prototype.updateHashCode = function(hash) {
  6494. hash.update(this.actionType, this.type);
  6495. };
  6496. LexerTypeAction.prototype.equals = function(other) {
  6497. if(this === other) {
  6498. return true;
  6499. } else if (! (other instanceof LexerTypeAction)) {
  6500. return false;
  6501. } else {
  6502. return this.type === other.type;
  6503. }
  6504. };
  6505. LexerTypeAction.prototype.toString = function() {
  6506. return "type(" + this.type + ")";
  6507. };
  6508. // Implements the {@code pushMode} lexer action by calling
  6509. // {@link Lexer//pushMode} with the assigned mode.
  6510. function LexerPushModeAction(mode) {
  6511. LexerAction.call(this, LexerActionType.PUSH_MODE);
  6512. this.mode = mode;
  6513. return this;
  6514. }
  6515. LexerPushModeAction.prototype = Object.create(LexerAction.prototype);
  6516. LexerPushModeAction.prototype.constructor = LexerPushModeAction;
  6517. // <p>This action is implemented by calling {@link Lexer//pushMode} with the
  6518. // value provided by {@link //getMode}.</p>
  6519. LexerPushModeAction.prototype.execute = function(lexer) {
  6520. lexer.pushMode(this.mode);
  6521. };
  6522. LexerPushModeAction.prototype.updateHashCode = function(hash) {
  6523. hash.update(this.actionType, this.mode);
  6524. };
  6525. LexerPushModeAction.prototype.equals = function(other) {
  6526. if (this === other) {
  6527. return true;
  6528. } else if (! (other instanceof LexerPushModeAction)) {
  6529. return false;
  6530. } else {
  6531. return this.mode === other.mode;
  6532. }
  6533. };
  6534. LexerPushModeAction.prototype.toString = function() {
  6535. return "pushMode(" + this.mode + ")";
  6536. };
  6537. // Implements the {@code popMode} lexer action by calling {@link Lexer//popMode}.
  6538. //
  6539. // <p>The {@code popMode} command does not have any parameters, so this action is
  6540. // implemented as a singleton instance exposed by {@link //INSTANCE}.</p>
  6541. function LexerPopModeAction() {
  6542. LexerAction.call(this,LexerActionType.POP_MODE);
  6543. return this;
  6544. }
  6545. LexerPopModeAction.prototype = Object.create(LexerAction.prototype);
  6546. LexerPopModeAction.prototype.constructor = LexerPopModeAction;
  6547. LexerPopModeAction.INSTANCE = new LexerPopModeAction();
  6548. // <p>This action is implemented by calling {@link Lexer//popMode}.</p>
  6549. LexerPopModeAction.prototype.execute = function(lexer) {
  6550. lexer.popMode();
  6551. };
  6552. LexerPopModeAction.prototype.toString = function() {
  6553. return "popMode";
  6554. };
  6555. // Implements the {@code more} lexer action by calling {@link Lexer//more}.
  6556. //
  6557. // <p>The {@code more} command does not have any parameters, so this action is
  6558. // implemented as a singleton instance exposed by {@link //INSTANCE}.</p>
  6559. function LexerMoreAction() {
  6560. LexerAction.call(this, LexerActionType.MORE);
  6561. return this;
  6562. }
  6563. LexerMoreAction.prototype = Object.create(LexerAction.prototype);
  6564. LexerMoreAction.prototype.constructor = LexerMoreAction;
  6565. LexerMoreAction.INSTANCE = new LexerMoreAction();
  6566. // <p>This action is implemented by calling {@link Lexer//popMode}.</p>
  6567. LexerMoreAction.prototype.execute = function(lexer) {
  6568. lexer.more();
  6569. };
  6570. LexerMoreAction.prototype.toString = function() {
  6571. return "more";
  6572. };
  6573. // Implements the {@code mode} lexer action by calling {@link Lexer//mode} with
  6574. // the assigned mode.
  6575. function LexerModeAction(mode) {
  6576. LexerAction.call(this, LexerActionType.MODE);
  6577. this.mode = mode;
  6578. return this;
  6579. }
  6580. LexerModeAction.prototype = Object.create(LexerAction.prototype);
  6581. LexerModeAction.prototype.constructor = LexerModeAction;
  6582. // <p>This action is implemented by calling {@link Lexer//mode} with the
  6583. // value provided by {@link //getMode}.</p>
  6584. LexerModeAction.prototype.execute = function(lexer) {
  6585. lexer.mode(this.mode);
  6586. };
  6587. LexerModeAction.prototype.updateHashCode = function(hash) {
  6588. hash.update(this.actionType, this.mode);
  6589. };
  6590. LexerModeAction.prototype.equals = function(other) {
  6591. if (this === other) {
  6592. return true;
  6593. } else if (! (other instanceof LexerModeAction)) {
  6594. return false;
  6595. } else {
  6596. return this.mode === other.mode;
  6597. }
  6598. };
  6599. LexerModeAction.prototype.toString = function() {
  6600. return "mode(" + this.mode + ")";
  6601. };
  6602. // Executes a custom lexer action by calling {@link Recognizer//action} with the
  6603. // rule and action indexes assigned to the custom action. The implementation of
  6604. // a custom action is added to the generated code for the lexer in an override
  6605. // of {@link Recognizer//action} when the grammar is compiled.
  6606. //
  6607. // <p>This class may represent embedded actions created with the <code>{...}</code>
  6608. // syntax in ANTLR 4, as well as actions created for lexer commands where the
  6609. // command argument could not be evaluated when the grammar was compiled.</p>
  6610. // Constructs a custom lexer action with the specified rule and action
  6611. // indexes.
  6612. //
  6613. // @param ruleIndex The rule index to use for calls to
  6614. // {@link Recognizer//action}.
  6615. // @param actionIndex The action index to use for calls to
  6616. // {@link Recognizer//action}.
  6617. function LexerCustomAction(ruleIndex, actionIndex) {
  6618. LexerAction.call(this, LexerActionType.CUSTOM);
  6619. this.ruleIndex = ruleIndex;
  6620. this.actionIndex = actionIndex;
  6621. this.isPositionDependent = true;
  6622. return this;
  6623. }
  6624. LexerCustomAction.prototype = Object.create(LexerAction.prototype);
  6625. LexerCustomAction.prototype.constructor = LexerCustomAction;
  6626. // <p>Custom actions are implemented by calling {@link Lexer//action} with the
  6627. // appropriate rule and action indexes.</p>
  6628. LexerCustomAction.prototype.execute = function(lexer) {
  6629. lexer.action(null, this.ruleIndex, this.actionIndex);
  6630. };
  6631. LexerCustomAction.prototype.updateHashCode = function(hash) {
  6632. hash.update(this.actionType, this.ruleIndex, this.actionIndex);
  6633. };
  6634. LexerCustomAction.prototype.equals = function(other) {
  6635. if (this === other) {
  6636. return true;
  6637. } else if (! (other instanceof LexerCustomAction)) {
  6638. return false;
  6639. } else {
  6640. return this.ruleIndex === other.ruleIndex && this.actionIndex === other.actionIndex;
  6641. }
  6642. };
  6643. // Implements the {@code channel} lexer action by calling
  6644. // {@link Lexer//setChannel} with the assigned channel.
  6645. // Constructs a new {@code channel} action with the specified channel value.
  6646. // @param channel The channel value to pass to {@link Lexer//setChannel}.
  6647. function LexerChannelAction(channel) {
  6648. LexerAction.call(this, LexerActionType.CHANNEL);
  6649. this.channel = channel;
  6650. return this;
  6651. }
  6652. LexerChannelAction.prototype = Object.create(LexerAction.prototype);
  6653. LexerChannelAction.prototype.constructor = LexerChannelAction;
  6654. // <p>This action is implemented by calling {@link Lexer//setChannel} with the
  6655. // value provided by {@link //getChannel}.</p>
  6656. LexerChannelAction.prototype.execute = function(lexer) {
  6657. lexer._channel = this.channel;
  6658. };
  6659. LexerChannelAction.prototype.updateHashCode = function(hash) {
  6660. hash.update(this.actionType, this.channel);
  6661. };
  6662. LexerChannelAction.prototype.equals = function(other) {
  6663. if (this === other) {
  6664. return true;
  6665. } else if (! (other instanceof LexerChannelAction)) {
  6666. return false;
  6667. } else {
  6668. return this.channel === other.channel;
  6669. }
  6670. };
  6671. LexerChannelAction.prototype.toString = function() {
  6672. return "channel(" + this.channel + ")";
  6673. };
  6674. // This implementation of {@link LexerAction} is used for tracking input offsets
  6675. // for position-dependent actions within a {@link LexerActionExecutor}.
  6676. //
  6677. // <p>This action is not serialized as part of the ATN, and is only required for
  6678. // position-dependent lexer actions which appear at a location other than the
  6679. // end of a rule. For more information about DFA optimizations employed for
  6680. // lexer actions, see {@link LexerActionExecutor//append} and
  6681. // {@link LexerActionExecutor//fixOffsetBeforeMatch}.</p>
  6682. // Constructs a new indexed custom action by associating a character offset
  6683. // with a {@link LexerAction}.
  6684. //
  6685. // <p>Note: This class is only required for lexer actions for which
  6686. // {@link LexerAction//isPositionDependent} returns {@code true}.</p>
  6687. //
  6688. // @param offset The offset into the input {@link CharStream}, relative to
  6689. // the token start index, at which the specified lexer action should be
  6690. // executed.
  6691. // @param action The lexer action to execute at a particular offset in the
  6692. // input {@link CharStream}.
  6693. function LexerIndexedCustomAction(offset, action) {
  6694. LexerAction.call(this, action.actionType);
  6695. this.offset = offset;
  6696. this.action = action;
  6697. this.isPositionDependent = true;
  6698. return this;
  6699. }
  6700. LexerIndexedCustomAction.prototype = Object.create(LexerAction.prototype);
  6701. LexerIndexedCustomAction.prototype.constructor = LexerIndexedCustomAction;
  6702. // <p>This method calls {@link //execute} on the result of {@link //getAction}
  6703. // using the provided {@code lexer}.</p>
  6704. LexerIndexedCustomAction.prototype.execute = function(lexer) {
  6705. // assume the input stream position was properly set by the calling code
  6706. this.action.execute(lexer);
  6707. };
  6708. LexerIndexedCustomAction.prototype.updateHashCode = function(hash) {
  6709. hash.update(this.actionType, this.offset, this.action);
  6710. };
  6711. LexerIndexedCustomAction.prototype.equals = function(other) {
  6712. if (this === other) {
  6713. return true;
  6714. } else if (! (other instanceof LexerIndexedCustomAction)) {
  6715. return false;
  6716. } else {
  6717. return this.offset === other.offset && this.action === other.action;
  6718. }
  6719. };
  6720. exports.LexerActionType = LexerActionType;
  6721. exports.LexerSkipAction = LexerSkipAction;
  6722. exports.LexerChannelAction = LexerChannelAction;
  6723. exports.LexerCustomAction = LexerCustomAction;
  6724. exports.LexerIndexedCustomAction = LexerIndexedCustomAction;
  6725. exports.LexerMoreAction = LexerMoreAction;
  6726. exports.LexerTypeAction = LexerTypeAction;
  6727. exports.LexerPushModeAction = LexerPushModeAction;
  6728. exports.LexerPopModeAction = LexerPopModeAction;
  6729. exports.LexerModeAction = LexerModeAction;
  6730. /***/ }),
  6731. /***/ "./node_modules/antlr4/atn/LexerActionExecutor.js":
  6732. /*!********************************************************!*\
  6733. !*** ./node_modules/antlr4/atn/LexerActionExecutor.js ***!
  6734. \********************************************************/
  6735. /*! no static exports found */
  6736. /***/ (function(module, exports, __webpack_require__) {
  6737. //
  6738. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  6739. * Use of this file is governed by the BSD 3-clause license that
  6740. * can be found in the LICENSE.txt file in the project root.
  6741. */
  6742. ///
  6743. // Represents an executor for a sequence of lexer actions which traversed during
  6744. // the matching operation of a lexer rule (token).
  6745. //
  6746. // <p>The executor tracks position information for position-dependent lexer actions
  6747. // efficiently, ensuring that actions appearing only at the end of the rule do
  6748. // not cause bloating of the {@link DFA} created for the lexer.</p>
  6749. var hashStuff = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").hashStuff;
  6750. var LexerIndexedCustomAction = __webpack_require__(/*! ./LexerAction */ "./node_modules/antlr4/atn/LexerAction.js").LexerIndexedCustomAction;
  6751. function LexerActionExecutor(lexerActions) {
  6752. this.lexerActions = lexerActions === null ? [] : lexerActions;
  6753. // Caches the result of {@link //hashCode} since the hash code is an element
  6754. // of the performance-critical {@link LexerATNConfig//hashCode} operation.
  6755. this.cachedHashCode = hashStuff(lexerActions); // "".join([str(la) for la in
  6756. // lexerActions]))
  6757. return this;
  6758. }
  6759. // Creates a {@link LexerActionExecutor} which executes the actions for
  6760. // the input {@code lexerActionExecutor} followed by a specified
  6761. // {@code lexerAction}.
  6762. //
  6763. // @param lexerActionExecutor The executor for actions already traversed by
  6764. // the lexer while matching a token within a particular
  6765. // {@link LexerATNConfig}. If this is {@code null}, the method behaves as
  6766. // though it were an empty executor.
  6767. // @param lexerAction The lexer action to execute after the actions
  6768. // specified in {@code lexerActionExecutor}.
  6769. //
  6770. // @return A {@link LexerActionExecutor} for executing the combine actions
  6771. // of {@code lexerActionExecutor} and {@code lexerAction}.
  6772. LexerActionExecutor.append = function(lexerActionExecutor, lexerAction) {
  6773. if (lexerActionExecutor === null) {
  6774. return new LexerActionExecutor([ lexerAction ]);
  6775. }
  6776. var lexerActions = lexerActionExecutor.lexerActions.concat([ lexerAction ]);
  6777. return new LexerActionExecutor(lexerActions);
  6778. };
  6779. // Creates a {@link LexerActionExecutor} which encodes the current offset
  6780. // for position-dependent lexer actions.
  6781. //
  6782. // <p>Normally, when the executor encounters lexer actions where
  6783. // {@link LexerAction//isPositionDependent} returns {@code true}, it calls
  6784. // {@link IntStream//seek} on the input {@link CharStream} to set the input
  6785. // position to the <em>end</em> of the current token. This behavior provides
  6786. // for efficient DFA representation of lexer actions which appear at the end
  6787. // of a lexer rule, even when the lexer rule matches a variable number of
  6788. // characters.</p>
  6789. //
  6790. // <p>Prior to traversing a match transition in the ATN, the current offset
  6791. // from the token start index is assigned to all position-dependent lexer
  6792. // actions which have not already been assigned a fixed offset. By storing
  6793. // the offsets relative to the token start index, the DFA representation of
  6794. // lexer actions which appear in the middle of tokens remains efficient due
  6795. // to sharing among tokens of the same length, regardless of their absolute
  6796. // position in the input stream.</p>
  6797. //
  6798. // <p>If the current executor already has offsets assigned to all
  6799. // position-dependent lexer actions, the method returns {@code this}.</p>
  6800. //
  6801. // @param offset The current offset to assign to all position-dependent
  6802. // lexer actions which do not already have offsets assigned.
  6803. //
  6804. // @return A {@link LexerActionExecutor} which stores input stream offsets
  6805. // for all position-dependent lexer actions.
  6806. // /
  6807. LexerActionExecutor.prototype.fixOffsetBeforeMatch = function(offset) {
  6808. var updatedLexerActions = null;
  6809. for (var i = 0; i < this.lexerActions.length; i++) {
  6810. if (this.lexerActions[i].isPositionDependent &&
  6811. !(this.lexerActions[i] instanceof LexerIndexedCustomAction)) {
  6812. if (updatedLexerActions === null) {
  6813. updatedLexerActions = this.lexerActions.concat([]);
  6814. }
  6815. updatedLexerActions[i] = new LexerIndexedCustomAction(offset,
  6816. this.lexerActions[i]);
  6817. }
  6818. }
  6819. if (updatedLexerActions === null) {
  6820. return this;
  6821. } else {
  6822. return new LexerActionExecutor(updatedLexerActions);
  6823. }
  6824. };
  6825. // Execute the actions encapsulated by this executor within the context of a
  6826. // particular {@link Lexer}.
  6827. //
  6828. // <p>This method calls {@link IntStream//seek} to set the position of the
  6829. // {@code input} {@link CharStream} prior to calling
  6830. // {@link LexerAction//execute} on a position-dependent action. Before the
  6831. // method returns, the input position will be restored to the same position
  6832. // it was in when the method was invoked.</p>
  6833. //
  6834. // @param lexer The lexer instance.
  6835. // @param input The input stream which is the source for the current token.
  6836. // When this method is called, the current {@link IntStream//index} for
  6837. // {@code input} should be the start of the following token, i.e. 1
  6838. // character past the end of the current token.
  6839. // @param startIndex The token start index. This value may be passed to
  6840. // {@link IntStream//seek} to set the {@code input} position to the beginning
  6841. // of the token.
  6842. // /
  6843. LexerActionExecutor.prototype.execute = function(lexer, input, startIndex) {
  6844. var requiresSeek = false;
  6845. var stopIndex = input.index;
  6846. try {
  6847. for (var i = 0; i < this.lexerActions.length; i++) {
  6848. var lexerAction = this.lexerActions[i];
  6849. if (lexerAction instanceof LexerIndexedCustomAction) {
  6850. var offset = lexerAction.offset;
  6851. input.seek(startIndex + offset);
  6852. lexerAction = lexerAction.action;
  6853. requiresSeek = (startIndex + offset) !== stopIndex;
  6854. } else if (lexerAction.isPositionDependent) {
  6855. input.seek(stopIndex);
  6856. requiresSeek = false;
  6857. }
  6858. lexerAction.execute(lexer);
  6859. }
  6860. } finally {
  6861. if (requiresSeek) {
  6862. input.seek(stopIndex);
  6863. }
  6864. }
  6865. };
  6866. LexerActionExecutor.prototype.hashCode = function() {
  6867. return this.cachedHashCode;
  6868. };
  6869. LexerActionExecutor.prototype.updateHashCode = function(hash) {
  6870. hash.update(this.cachedHashCode);
  6871. };
  6872. LexerActionExecutor.prototype.equals = function(other) {
  6873. if (this === other) {
  6874. return true;
  6875. } else if (!(other instanceof LexerActionExecutor)) {
  6876. return false;
  6877. } else if (this.cachedHashCode != other.cachedHashCode) {
  6878. return false;
  6879. } else if (this.lexerActions.length != other.lexerActions.length) {
  6880. return false;
  6881. } else {
  6882. var numActions = this.lexerActions.length
  6883. for (var idx = 0; idx < numActions; ++idx) {
  6884. if (!this.lexerActions[idx].equals(other.lexerActions[idx])) {
  6885. return false;
  6886. }
  6887. }
  6888. return true;
  6889. }
  6890. };
  6891. exports.LexerActionExecutor = LexerActionExecutor;
  6892. /***/ }),
  6893. /***/ "./node_modules/antlr4/atn/ParserATNSimulator.js":
  6894. /*!*******************************************************!*\
  6895. !*** ./node_modules/antlr4/atn/ParserATNSimulator.js ***!
  6896. \*******************************************************/
  6897. /*! no static exports found */
  6898. /***/ (function(module, exports, __webpack_require__) {
  6899. //
  6900. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  6901. * Use of this file is governed by the BSD 3-clause license that
  6902. * can be found in the LICENSE.txt file in the project root.
  6903. */
  6904. //
  6905. //
  6906. // The embodiment of the adaptive LL(*), ALL(*), parsing strategy.
  6907. //
  6908. // <p>
  6909. // The basic complexity of the adaptive strategy makes it harder to understand.
  6910. // We begin with ATN simulation to build paths in a DFA. Subsequent prediction
  6911. // requests go through the DFA first. If they reach a state without an edge for
  6912. // the current symbol, the algorithm fails over to the ATN simulation to
  6913. // complete the DFA path for the current input (until it finds a conflict state
  6914. // or uniquely predicting state).</p>
  6915. //
  6916. // <p>
  6917. // All of that is done without using the outer context because we want to create
  6918. // a DFA that is not dependent upon the rule invocation stack when we do a
  6919. // prediction. One DFA works in all contexts. We avoid using context not
  6920. // necessarily because it's slower, although it can be, but because of the DFA
  6921. // caching problem. The closure routine only considers the rule invocation stack
  6922. // created during prediction beginning in the decision rule. For example, if
  6923. // prediction occurs without invoking another rule's ATN, there are no context
  6924. // stacks in the configurations. When lack of context leads to a conflict, we
  6925. // don't know if it's an ambiguity or a weakness in the strong LL(*) parsing
  6926. // strategy (versus full LL(*)).</p>
  6927. //
  6928. // <p>
  6929. // When SLL yields a configuration set with conflict, we rewind the input and
  6930. // retry the ATN simulation, this time using full outer context without adding
  6931. // to the DFA. Configuration context stacks will be the full invocation stacks
  6932. // from the start rule. If we get a conflict using full context, then we can
  6933. // definitively say we have a true ambiguity for that input sequence. If we
  6934. // don't get a conflict, it implies that the decision is sensitive to the outer
  6935. // context. (It is not context-sensitive in the sense of context-sensitive
  6936. // grammars.)</p>
  6937. //
  6938. // <p>
  6939. // The next time we reach this DFA state with an SLL conflict, through DFA
  6940. // simulation, we will again retry the ATN simulation using full context mode.
  6941. // This is slow because we can't save the results and have to "interpret" the
  6942. // ATN each time we get that input.</p>
  6943. //
  6944. // <p>
  6945. // <strong>CACHING FULL CONTEXT PREDICTIONS</strong></p>
  6946. //
  6947. // <p>
  6948. // We could cache results from full context to predicted alternative easily and
  6949. // that saves a lot of time but doesn't work in presence of predicates. The set
  6950. // of visible predicates from the ATN start state changes depending on the
  6951. // context, because closure can fall off the end of a rule. I tried to cache
  6952. // tuples (stack context, semantic context, predicted alt) but it was slower
  6953. // than interpreting and much more complicated. Also required a huge amount of
  6954. // memory. The goal is not to create the world's fastest parser anyway. I'd like
  6955. // to keep this algorithm simple. By launching multiple threads, we can improve
  6956. // the speed of parsing across a large number of files.</p>
  6957. //
  6958. // <p>
  6959. // There is no strict ordering between the amount of input used by SLL vs LL,
  6960. // which makes it really hard to build a cache for full context. Let's say that
  6961. // we have input A B C that leads to an SLL conflict with full context X. That
  6962. // implies that using X we might only use A B but we could also use A B C D to
  6963. // resolve conflict. Input A B C D could predict alternative 1 in one position
  6964. // in the input and A B C E could predict alternative 2 in another position in
  6965. // input. The conflicting SLL configurations could still be non-unique in the
  6966. // full context prediction, which would lead us to requiring more input than the
  6967. // original A B C. To make a prediction cache work, we have to track the exact
  6968. // input used during the previous prediction. That amounts to a cache that maps
  6969. // X to a specific DFA for that context.</p>
  6970. //
  6971. // <p>
  6972. // Something should be done for left-recursive expression predictions. They are
  6973. // likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry
  6974. // with full LL thing Sam does.</p>
  6975. //
  6976. // <p>
  6977. // <strong>AVOIDING FULL CONTEXT PREDICTION</strong></p>
  6978. //
  6979. // <p>
  6980. // We avoid doing full context retry when the outer context is empty, we did not
  6981. // dip into the outer context by falling off the end of the decision state rule,
  6982. // or when we force SLL mode.</p>
  6983. //
  6984. // <p>
  6985. // As an example of the not dip into outer context case, consider as super
  6986. // constructor calls versus function calls. One grammar might look like
  6987. // this:</p>
  6988. //
  6989. // <pre>
  6990. // ctorBody
  6991. // : '{' superCall? stat* '}'
  6992. // ;
  6993. // </pre>
  6994. //
  6995. // <p>
  6996. // Or, you might see something like</p>
  6997. //
  6998. // <pre>
  6999. // stat
  7000. // : superCall ';'
  7001. // | expression ';'
  7002. // | ...
  7003. // ;
  7004. // </pre>
  7005. //
  7006. // <p>
  7007. // In both cases I believe that no closure operations will dip into the outer
  7008. // context. In the first case ctorBody in the worst case will stop at the '}'.
  7009. // In the 2nd case it should stop at the ';'. Both cases should stay within the
  7010. // entry rule and not dip into the outer context.</p>
  7011. //
  7012. // <p>
  7013. // <strong>PREDICATES</strong></p>
  7014. //
  7015. // <p>
  7016. // Predicates are always evaluated if present in either SLL or LL both. SLL and
  7017. // LL simulation deals with predicates differently. SLL collects predicates as
  7018. // it performs closure operations like ANTLR v3 did. It delays predicate
  7019. // evaluation until it reaches and accept state. This allows us to cache the SLL
  7020. // ATN simulation whereas, if we had evaluated predicates on-the-fly during
  7021. // closure, the DFA state configuration sets would be different and we couldn't
  7022. // build up a suitable DFA.</p>
  7023. //
  7024. // <p>
  7025. // When building a DFA accept state during ATN simulation, we evaluate any
  7026. // predicates and return the sole semantically valid alternative. If there is
  7027. // more than 1 alternative, we report an ambiguity. If there are 0 alternatives,
  7028. // we throw an exception. Alternatives without predicates act like they have
  7029. // true predicates. The simple way to think about it is to strip away all
  7030. // alternatives with false predicates and choose the minimum alternative that
  7031. // remains.</p>
  7032. //
  7033. // <p>
  7034. // When we start in the DFA and reach an accept state that's predicated, we test
  7035. // those and return the minimum semantically viable alternative. If no
  7036. // alternatives are viable, we throw an exception.</p>
  7037. //
  7038. // <p>
  7039. // During full LL ATN simulation, closure always evaluates predicates and
  7040. // on-the-fly. This is crucial to reducing the configuration set size during
  7041. // closure. It hits a landmine when parsing with the Java grammar, for example,
  7042. // without this on-the-fly evaluation.</p>
  7043. //
  7044. // <p>
  7045. // <strong>SHARING DFA</strong></p>
  7046. //
  7047. // <p>
  7048. // All instances of the same parser share the same decision DFAs through a
  7049. // static field. Each instance gets its own ATN simulator but they share the
  7050. // same {@link //decisionToDFA} field. They also share a
  7051. // {@link PredictionContextCache} object that makes sure that all
  7052. // {@link PredictionContext} objects are shared among the DFA states. This makes
  7053. // a big size difference.</p>
  7054. //
  7055. // <p>
  7056. // <strong>THREAD SAFETY</strong></p>
  7057. //
  7058. // <p>
  7059. // The {@link ParserATNSimulator} locks on the {@link //decisionToDFA} field when
  7060. // it adds a new DFA object to that array. {@link //addDFAEdge}
  7061. // locks on the DFA for the current decision when setting the
  7062. // {@link DFAState//edges} field. {@link //addDFAState} locks on
  7063. // the DFA for the current decision when looking up a DFA state to see if it
  7064. // already exists. We must make sure that all requests to add DFA states that
  7065. // are equivalent result in the same shared DFA object. This is because lots of
  7066. // threads will be trying to update the DFA at once. The
  7067. // {@link //addDFAState} method also locks inside the DFA lock
  7068. // but this time on the shared context cache when it rebuilds the
  7069. // configurations' {@link PredictionContext} objects using cached
  7070. // subgraphs/nodes. No other locking occurs, even during DFA simulation. This is
  7071. // safe as long as we can guarantee that all threads referencing
  7072. // {@code s.edge[t]} get the same physical target {@link DFAState}, or
  7073. // {@code null}. Once into the DFA, the DFA simulation does not reference the
  7074. // {@link DFA//states} map. It follows the {@link DFAState//edges} field to new
  7075. // targets. The DFA simulator will either find {@link DFAState//edges} to be
  7076. // {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or
  7077. // {@code dfa.edges[t]} to be non-null. The
  7078. // {@link //addDFAEdge} method could be racing to set the field
  7079. // but in either case the DFA simulator works; if {@code null}, and requests ATN
  7080. // simulation. It could also race trying to get {@code dfa.edges[t]}, but either
  7081. // way it will work because it's not doing a test and set operation.</p>
  7082. //
  7083. // <p>
  7084. // <strong>Starting with SLL then failing to combined SLL/LL (Two-Stage
  7085. // Parsing)</strong></p>
  7086. //
  7087. // <p>
  7088. // Sam pointed out that if SLL does not give a syntax error, then there is no
  7089. // point in doing full LL, which is slower. We only have to try LL if we get a
  7090. // syntax error. For maximum speed, Sam starts the parser set to pure SLL
  7091. // mode with the {@link BailErrorStrategy}:</p>
  7092. //
  7093. // <pre>
  7094. // parser.{@link Parser//getInterpreter() getInterpreter()}.{@link //setPredictionMode setPredictionMode}{@code (}{@link PredictionMode//SLL}{@code )};
  7095. // parser.{@link Parser//setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());
  7096. // </pre>
  7097. //
  7098. // <p>
  7099. // If it does not get a syntax error, then we're done. If it does get a syntax
  7100. // error, we need to retry with the combined SLL/LL strategy.</p>
  7101. //
  7102. // <p>
  7103. // The reason this works is as follows. If there are no SLL conflicts, then the
  7104. // grammar is SLL (at least for that input set). If there is an SLL conflict,
  7105. // the full LL analysis must yield a set of viable alternatives which is a
  7106. // subset of the alternatives reported by SLL. If the LL set is a singleton,
  7107. // then the grammar is LL but not SLL. If the LL set is the same size as the SLL
  7108. // set, the decision is SLL. If the LL set has size &gt; 1, then that decision
  7109. // is truly ambiguous on the current input. If the LL set is smaller, then the
  7110. // SLL conflict resolution might choose an alternative that the full LL would
  7111. // rule out as a possibility based upon better context information. If that's
  7112. // the case, then the SLL parse will definitely get an error because the full LL
  7113. // analysis says it's not viable. If SLL conflict resolution chooses an
  7114. // alternative within the LL set, them both SLL and LL would choose the same
  7115. // alternative because they both choose the minimum of multiple conflicting
  7116. // alternatives.</p>
  7117. //
  7118. // <p>
  7119. // Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and
  7120. // a smaller LL set called <em>s</em>. If <em>s</em> is {@code {2, 3}}, then SLL
  7121. // parsing will get an error because SLL will pursue alternative 1. If
  7122. // <em>s</em> is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will
  7123. // choose the same alternative because alternative one is the minimum of either
  7124. // set. If <em>s</em> is {@code {2}} or {@code {3}} then SLL will get a syntax
  7125. // error. If <em>s</em> is {@code {1}} then SLL will succeed.</p>
  7126. //
  7127. // <p>
  7128. // Of course, if the input is invalid, then we will get an error for sure in
  7129. // both SLL and LL parsing. Erroneous input will therefore require 2 passes over
  7130. // the input.</p>
  7131. //
  7132. var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
  7133. var Set = Utils.Set;
  7134. var BitSet = Utils.BitSet;
  7135. var DoubleDict = Utils.DoubleDict;
  7136. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  7137. var ATNState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").ATNState;
  7138. var ATNConfig = __webpack_require__(/*! ./ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").ATNConfig;
  7139. var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  7140. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  7141. var DFAState = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
  7142. var PredPrediction = __webpack_require__(/*! ./../dfa/DFAState */ "./node_modules/antlr4/dfa/DFAState.js").PredPrediction;
  7143. var ATNSimulator = __webpack_require__(/*! ./ATNSimulator */ "./node_modules/antlr4/atn/ATNSimulator.js").ATNSimulator;
  7144. var PredictionMode = __webpack_require__(/*! ./PredictionMode */ "./node_modules/antlr4/atn/PredictionMode.js").PredictionMode;
  7145. var RuleContext = __webpack_require__(/*! ./../RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
  7146. var ParserRuleContext = __webpack_require__(/*! ./../ParserRuleContext */ "./node_modules/antlr4/ParserRuleContext.js").ParserRuleContext;
  7147. var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
  7148. var StarLoopEntryState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").StarLoopEntryState;
  7149. var RuleStopState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
  7150. var PredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").PredictionContext;
  7151. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  7152. var Transitions = __webpack_require__(/*! ./Transition */ "./node_modules/antlr4/atn/Transition.js");
  7153. var Transition = Transitions.Transition;
  7154. var SetTransition = Transitions.SetTransition;
  7155. var NotSetTransition = Transitions.NotSetTransition;
  7156. var RuleTransition = Transitions.RuleTransition;
  7157. var ActionTransition = Transitions.ActionTransition;
  7158. var NoViableAltException = __webpack_require__(/*! ./../error/Errors */ "./node_modules/antlr4/error/Errors.js").NoViableAltException;
  7159. var SingletonPredictionContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").SingletonPredictionContext;
  7160. var predictionContextFromRuleContext = __webpack_require__(/*! ./../PredictionContext */ "./node_modules/antlr4/PredictionContext.js").predictionContextFromRuleContext;
  7161. function ParserATNSimulator(parser, atn, decisionToDFA, sharedContextCache) {
  7162. ATNSimulator.call(this, atn, sharedContextCache);
  7163. this.parser = parser;
  7164. this.decisionToDFA = decisionToDFA;
  7165. // SLL, LL, or LL + exact ambig detection?//
  7166. this.predictionMode = PredictionMode.LL;
  7167. // LAME globals to avoid parameters!!!!! I need these down deep in predTransition
  7168. this._input = null;
  7169. this._startIndex = 0;
  7170. this._outerContext = null;
  7171. this._dfa = null;
  7172. // Each prediction operation uses a cache for merge of prediction contexts.
  7173. // Don't keep around as it wastes huge amounts of memory. DoubleKeyMap
  7174. // isn't synchronized but we're ok since two threads shouldn't reuse same
  7175. // parser/atnsim object because it can only handle one input at a time.
  7176. // This maps graphs a and b to merged result c. (a,b)&rarr;c. We can avoid
  7177. // the merge if we ever see a and b again. Note that (b,a)&rarr;c should
  7178. // also be examined during cache lookup.
  7179. //
  7180. this.mergeCache = null;
  7181. return this;
  7182. }
  7183. ParserATNSimulator.prototype = Object.create(ATNSimulator.prototype);
  7184. ParserATNSimulator.prototype.constructor = ParserATNSimulator;
  7185. ParserATNSimulator.prototype.debug = false;
  7186. ParserATNSimulator.prototype.debug_closure = false;
  7187. ParserATNSimulator.prototype.debug_add = false;
  7188. ParserATNSimulator.prototype.debug_list_atn_decisions = false;
  7189. ParserATNSimulator.prototype.dfa_debug = false;
  7190. ParserATNSimulator.prototype.retry_debug = false;
  7191. ParserATNSimulator.prototype.reset = function() {
  7192. };
  7193. ParserATNSimulator.prototype.adaptivePredict = function(input, decision, outerContext) {
  7194. if (this.debug || this.debug_list_atn_decisions) {
  7195. console.log("adaptivePredict decision " + decision +
  7196. " exec LA(1)==" + this.getLookaheadName(input) +
  7197. " line " + input.LT(1).line + ":" +
  7198. input.LT(1).column);
  7199. }
  7200. this._input = input;
  7201. this._startIndex = input.index;
  7202. this._outerContext = outerContext;
  7203. var dfa = this.decisionToDFA[decision];
  7204. this._dfa = dfa;
  7205. var m = input.mark();
  7206. var index = input.index;
  7207. // Now we are certain to have a specific decision's DFA
  7208. // But, do we still need an initial state?
  7209. try {
  7210. var s0;
  7211. if (dfa.precedenceDfa) {
  7212. // the start state for a precedence DFA depends on the current
  7213. // parser precedence, and is provided by a DFA method.
  7214. s0 = dfa.getPrecedenceStartState(this.parser.getPrecedence());
  7215. } else {
  7216. // the start state for a "regular" DFA is just s0
  7217. s0 = dfa.s0;
  7218. }
  7219. if (s0===null) {
  7220. if (outerContext===null) {
  7221. outerContext = RuleContext.EMPTY;
  7222. }
  7223. if (this.debug || this.debug_list_atn_decisions) {
  7224. console.log("predictATN decision " + dfa.decision +
  7225. " exec LA(1)==" + this.getLookaheadName(input) +
  7226. ", outerContext=" + outerContext.toString(this.parser.ruleNames));
  7227. }
  7228. var fullCtx = false;
  7229. var s0_closure = this.computeStartState(dfa.atnStartState, RuleContext.EMPTY, fullCtx);
  7230. if( dfa.precedenceDfa) {
  7231. // If this is a precedence DFA, we use applyPrecedenceFilter
  7232. // to convert the computed start state to a precedence start
  7233. // state. We then use DFA.setPrecedenceStartState to set the
  7234. // appropriate start state for the precedence level rather
  7235. // than simply setting DFA.s0.
  7236. //
  7237. dfa.s0.configs = s0_closure; // not used for prediction but useful to know start configs anyway
  7238. s0_closure = this.applyPrecedenceFilter(s0_closure);
  7239. s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
  7240. dfa.setPrecedenceStartState(this.parser.getPrecedence(), s0);
  7241. } else {
  7242. s0 = this.addDFAState(dfa, new DFAState(null, s0_closure));
  7243. dfa.s0 = s0;
  7244. }
  7245. }
  7246. var alt = this.execATN(dfa, s0, input, index, outerContext);
  7247. if (this.debug) {
  7248. console.log("DFA after predictATN: " + dfa.toString(this.parser.literalNames));
  7249. }
  7250. return alt;
  7251. } finally {
  7252. this._dfa = null;
  7253. this.mergeCache = null; // wack cache after each prediction
  7254. input.seek(index);
  7255. input.release(m);
  7256. }
  7257. };
  7258. // Performs ATN simulation to compute a predicted alternative based
  7259. // upon the remaining input, but also updates the DFA cache to avoid
  7260. // having to traverse the ATN again for the same input sequence.
  7261. // There are some key conditions we're looking for after computing a new
  7262. // set of ATN configs (proposed DFA state):
  7263. // if the set is empty, there is no viable alternative for current symbol
  7264. // does the state uniquely predict an alternative?
  7265. // does the state have a conflict that would prevent us from
  7266. // putting it on the work list?
  7267. // We also have some key operations to do:
  7268. // add an edge from previous DFA state to potentially new DFA state, D,
  7269. // upon current symbol but only if adding to work list, which means in all
  7270. // cases except no viable alternative (and possibly non-greedy decisions?)
  7271. // collecting predicates and adding semantic context to DFA accept states
  7272. // adding rule context to context-sensitive DFA accept states
  7273. // consuming an input symbol
  7274. // reporting a conflict
  7275. // reporting an ambiguity
  7276. // reporting a context sensitivity
  7277. // reporting insufficient predicates
  7278. // cover these cases:
  7279. // dead end
  7280. // single alt
  7281. // single alt + preds
  7282. // conflict
  7283. // conflict + preds
  7284. //
  7285. ParserATNSimulator.prototype.execATN = function(dfa, s0, input, startIndex, outerContext ) {
  7286. if (this.debug || this.debug_list_atn_decisions) {
  7287. console.log("execATN decision " + dfa.decision +
  7288. " exec LA(1)==" + this.getLookaheadName(input) +
  7289. " line " + input.LT(1).line + ":" + input.LT(1).column);
  7290. }
  7291. var alt;
  7292. var previousD = s0;
  7293. if (this.debug) {
  7294. console.log("s0 = " + s0);
  7295. }
  7296. var t = input.LA(1);
  7297. while(true) { // while more work
  7298. var D = this.getExistingTargetState(previousD, t);
  7299. if(D===null) {
  7300. D = this.computeTargetState(dfa, previousD, t);
  7301. }
  7302. if(D===ATNSimulator.ERROR) {
  7303. // if any configs in previous dipped into outer context, that
  7304. // means that input up to t actually finished entry rule
  7305. // at least for SLL decision. Full LL doesn't dip into outer
  7306. // so don't need special case.
  7307. // We will get an error no matter what so delay until after
  7308. // decision; better error message. Also, no reachable target
  7309. // ATN states in SLL implies LL will also get nowhere.
  7310. // If conflict in states that dip out, choose min since we
  7311. // will get error no matter what.
  7312. var e = this.noViableAlt(input, outerContext, previousD.configs, startIndex);
  7313. input.seek(startIndex);
  7314. alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext);
  7315. if(alt!==ATN.INVALID_ALT_NUMBER) {
  7316. return alt;
  7317. } else {
  7318. throw e;
  7319. }
  7320. }
  7321. if(D.requiresFullContext && this.predictionMode !== PredictionMode.SLL) {
  7322. // IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error)
  7323. var conflictingAlts = null;
  7324. if (D.predicates!==null) {
  7325. if (this.debug) {
  7326. console.log("DFA state has preds in DFA sim LL failover");
  7327. }
  7328. var conflictIndex = input.index;
  7329. if(conflictIndex !== startIndex) {
  7330. input.seek(startIndex);
  7331. }
  7332. conflictingAlts = this.evalSemanticContext(D.predicates, outerContext, true);
  7333. if (conflictingAlts.length===1) {
  7334. if(this.debug) {
  7335. console.log("Full LL avoided");
  7336. }
  7337. return conflictingAlts.minValue();
  7338. }
  7339. if (conflictIndex !== startIndex) {
  7340. // restore the index so reporting the fallback to full
  7341. // context occurs with the index at the correct spot
  7342. input.seek(conflictIndex);
  7343. }
  7344. }
  7345. if (this.dfa_debug) {
  7346. console.log("ctx sensitive state " + outerContext +" in " + D);
  7347. }
  7348. var fullCtx = true;
  7349. var s0_closure = this.computeStartState(dfa.atnStartState, outerContext, fullCtx);
  7350. this.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index);
  7351. alt = this.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext);
  7352. return alt;
  7353. }
  7354. if (D.isAcceptState) {
  7355. if (D.predicates===null) {
  7356. return D.prediction;
  7357. }
  7358. var stopIndex = input.index;
  7359. input.seek(startIndex);
  7360. var alts = this.evalSemanticContext(D.predicates, outerContext, true);
  7361. if (alts.length===0) {
  7362. throw this.noViableAlt(input, outerContext, D.configs, startIndex);
  7363. } else if (alts.length===1) {
  7364. return alts.minValue();
  7365. } else {
  7366. // report ambiguity after predicate evaluation to make sure the correct set of ambig alts is reported.
  7367. this.reportAmbiguity(dfa, D, startIndex, stopIndex, false, alts, D.configs);
  7368. return alts.minValue();
  7369. }
  7370. }
  7371. previousD = D;
  7372. if (t !== Token.EOF) {
  7373. input.consume();
  7374. t = input.LA(1);
  7375. }
  7376. }
  7377. };
  7378. //
  7379. // Get an existing target state for an edge in the DFA. If the target state
  7380. // for the edge has not yet been computed or is otherwise not available,
  7381. // this method returns {@code null}.
  7382. //
  7383. // @param previousD The current DFA state
  7384. // @param t The next input symbol
  7385. // @return The existing target DFA state for the given input symbol
  7386. // {@code t}, or {@code null} if the target state for this edge is not
  7387. // already cached
  7388. //
  7389. ParserATNSimulator.prototype.getExistingTargetState = function(previousD, t) {
  7390. var edges = previousD.edges;
  7391. if (edges===null) {
  7392. return null;
  7393. } else {
  7394. return edges[t + 1] || null;
  7395. }
  7396. };
  7397. //
  7398. // Compute a target state for an edge in the DFA, and attempt to add the
  7399. // computed state and corresponding edge to the DFA.
  7400. //
  7401. // @param dfa The DFA
  7402. // @param previousD The current DFA state
  7403. // @param t The next input symbol
  7404. //
  7405. // @return The computed target DFA state for the given input symbol
  7406. // {@code t}. If {@code t} does not lead to a valid DFA state, this method
  7407. // returns {@link //ERROR}.
  7408. //
  7409. ParserATNSimulator.prototype.computeTargetState = function(dfa, previousD, t) {
  7410. var reach = this.computeReachSet(previousD.configs, t, false);
  7411. if(reach===null) {
  7412. this.addDFAEdge(dfa, previousD, t, ATNSimulator.ERROR);
  7413. return ATNSimulator.ERROR;
  7414. }
  7415. // create new target state; we'll add to DFA after it's complete
  7416. var D = new DFAState(null, reach);
  7417. var predictedAlt = this.getUniqueAlt(reach);
  7418. if (this.debug) {
  7419. var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
  7420. console.log("SLL altSubSets=" + Utils.arrayToString(altSubSets) +
  7421. ", previous=" + previousD.configs +
  7422. ", configs=" + reach +
  7423. ", predict=" + predictedAlt +
  7424. ", allSubsetsConflict=" +
  7425. PredictionMode.allSubsetsConflict(altSubSets) + ", conflictingAlts=" +
  7426. this.getConflictingAlts(reach));
  7427. }
  7428. if (predictedAlt!==ATN.INVALID_ALT_NUMBER) {
  7429. // NO CONFLICT, UNIQUELY PREDICTED ALT
  7430. D.isAcceptState = true;
  7431. D.configs.uniqueAlt = predictedAlt;
  7432. D.prediction = predictedAlt;
  7433. } else if (PredictionMode.hasSLLConflictTerminatingPrediction(this.predictionMode, reach)) {
  7434. // MORE THAN ONE VIABLE ALTERNATIVE
  7435. D.configs.conflictingAlts = this.getConflictingAlts(reach);
  7436. D.requiresFullContext = true;
  7437. // in SLL-only mode, we will stop at this state and return the minimum alt
  7438. D.isAcceptState = true;
  7439. D.prediction = D.configs.conflictingAlts.minValue();
  7440. }
  7441. if (D.isAcceptState && D.configs.hasSemanticContext) {
  7442. this.predicateDFAState(D, this.atn.getDecisionState(dfa.decision));
  7443. if( D.predicates!==null) {
  7444. D.prediction = ATN.INVALID_ALT_NUMBER;
  7445. }
  7446. }
  7447. // all adds to dfa are done after we've created full D state
  7448. D = this.addDFAEdge(dfa, previousD, t, D);
  7449. return D;
  7450. };
  7451. ParserATNSimulator.prototype.predicateDFAState = function(dfaState, decisionState) {
  7452. // We need to test all predicates, even in DFA states that
  7453. // uniquely predict alternative.
  7454. var nalts = decisionState.transitions.length;
  7455. // Update DFA so reach becomes accept state with (predicate,alt)
  7456. // pairs if preds found for conflicting alts
  7457. var altsToCollectPredsFrom = this.getConflictingAltsOrUniqueAlt(dfaState.configs);
  7458. var altToPred = this.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts);
  7459. if (altToPred!==null) {
  7460. dfaState.predicates = this.getPredicatePredictions(altsToCollectPredsFrom, altToPred);
  7461. dfaState.prediction = ATN.INVALID_ALT_NUMBER; // make sure we use preds
  7462. } else {
  7463. // There are preds in configs but they might go away
  7464. // when OR'd together like {p}? || NONE == NONE. If neither
  7465. // alt has preds, resolve to min alt
  7466. dfaState.prediction = altsToCollectPredsFrom.minValue();
  7467. }
  7468. };
  7469. // comes back with reach.uniqueAlt set to a valid alt
  7470. ParserATNSimulator.prototype.execATNWithFullContext = function(dfa, D, // how far we got before failing over
  7471. s0,
  7472. input,
  7473. startIndex,
  7474. outerContext) {
  7475. if (this.debug || this.debug_list_atn_decisions) {
  7476. console.log("execATNWithFullContext "+s0);
  7477. }
  7478. var fullCtx = true;
  7479. var foundExactAmbig = false;
  7480. var reach = null;
  7481. var previous = s0;
  7482. input.seek(startIndex);
  7483. var t = input.LA(1);
  7484. var predictedAlt = -1;
  7485. while (true) { // while more work
  7486. reach = this.computeReachSet(previous, t, fullCtx);
  7487. if (reach===null) {
  7488. // if any configs in previous dipped into outer context, that
  7489. // means that input up to t actually finished entry rule
  7490. // at least for LL decision. Full LL doesn't dip into outer
  7491. // so don't need special case.
  7492. // We will get an error no matter what so delay until after
  7493. // decision; better error message. Also, no reachable target
  7494. // ATN states in SLL implies LL will also get nowhere.
  7495. // If conflict in states that dip out, choose min since we
  7496. // will get error no matter what.
  7497. var e = this.noViableAlt(input, outerContext, previous, startIndex);
  7498. input.seek(startIndex);
  7499. var alt = this.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext);
  7500. if(alt!==ATN.INVALID_ALT_NUMBER) {
  7501. return alt;
  7502. } else {
  7503. throw e;
  7504. }
  7505. }
  7506. var altSubSets = PredictionMode.getConflictingAltSubsets(reach);
  7507. if(this.debug) {
  7508. console.log("LL altSubSets=" + altSubSets + ", predict=" +
  7509. PredictionMode.getUniqueAlt(altSubSets) + ", resolvesToJustOneViableAlt=" +
  7510. PredictionMode.resolvesToJustOneViableAlt(altSubSets));
  7511. }
  7512. reach.uniqueAlt = this.getUniqueAlt(reach);
  7513. // unique prediction?
  7514. if(reach.uniqueAlt!==ATN.INVALID_ALT_NUMBER) {
  7515. predictedAlt = reach.uniqueAlt;
  7516. break;
  7517. } else if (this.predictionMode !== PredictionMode.LL_EXACT_AMBIG_DETECTION) {
  7518. predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets);
  7519. if(predictedAlt !== ATN.INVALID_ALT_NUMBER) {
  7520. break;
  7521. }
  7522. } else {
  7523. // In exact ambiguity mode, we never try to terminate early.
  7524. // Just keeps scarfing until we know what the conflict is
  7525. if (PredictionMode.allSubsetsConflict(altSubSets) && PredictionMode.allSubsetsEqual(altSubSets)) {
  7526. foundExactAmbig = true;
  7527. predictedAlt = PredictionMode.getSingleViableAlt(altSubSets);
  7528. break;
  7529. }
  7530. // else there are multiple non-conflicting subsets or
  7531. // we're not sure what the ambiguity is yet.
  7532. // So, keep going.
  7533. }
  7534. previous = reach;
  7535. if( t !== Token.EOF) {
  7536. input.consume();
  7537. t = input.LA(1);
  7538. }
  7539. }
  7540. // If the configuration set uniquely predicts an alternative,
  7541. // without conflict, then we know that it's a full LL decision
  7542. // not SLL.
  7543. if (reach.uniqueAlt !== ATN.INVALID_ALT_NUMBER ) {
  7544. this.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index);
  7545. return predictedAlt;
  7546. }
  7547. // We do not check predicates here because we have checked them
  7548. // on-the-fly when doing full context prediction.
  7549. //
  7550. // In non-exact ambiguity detection mode, we might actually be able to
  7551. // detect an exact ambiguity, but I'm not going to spend the cycles
  7552. // needed to check. We only emit ambiguity warnings in exact ambiguity
  7553. // mode.
  7554. //
  7555. // For example, we might know that we have conflicting configurations.
  7556. // But, that does not mean that there is no way forward without a
  7557. // conflict. It's possible to have nonconflicting alt subsets as in:
  7558. // altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}]
  7559. // from
  7560. //
  7561. // [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]),
  7562. // (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])]
  7563. //
  7564. // In this case, (17,1,[5 $]) indicates there is some next sequence that
  7565. // would resolve this without conflict to alternative 1. Any other viable
  7566. // next sequence, however, is associated with a conflict. We stop
  7567. // looking for input because no amount of further lookahead will alter
  7568. // the fact that we should predict alternative 1. We just can't say for
  7569. // sure that there is an ambiguity without looking further.
  7570. this.reportAmbiguity(dfa, D, startIndex, input.index, foundExactAmbig, null, reach);
  7571. return predictedAlt;
  7572. };
  7573. ParserATNSimulator.prototype.computeReachSet = function(closure, t, fullCtx) {
  7574. if (this.debug) {
  7575. console.log("in computeReachSet, starting closure: " + closure);
  7576. }
  7577. if( this.mergeCache===null) {
  7578. this.mergeCache = new DoubleDict();
  7579. }
  7580. var intermediate = new ATNConfigSet(fullCtx);
  7581. // Configurations already in a rule stop state indicate reaching the end
  7582. // of the decision rule (local context) or end of the start rule (full
  7583. // context). Once reached, these configurations are never updated by a
  7584. // closure operation, so they are handled separately for the performance
  7585. // advantage of having a smaller intermediate set when calling closure.
  7586. //
  7587. // For full-context reach operations, separate handling is required to
  7588. // ensure that the alternative matching the longest overall sequence is
  7589. // chosen when multiple such configurations can match the input.
  7590. var skippedStopStates = null;
  7591. // First figure out where we can reach on input t
  7592. for (var i=0; i<closure.items.length;i++) {
  7593. var c = closure.items[i];
  7594. if(this.debug_add) {
  7595. console.log("testing " + this.getTokenName(t) + " at " + c);
  7596. }
  7597. if (c.state instanceof RuleStopState) {
  7598. if (fullCtx || t === Token.EOF) {
  7599. if (skippedStopStates===null) {
  7600. skippedStopStates = [];
  7601. }
  7602. skippedStopStates.push(c);
  7603. if(this.debug_add) {
  7604. console.log("added " + c + " to skippedStopStates");
  7605. }
  7606. }
  7607. continue;
  7608. }
  7609. for(var j=0;j<c.state.transitions.length;j++) {
  7610. var trans = c.state.transitions[j];
  7611. var target = this.getReachableTarget(trans, t);
  7612. if (target!==null) {
  7613. var cfg = new ATNConfig({state:target}, c);
  7614. intermediate.add(cfg, this.mergeCache);
  7615. if(this.debug_add) {
  7616. console.log("added " + cfg + " to intermediate");
  7617. }
  7618. }
  7619. }
  7620. }
  7621. // Now figure out where the reach operation can take us...
  7622. var reach = null;
  7623. // This block optimizes the reach operation for intermediate sets which
  7624. // trivially indicate a termination state for the overall
  7625. // adaptivePredict operation.
  7626. //
  7627. // The conditions assume that intermediate
  7628. // contains all configurations relevant to the reach set, but this
  7629. // condition is not true when one or more configurations have been
  7630. // withheld in skippedStopStates, or when the current symbol is EOF.
  7631. //
  7632. if (skippedStopStates===null && t!==Token.EOF) {
  7633. if (intermediate.items.length===1) {
  7634. // Don't pursue the closure if there is just one state.
  7635. // It can only have one alternative; just add to result
  7636. // Also don't pursue the closure if there is unique alternative
  7637. // among the configurations.
  7638. reach = intermediate;
  7639. } else if (this.getUniqueAlt(intermediate)!==ATN.INVALID_ALT_NUMBER) {
  7640. // Also don't pursue the closure if there is unique alternative
  7641. // among the configurations.
  7642. reach = intermediate;
  7643. }
  7644. }
  7645. // If the reach set could not be trivially determined, perform a closure
  7646. // operation on the intermediate set to compute its initial value.
  7647. //
  7648. if (reach===null) {
  7649. reach = new ATNConfigSet(fullCtx);
  7650. var closureBusy = new Set();
  7651. var treatEofAsEpsilon = t === Token.EOF;
  7652. for (var k=0; k<intermediate.items.length;k++) {
  7653. this.closure(intermediate.items[k], reach, closureBusy, false, fullCtx, treatEofAsEpsilon);
  7654. }
  7655. }
  7656. if (t === Token.EOF) {
  7657. // After consuming EOF no additional input is possible, so we are
  7658. // only interested in configurations which reached the end of the
  7659. // decision rule (local context) or end of the start rule (full
  7660. // context). Update reach to contain only these configurations. This
  7661. // handles both explicit EOF transitions in the grammar and implicit
  7662. // EOF transitions following the end of the decision or start rule.
  7663. //
  7664. // When reach==intermediate, no closure operation was performed. In
  7665. // this case, removeAllConfigsNotInRuleStopState needs to check for
  7666. // reachable rule stop states as well as configurations already in
  7667. // a rule stop state.
  7668. //
  7669. // This is handled before the configurations in skippedStopStates,
  7670. // because any configurations potentially added from that list are
  7671. // already guaranteed to meet this condition whether or not it's
  7672. // required.
  7673. //
  7674. reach = this.removeAllConfigsNotInRuleStopState(reach, reach === intermediate);
  7675. }
  7676. // If skippedStopStates!==null, then it contains at least one
  7677. // configuration. For full-context reach operations, these
  7678. // configurations reached the end of the start rule, in which case we
  7679. // only add them back to reach if no configuration during the current
  7680. // closure operation reached such a state. This ensures adaptivePredict
  7681. // chooses an alternative matching the longest overall sequence when
  7682. // multiple alternatives are viable.
  7683. //
  7684. if (skippedStopStates!==null && ( (! fullCtx) || (! PredictionMode.hasConfigInRuleStopState(reach)))) {
  7685. for (var l=0; l<skippedStopStates.length;l++) {
  7686. reach.add(skippedStopStates[l], this.mergeCache);
  7687. }
  7688. }
  7689. if (reach.items.length===0) {
  7690. return null;
  7691. } else {
  7692. return reach;
  7693. }
  7694. };
  7695. //
  7696. // Return a configuration set containing only the configurations from
  7697. // {@code configs} which are in a {@link RuleStopState}. If all
  7698. // configurations in {@code configs} are already in a rule stop state, this
  7699. // method simply returns {@code configs}.
  7700. //
  7701. // <p>When {@code lookToEndOfRule} is true, this method uses
  7702. // {@link ATN//nextTokens} for each configuration in {@code configs} which is
  7703. // not already in a rule stop state to see if a rule stop state is reachable
  7704. // from the configuration via epsilon-only transitions.</p>
  7705. //
  7706. // @param configs the configuration set to update
  7707. // @param lookToEndOfRule when true, this method checks for rule stop states
  7708. // reachable by epsilon-only transitions from each configuration in
  7709. // {@code configs}.
  7710. //
  7711. // @return {@code configs} if all configurations in {@code configs} are in a
  7712. // rule stop state, otherwise return a new configuration set containing only
  7713. // the configurations from {@code configs} which are in a rule stop state
  7714. //
  7715. ParserATNSimulator.prototype.removeAllConfigsNotInRuleStopState = function(configs, lookToEndOfRule) {
  7716. if (PredictionMode.allConfigsInRuleStopStates(configs)) {
  7717. return configs;
  7718. }
  7719. var result = new ATNConfigSet(configs.fullCtx);
  7720. for(var i=0; i<configs.items.length;i++) {
  7721. var config = configs.items[i];
  7722. if (config.state instanceof RuleStopState) {
  7723. result.add(config, this.mergeCache);
  7724. continue;
  7725. }
  7726. if (lookToEndOfRule && config.state.epsilonOnlyTransitions) {
  7727. var nextTokens = this.atn.nextTokens(config.state);
  7728. if (nextTokens.contains(Token.EPSILON)) {
  7729. var endOfRuleState = this.atn.ruleToStopState[config.state.ruleIndex];
  7730. result.add(new ATNConfig({state:endOfRuleState}, config), this.mergeCache);
  7731. }
  7732. }
  7733. }
  7734. return result;
  7735. };
  7736. ParserATNSimulator.prototype.computeStartState = function(p, ctx, fullCtx) {
  7737. // always at least the implicit call to start rule
  7738. var initialContext = predictionContextFromRuleContext(this.atn, ctx);
  7739. var configs = new ATNConfigSet(fullCtx);
  7740. for(var i=0;i<p.transitions.length;i++) {
  7741. var target = p.transitions[i].target;
  7742. var c = new ATNConfig({ state:target, alt:i+1, context:initialContext }, null);
  7743. var closureBusy = new Set();
  7744. this.closure(c, configs, closureBusy, true, fullCtx, false);
  7745. }
  7746. return configs;
  7747. };
  7748. //
  7749. // This method transforms the start state computed by
  7750. // {@link //computeStartState} to the special start state used by a
  7751. // precedence DFA for a particular precedence value. The transformation
  7752. // process applies the following changes to the start state's configuration
  7753. // set.
  7754. //
  7755. // <ol>
  7756. // <li>Evaluate the precedence predicates for each configuration using
  7757. // {@link SemanticContext//evalPrecedence}.</li>
  7758. // <li>Remove all configurations which predict an alternative greater than
  7759. // 1, for which another configuration that predicts alternative 1 is in the
  7760. // same ATN state with the same prediction context. This transformation is
  7761. // valid for the following reasons:
  7762. // <ul>
  7763. // <li>The closure block cannot contain any epsilon transitions which bypass
  7764. // the body of the closure, so all states reachable via alternative 1 are
  7765. // part of the precedence alternatives of the transformed left-recursive
  7766. // rule.</li>
  7767. // <li>The "primary" portion of a left recursive rule cannot contain an
  7768. // epsilon transition, so the only way an alternative other than 1 can exist
  7769. // in a state that is also reachable via alternative 1 is by nesting calls
  7770. // to the left-recursive rule, with the outer calls not being at the
  7771. // preferred precedence level.</li>
  7772. // </ul>
  7773. // </li>
  7774. // </ol>
  7775. //
  7776. // <p>
  7777. // The prediction context must be considered by this filter to address
  7778. // situations like the following.
  7779. // </p>
  7780. // <code>
  7781. // <pre>
  7782. // grammar TA;
  7783. // prog: statement* EOF;
  7784. // statement: letterA | statement letterA 'b' ;
  7785. // letterA: 'a';
  7786. // </pre>
  7787. // </code>
  7788. // <p>
  7789. // If the above grammar, the ATN state immediately before the token
  7790. // reference {@code 'a'} in {@code letterA} is reachable from the left edge
  7791. // of both the primary and closure blocks of the left-recursive rule
  7792. // {@code statement}. The prediction context associated with each of these
  7793. // configurations distinguishes between them, and prevents the alternative
  7794. // which stepped out to {@code prog} (and then back in to {@code statement}
  7795. // from being eliminated by the filter.
  7796. // </p>
  7797. //
  7798. // @param configs The configuration set computed by
  7799. // {@link //computeStartState} as the start state for the DFA.
  7800. // @return The transformed configuration set representing the start state
  7801. // for a precedence DFA at a particular precedence level (determined by
  7802. // calling {@link Parser//getPrecedence}).
  7803. //
  7804. ParserATNSimulator.prototype.applyPrecedenceFilter = function(configs) {
  7805. var config;
  7806. var statesFromAlt1 = [];
  7807. var configSet = new ATNConfigSet(configs.fullCtx);
  7808. for(var i=0; i<configs.items.length; i++) {
  7809. config = configs.items[i];
  7810. // handle alt 1 first
  7811. if (config.alt !== 1) {
  7812. continue;
  7813. }
  7814. var updatedContext = config.semanticContext.evalPrecedence(this.parser, this._outerContext);
  7815. if (updatedContext===null) {
  7816. // the configuration was eliminated
  7817. continue;
  7818. }
  7819. statesFromAlt1[config.state.stateNumber] = config.context;
  7820. if (updatedContext !== config.semanticContext) {
  7821. configSet.add(new ATNConfig({semanticContext:updatedContext}, config), this.mergeCache);
  7822. } else {
  7823. configSet.add(config, this.mergeCache);
  7824. }
  7825. }
  7826. for(i=0; i<configs.items.length; i++) {
  7827. config = configs.items[i];
  7828. if (config.alt === 1) {
  7829. // already handled
  7830. continue;
  7831. }
  7832. // In the future, this elimination step could be updated to also
  7833. // filter the prediction context for alternatives predicting alt>1
  7834. // (basically a graph subtraction algorithm).
  7835. if (!config.precedenceFilterSuppressed) {
  7836. var context = statesFromAlt1[config.state.stateNumber] || null;
  7837. if (context!==null && context.equals(config.context)) {
  7838. // eliminated
  7839. continue;
  7840. }
  7841. }
  7842. configSet.add(config, this.mergeCache);
  7843. }
  7844. return configSet;
  7845. };
  7846. ParserATNSimulator.prototype.getReachableTarget = function(trans, ttype) {
  7847. if (trans.matches(ttype, 0, this.atn.maxTokenType)) {
  7848. return trans.target;
  7849. } else {
  7850. return null;
  7851. }
  7852. };
  7853. ParserATNSimulator.prototype.getPredsForAmbigAlts = function(ambigAlts, configs, nalts) {
  7854. // REACH=[1|1|[]|0:0, 1|2|[]|0:1]
  7855. // altToPred starts as an array of all null contexts. The entry at index i
  7856. // corresponds to alternative i. altToPred[i] may have one of three values:
  7857. // 1. null: no ATNConfig c is found such that c.alt==i
  7858. // 2. SemanticContext.NONE: At least one ATNConfig c exists such that
  7859. // c.alt==i and c.semanticContext==SemanticContext.NONE. In other words,
  7860. // alt i has at least one unpredicated config.
  7861. // 3. Non-NONE Semantic Context: There exists at least one, and for all
  7862. // ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE.
  7863. //
  7864. // From this, it is clear that NONE||anything==NONE.
  7865. //
  7866. var altToPred = [];
  7867. for(var i=0;i<configs.items.length;i++) {
  7868. var c = configs.items[i];
  7869. if(ambigAlts.contains( c.alt )) {
  7870. altToPred[c.alt] = SemanticContext.orContext(altToPred[c.alt] || null, c.semanticContext);
  7871. }
  7872. }
  7873. var nPredAlts = 0;
  7874. for (i =1;i< nalts+1;i++) {
  7875. var pred = altToPred[i] || null;
  7876. if (pred===null) {
  7877. altToPred[i] = SemanticContext.NONE;
  7878. } else if (pred !== SemanticContext.NONE) {
  7879. nPredAlts += 1;
  7880. }
  7881. }
  7882. // nonambig alts are null in altToPred
  7883. if (nPredAlts===0) {
  7884. altToPred = null;
  7885. }
  7886. if (this.debug) {
  7887. console.log("getPredsForAmbigAlts result " + Utils.arrayToString(altToPred));
  7888. }
  7889. return altToPred;
  7890. };
  7891. ParserATNSimulator.prototype.getPredicatePredictions = function(ambigAlts, altToPred) {
  7892. var pairs = [];
  7893. var containsPredicate = false;
  7894. for (var i=1; i<altToPred.length;i++) {
  7895. var pred = altToPred[i];
  7896. // unpredicated is indicated by SemanticContext.NONE
  7897. if( ambigAlts!==null && ambigAlts.contains( i )) {
  7898. pairs.push(new PredPrediction(pred, i));
  7899. }
  7900. if (pred !== SemanticContext.NONE) {
  7901. containsPredicate = true;
  7902. }
  7903. }
  7904. if (! containsPredicate) {
  7905. return null;
  7906. }
  7907. return pairs;
  7908. };
  7909. //
  7910. // This method is used to improve the localization of error messages by
  7911. // choosing an alternative rather than throwing a
  7912. // {@link NoViableAltException} in particular prediction scenarios where the
  7913. // {@link //ERROR} state was reached during ATN simulation.
  7914. //
  7915. // <p>
  7916. // The default implementation of this method uses the following
  7917. // algorithm to identify an ATN configuration which successfully parsed the
  7918. // decision entry rule. Choosing such an alternative ensures that the
  7919. // {@link ParserRuleContext} returned by the calling rule will be complete
  7920. // and valid, and the syntax error will be reported later at a more
  7921. // localized location.</p>
  7922. //
  7923. // <ul>
  7924. // <li>If a syntactically valid path or paths reach the end of the decision rule and
  7925. // they are semantically valid if predicated, return the min associated alt.</li>
  7926. // <li>Else, if a semantically invalid but syntactically valid path exist
  7927. // or paths exist, return the minimum associated alt.
  7928. // </li>
  7929. // <li>Otherwise, return {@link ATN//INVALID_ALT_NUMBER}.</li>
  7930. // </ul>
  7931. //
  7932. // <p>
  7933. // In some scenarios, the algorithm described above could predict an
  7934. // alternative which will result in a {@link FailedPredicateException} in
  7935. // the parser. Specifically, this could occur if the <em>only</em> configuration
  7936. // capable of successfully parsing to the end of the decision rule is
  7937. // blocked by a semantic predicate. By choosing this alternative within
  7938. // {@link //adaptivePredict} instead of throwing a
  7939. // {@link NoViableAltException}, the resulting
  7940. // {@link FailedPredicateException} in the parser will identify the specific
  7941. // predicate which is preventing the parser from successfully parsing the
  7942. // decision rule, which helps developers identify and correct logic errors
  7943. // in semantic predicates.
  7944. // </p>
  7945. //
  7946. // @param configs The ATN configurations which were valid immediately before
  7947. // the {@link //ERROR} state was reached
  7948. // @param outerContext The is the \gamma_0 initial parser context from the paper
  7949. // or the parser stack at the instant before prediction commences.
  7950. //
  7951. // @return The value to return from {@link //adaptivePredict}, or
  7952. // {@link ATN//INVALID_ALT_NUMBER} if a suitable alternative was not
  7953. // identified and {@link //adaptivePredict} should report an error instead.
  7954. //
  7955. ParserATNSimulator.prototype.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule = function(configs, outerContext) {
  7956. var cfgs = this.splitAccordingToSemanticValidity(configs, outerContext);
  7957. var semValidConfigs = cfgs[0];
  7958. var semInvalidConfigs = cfgs[1];
  7959. var alt = this.getAltThatFinishedDecisionEntryRule(semValidConfigs);
  7960. if (alt!==ATN.INVALID_ALT_NUMBER) { // semantically/syntactically viable path exists
  7961. return alt;
  7962. }
  7963. // Is there a syntactically valid path with a failed pred?
  7964. if (semInvalidConfigs.items.length>0) {
  7965. alt = this.getAltThatFinishedDecisionEntryRule(semInvalidConfigs);
  7966. if (alt!==ATN.INVALID_ALT_NUMBER) { // syntactically viable path exists
  7967. return alt;
  7968. }
  7969. }
  7970. return ATN.INVALID_ALT_NUMBER;
  7971. };
  7972. ParserATNSimulator.prototype.getAltThatFinishedDecisionEntryRule = function(configs) {
  7973. var alts = [];
  7974. for(var i=0;i<configs.items.length; i++) {
  7975. var c = configs.items[i];
  7976. if (c.reachesIntoOuterContext>0 || ((c.state instanceof RuleStopState) && c.context.hasEmptyPath())) {
  7977. if(alts.indexOf(c.alt)<0) {
  7978. alts.push(c.alt);
  7979. }
  7980. }
  7981. }
  7982. if (alts.length===0) {
  7983. return ATN.INVALID_ALT_NUMBER;
  7984. } else {
  7985. return Math.min.apply(null, alts);
  7986. }
  7987. };
  7988. // Walk the list of configurations and split them according to
  7989. // those that have preds evaluating to true/false. If no pred, assume
  7990. // true pred and include in succeeded set. Returns Pair of sets.
  7991. //
  7992. // Create a new set so as not to alter the incoming parameter.
  7993. //
  7994. // Assumption: the input stream has been restored to the starting point
  7995. // prediction, which is where predicates need to evaluate.
  7996. //
  7997. ParserATNSimulator.prototype.splitAccordingToSemanticValidity = function( configs, outerContext) {
  7998. var succeeded = new ATNConfigSet(configs.fullCtx);
  7999. var failed = new ATNConfigSet(configs.fullCtx);
  8000. for(var i=0;i<configs.items.length; i++) {
  8001. var c = configs.items[i];
  8002. if (c.semanticContext !== SemanticContext.NONE) {
  8003. var predicateEvaluationResult = c.semanticContext.evaluate(this.parser, outerContext);
  8004. if (predicateEvaluationResult) {
  8005. succeeded.add(c);
  8006. } else {
  8007. failed.add(c);
  8008. }
  8009. } else {
  8010. succeeded.add(c);
  8011. }
  8012. }
  8013. return [succeeded, failed];
  8014. };
  8015. // Look through a list of predicate/alt pairs, returning alts for the
  8016. // pairs that win. A {@code NONE} predicate indicates an alt containing an
  8017. // unpredicated config which behaves as "always true." If !complete
  8018. // then we stop at the first predicate that evaluates to true. This
  8019. // includes pairs with null predicates.
  8020. //
  8021. ParserATNSimulator.prototype.evalSemanticContext = function(predPredictions, outerContext, complete) {
  8022. var predictions = new BitSet();
  8023. for(var i=0;i<predPredictions.length;i++) {
  8024. var pair = predPredictions[i];
  8025. if (pair.pred === SemanticContext.NONE) {
  8026. predictions.add(pair.alt);
  8027. if (! complete) {
  8028. break;
  8029. }
  8030. continue;
  8031. }
  8032. var predicateEvaluationResult = pair.pred.evaluate(this.parser, outerContext);
  8033. if (this.debug || this.dfa_debug) {
  8034. console.log("eval pred " + pair + "=" + predicateEvaluationResult);
  8035. }
  8036. if (predicateEvaluationResult) {
  8037. if (this.debug || this.dfa_debug) {
  8038. console.log("PREDICT " + pair.alt);
  8039. }
  8040. predictions.add(pair.alt);
  8041. if (! complete) {
  8042. break;
  8043. }
  8044. }
  8045. }
  8046. return predictions;
  8047. };
  8048. // TODO: If we are doing predicates, there is no point in pursuing
  8049. // closure operations if we reach a DFA state that uniquely predicts
  8050. // alternative. We will not be caching that DFA state and it is a
  8051. // waste to pursue the closure. Might have to advance when we do
  8052. // ambig detection thought :(
  8053. //
  8054. ParserATNSimulator.prototype.closure = function(config, configs, closureBusy, collectPredicates, fullCtx, treatEofAsEpsilon) {
  8055. var initialDepth = 0;
  8056. this.closureCheckingStopState(config, configs, closureBusy, collectPredicates,
  8057. fullCtx, initialDepth, treatEofAsEpsilon);
  8058. };
  8059. ParserATNSimulator.prototype.closureCheckingStopState = function(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
  8060. if (this.debug || this.debug_closure) {
  8061. console.log("closure(" + config.toString(this.parser,true) + ")");
  8062. // console.log("configs(" + configs.toString() + ")");
  8063. if(config.reachesIntoOuterContext>50) {
  8064. throw "problem";
  8065. }
  8066. }
  8067. if (config.state instanceof RuleStopState) {
  8068. // We hit rule end. If we have context info, use it
  8069. // run thru all possible stack tops in ctx
  8070. if (! config.context.isEmpty()) {
  8071. for ( var i =0; i<config.context.length; i++) {
  8072. if (config.context.getReturnState(i) === PredictionContext.EMPTY_RETURN_STATE) {
  8073. if (fullCtx) {
  8074. configs.add(new ATNConfig({state:config.state, context:PredictionContext.EMPTY}, config), this.mergeCache);
  8075. continue;
  8076. } else {
  8077. // we have no context info, just chase follow links (if greedy)
  8078. if (this.debug) {
  8079. console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
  8080. }
  8081. this.closure_(config, configs, closureBusy, collectPredicates,
  8082. fullCtx, depth, treatEofAsEpsilon);
  8083. }
  8084. continue;
  8085. }
  8086. var returnState = this.atn.states[config.context.getReturnState(i)];
  8087. var newContext = config.context.getParent(i); // "pop" return state
  8088. var parms = {state:returnState, alt:config.alt, context:newContext, semanticContext:config.semanticContext};
  8089. var c = new ATNConfig(parms, null);
  8090. // While we have context to pop back from, we may have
  8091. // gotten that context AFTER having falling off a rule.
  8092. // Make sure we track that we are now out of context.
  8093. c.reachesIntoOuterContext = config.reachesIntoOuterContext;
  8094. this.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1, treatEofAsEpsilon);
  8095. }
  8096. return;
  8097. } else if( fullCtx) {
  8098. // reached end of start rule
  8099. configs.add(config, this.mergeCache);
  8100. return;
  8101. } else {
  8102. // else if we have no context info, just chase follow links (if greedy)
  8103. if (this.debug) {
  8104. console.log("FALLING off rule " + this.getRuleName(config.state.ruleIndex));
  8105. }
  8106. }
  8107. }
  8108. this.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon);
  8109. };
  8110. // Do the actual work of walking epsilon edges//
  8111. ParserATNSimulator.prototype.closure_ = function(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) {
  8112. var p = config.state;
  8113. // optimization
  8114. if (! p.epsilonOnlyTransitions) {
  8115. configs.add(config, this.mergeCache);
  8116. // make sure to not return here, because EOF transitions can act as
  8117. // both epsilon transitions and non-epsilon transitions.
  8118. }
  8119. for(var i = 0;i<p.transitions.length; i++) {
  8120. if(i==0 && this.canDropLoopEntryEdgeInLeftRecursiveRule(config))
  8121. continue;
  8122. var t = p.transitions[i];
  8123. var continueCollecting = collectPredicates && !(t instanceof ActionTransition);
  8124. var c = this.getEpsilonTarget(config, t, continueCollecting, depth === 0, fullCtx, treatEofAsEpsilon);
  8125. if (c!==null) {
  8126. var newDepth = depth;
  8127. if ( config.state instanceof RuleStopState) {
  8128. // target fell off end of rule; mark resulting c as having dipped into outer context
  8129. // We can't get here if incoming config was rule stop and we had context
  8130. // track how far we dip into outer context. Might
  8131. // come in handy and we avoid evaluating context dependent
  8132. // preds if this is > 0.
  8133. if (this._dfa !== null && this._dfa.precedenceDfa) {
  8134. if (t.outermostPrecedenceReturn === this._dfa.atnStartState.ruleIndex) {
  8135. c.precedenceFilterSuppressed = true;
  8136. }
  8137. }
  8138. c.reachesIntoOuterContext += 1;
  8139. if (closureBusy.add(c)!==c) {
  8140. // avoid infinite recursion for right-recursive rules
  8141. continue;
  8142. }
  8143. configs.dipsIntoOuterContext = true; // TODO: can remove? only care when we add to set per middle of this method
  8144. newDepth -= 1;
  8145. if (this.debug) {
  8146. console.log("dips into outer ctx: " + c);
  8147. }
  8148. } else {
  8149. if (!t.isEpsilon && closureBusy.add(c)!==c){
  8150. // avoid infinite recursion for EOF* and EOF+
  8151. continue;
  8152. }
  8153. if (t instanceof RuleTransition) {
  8154. // latch when newDepth goes negative - once we step out of the entry context we can't return
  8155. if (newDepth >= 0) {
  8156. newDepth += 1;
  8157. }
  8158. }
  8159. }
  8160. this.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEofAsEpsilon);
  8161. }
  8162. }
  8163. };
  8164. ParserATNSimulator.prototype.canDropLoopEntryEdgeInLeftRecursiveRule = function(config) {
  8165. // return False
  8166. var p = config.state;
  8167. // First check to see if we are in StarLoopEntryState generated during
  8168. // left-recursion elimination. For efficiency, also check if
  8169. // the context has an empty stack case. If so, it would mean
  8170. // global FOLLOW so we can't perform optimization
  8171. // Are we the special loop entry/exit state? or SLL wildcard
  8172. if(p.stateType != ATNState.STAR_LOOP_ENTRY)
  8173. return false;
  8174. if(p.stateType != ATNState.STAR_LOOP_ENTRY || !p.isPrecedenceDecision ||
  8175. config.context.isEmpty() || config.context.hasEmptyPath())
  8176. return false;
  8177. // Require all return states to return back to the same rule that p is in.
  8178. var numCtxs = config.context.length;
  8179. for(var i=0; i<numCtxs; i++) { // for each stack context
  8180. var returnState = this.atn.states[config.context.getReturnState(i)];
  8181. if (returnState.ruleIndex != p.ruleIndex)
  8182. return false;
  8183. }
  8184. var decisionStartState = p.transitions[0].target;
  8185. var blockEndStateNum = decisionStartState.endState.stateNumber;
  8186. var blockEndState = this.atn.states[blockEndStateNum];
  8187. // Verify that the top of each stack context leads to loop entry/exit
  8188. // state through epsilon edges and w/o leaving rule.
  8189. for(var i=0; i<numCtxs; i++) { // for each stack context
  8190. var returnStateNumber = config.context.getReturnState(i);
  8191. var returnState = this.atn.states[returnStateNumber];
  8192. // all states must have single outgoing epsilon edge
  8193. if (returnState.transitions.length != 1 || !returnState.transitions[0].isEpsilon)
  8194. return false;
  8195. // Look for prefix op case like 'not expr', (' type ')' expr
  8196. var returnStateTarget = returnState.transitions[0].target;
  8197. if ( returnState.stateType == ATNState.BLOCK_END && returnStateTarget == p )
  8198. continue;
  8199. // Look for 'expr op expr' or case where expr's return state is block end
  8200. // of (...)* internal block; the block end points to loop back
  8201. // which points to p but we don't need to check that
  8202. if ( returnState == blockEndState )
  8203. continue;
  8204. // Look for ternary expr ? expr : expr. The return state points at block end,
  8205. // which points at loop entry state
  8206. if ( returnStateTarget == blockEndState )
  8207. continue;
  8208. // Look for complex prefix 'between expr and expr' case where 2nd expr's
  8209. // return state points at block end state of (...)* internal block
  8210. if (returnStateTarget.stateType == ATNState.BLOCK_END && returnStateTarget.transitions.length == 1
  8211. && returnStateTarget.transitions[0].isEpsilon && returnStateTarget.transitions[0].target == p)
  8212. continue;
  8213. // anything else ain't conforming
  8214. return false;
  8215. }
  8216. return true;
  8217. };
  8218. ParserATNSimulator.prototype.getRuleName = function( index) {
  8219. if (this.parser!==null && index>=0) {
  8220. return this.parser.ruleNames[index];
  8221. } else {
  8222. return "<rule " + index + ">";
  8223. }
  8224. };
  8225. ParserATNSimulator.prototype.getEpsilonTarget = function(config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon) {
  8226. switch(t.serializationType) {
  8227. case Transition.RULE:
  8228. return this.ruleTransition(config, t);
  8229. case Transition.PRECEDENCE:
  8230. return this.precedenceTransition(config, t, collectPredicates, inContext, fullCtx);
  8231. case Transition.PREDICATE:
  8232. return this.predTransition(config, t, collectPredicates, inContext, fullCtx);
  8233. case Transition.ACTION:
  8234. return this.actionTransition(config, t);
  8235. case Transition.EPSILON:
  8236. return new ATNConfig({state:t.target}, config);
  8237. case Transition.ATOM:
  8238. case Transition.RANGE:
  8239. case Transition.SET:
  8240. // EOF transitions act like epsilon transitions after the first EOF
  8241. // transition is traversed
  8242. if (treatEofAsEpsilon) {
  8243. if (t.matches(Token.EOF, 0, 1)) {
  8244. return new ATNConfig({state: t.target}, config);
  8245. }
  8246. }
  8247. return null;
  8248. default:
  8249. return null;
  8250. }
  8251. };
  8252. ParserATNSimulator.prototype.actionTransition = function(config, t) {
  8253. if (this.debug) {
  8254. var index = t.actionIndex==-1 ? 65535 : t.actionIndex;
  8255. console.log("ACTION edge " + t.ruleIndex + ":" + index);
  8256. }
  8257. return new ATNConfig({state:t.target}, config);
  8258. };
  8259. ParserATNSimulator.prototype.precedenceTransition = function(config, pt, collectPredicates, inContext, fullCtx) {
  8260. if (this.debug) {
  8261. console.log("PRED (collectPredicates=" + collectPredicates + ") " +
  8262. pt.precedence + ">=_p, ctx dependent=true");
  8263. if (this.parser!==null) {
  8264. console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
  8265. }
  8266. }
  8267. var c = null;
  8268. if (collectPredicates && inContext) {
  8269. if (fullCtx) {
  8270. // In full context mode, we can evaluate predicates on-the-fly
  8271. // during closure, which dramatically reduces the size of
  8272. // the config sets. It also obviates the need to test predicates
  8273. // later during conflict resolution.
  8274. var currentPosition = this._input.index;
  8275. this._input.seek(this._startIndex);
  8276. var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
  8277. this._input.seek(currentPosition);
  8278. if (predSucceeds) {
  8279. c = new ATNConfig({state:pt.target}, config); // no pred context
  8280. }
  8281. } else {
  8282. var newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
  8283. c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);
  8284. }
  8285. } else {
  8286. c = new ATNConfig({state:pt.target}, config);
  8287. }
  8288. if (this.debug) {
  8289. console.log("config from pred transition=" + c);
  8290. }
  8291. return c;
  8292. };
  8293. ParserATNSimulator.prototype.predTransition = function(config, pt, collectPredicates, inContext, fullCtx) {
  8294. if (this.debug) {
  8295. console.log("PRED (collectPredicates=" + collectPredicates + ") " + pt.ruleIndex +
  8296. ":" + pt.predIndex + ", ctx dependent=" + pt.isCtxDependent);
  8297. if (this.parser!==null) {
  8298. console.log("context surrounding pred is " + Utils.arrayToString(this.parser.getRuleInvocationStack()));
  8299. }
  8300. }
  8301. var c = null;
  8302. if (collectPredicates && ((pt.isCtxDependent && inContext) || ! pt.isCtxDependent)) {
  8303. if (fullCtx) {
  8304. // In full context mode, we can evaluate predicates on-the-fly
  8305. // during closure, which dramatically reduces the size of
  8306. // the config sets. It also obviates the need to test predicates
  8307. // later during conflict resolution.
  8308. var currentPosition = this._input.index;
  8309. this._input.seek(this._startIndex);
  8310. var predSucceeds = pt.getPredicate().evaluate(this.parser, this._outerContext);
  8311. this._input.seek(currentPosition);
  8312. if (predSucceeds) {
  8313. c = new ATNConfig({state:pt.target}, config); // no pred context
  8314. }
  8315. } else {
  8316. var newSemCtx = SemanticContext.andContext(config.semanticContext, pt.getPredicate());
  8317. c = new ATNConfig({state:pt.target, semanticContext:newSemCtx}, config);
  8318. }
  8319. } else {
  8320. c = new ATNConfig({state:pt.target}, config);
  8321. }
  8322. if (this.debug) {
  8323. console.log("config from pred transition=" + c);
  8324. }
  8325. return c;
  8326. };
  8327. ParserATNSimulator.prototype.ruleTransition = function(config, t) {
  8328. if (this.debug) {
  8329. console.log("CALL rule " + this.getRuleName(t.target.ruleIndex) + ", ctx=" + config.context);
  8330. }
  8331. var returnState = t.followState;
  8332. var newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber);
  8333. return new ATNConfig({state:t.target, context:newContext}, config );
  8334. };
  8335. ParserATNSimulator.prototype.getConflictingAlts = function(configs) {
  8336. var altsets = PredictionMode.getConflictingAltSubsets(configs);
  8337. return PredictionMode.getAlts(altsets);
  8338. };
  8339. // Sam pointed out a problem with the previous definition, v3, of
  8340. // ambiguous states. If we have another state associated with conflicting
  8341. // alternatives, we should keep going. For example, the following grammar
  8342. //
  8343. // s : (ID | ID ID?) ';' ;
  8344. //
  8345. // When the ATN simulation reaches the state before ';', it has a DFA
  8346. // state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally
  8347. // 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node
  8348. // because alternative to has another way to continue, via [6|2|[]].
  8349. // The key is that we have a single state that has config's only associated
  8350. // with a single alternative, 2, and crucially the state transitions
  8351. // among the configurations are all non-epsilon transitions. That means
  8352. // we don't consider any conflicts that include alternative 2. So, we
  8353. // ignore the conflict between alts 1 and 2. We ignore a set of
  8354. // conflicting alts when there is an intersection with an alternative
  8355. // associated with a single alt state in the state&rarr;config-list map.
  8356. //
  8357. // It's also the case that we might have two conflicting configurations but
  8358. // also a 3rd nonconflicting configuration for a different alternative:
  8359. // [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar:
  8360. //
  8361. // a : A | A | A B ;
  8362. //
  8363. // After matching input A, we reach the stop state for rule A, state 1.
  8364. // State 8 is the state right before B. Clearly alternatives 1 and 2
  8365. // conflict and no amount of further lookahead will separate the two.
  8366. // However, alternative 3 will be able to continue and so we do not
  8367. // stop working on this state. In the previous example, we're concerned
  8368. // with states associated with the conflicting alternatives. Here alt
  8369. // 3 is not associated with the conflicting configs, but since we can continue
  8370. // looking for input reasonably, I don't declare the state done. We
  8371. // ignore a set of conflicting alts when we have an alternative
  8372. // that we still need to pursue.
  8373. //
  8374. ParserATNSimulator.prototype.getConflictingAltsOrUniqueAlt = function(configs) {
  8375. var conflictingAlts = null;
  8376. if (configs.uniqueAlt!== ATN.INVALID_ALT_NUMBER) {
  8377. conflictingAlts = new BitSet();
  8378. conflictingAlts.add(configs.uniqueAlt);
  8379. } else {
  8380. conflictingAlts = configs.conflictingAlts;
  8381. }
  8382. return conflictingAlts;
  8383. };
  8384. ParserATNSimulator.prototype.getTokenName = function( t) {
  8385. if (t===Token.EOF) {
  8386. return "EOF";
  8387. }
  8388. if( this.parser!==null && this.parser.literalNames!==null) {
  8389. if (t >= this.parser.literalNames.length && t >= this.parser.symbolicNames.length) {
  8390. console.log("" + t + " ttype out of range: " + this.parser.literalNames);
  8391. console.log("" + this.parser.getInputStream().getTokens());
  8392. } else {
  8393. var name = this.parser.literalNames[t] || this.parser.symbolicNames[t];
  8394. return name + "<" + t + ">";
  8395. }
  8396. }
  8397. return "" + t;
  8398. };
  8399. ParserATNSimulator.prototype.getLookaheadName = function(input) {
  8400. return this.getTokenName(input.LA(1));
  8401. };
  8402. // Used for debugging in adaptivePredict around execATN but I cut
  8403. // it out for clarity now that alg. works well. We can leave this
  8404. // "dead" code for a bit.
  8405. //
  8406. ParserATNSimulator.prototype.dumpDeadEndConfigs = function(nvae) {
  8407. console.log("dead end configs: ");
  8408. var decs = nvae.getDeadEndConfigs();
  8409. for(var i=0; i<decs.length; i++) {
  8410. var c = decs[i];
  8411. var trans = "no edges";
  8412. if (c.state.transitions.length>0) {
  8413. var t = c.state.transitions[0];
  8414. if (t instanceof AtomTransition) {
  8415. trans = "Atom "+ this.getTokenName(t.label);
  8416. } else if (t instanceof SetTransition) {
  8417. var neg = (t instanceof NotSetTransition);
  8418. trans = (neg ? "~" : "") + "Set " + t.set;
  8419. }
  8420. }
  8421. console.error(c.toString(this.parser, true) + ":" + trans);
  8422. }
  8423. };
  8424. ParserATNSimulator.prototype.noViableAlt = function(input, outerContext, configs, startIndex) {
  8425. return new NoViableAltException(this.parser, input, input.get(startIndex), input.LT(1), configs, outerContext);
  8426. };
  8427. ParserATNSimulator.prototype.getUniqueAlt = function(configs) {
  8428. var alt = ATN.INVALID_ALT_NUMBER;
  8429. for(var i=0;i<configs.items.length;i++) {
  8430. var c = configs.items[i];
  8431. if (alt === ATN.INVALID_ALT_NUMBER) {
  8432. alt = c.alt // found first alt
  8433. } else if( c.alt!==alt) {
  8434. return ATN.INVALID_ALT_NUMBER;
  8435. }
  8436. }
  8437. return alt;
  8438. };
  8439. //
  8440. // Add an edge to the DFA, if possible. This method calls
  8441. // {@link //addDFAState} to ensure the {@code to} state is present in the
  8442. // DFA. If {@code from} is {@code null}, or if {@code t} is outside the
  8443. // range of edges that can be represented in the DFA tables, this method
  8444. // returns without adding the edge to the DFA.
  8445. //
  8446. // <p>If {@code to} is {@code null}, this method returns {@code null}.
  8447. // Otherwise, this method returns the {@link DFAState} returned by calling
  8448. // {@link //addDFAState} for the {@code to} state.</p>
  8449. //
  8450. // @param dfa The DFA
  8451. // @param from The source state for the edge
  8452. // @param t The input symbol
  8453. // @param to The target state for the edge
  8454. //
  8455. // @return If {@code to} is {@code null}, this method returns {@code null};
  8456. // otherwise this method returns the result of calling {@link //addDFAState}
  8457. // on {@code to}
  8458. //
  8459. ParserATNSimulator.prototype.addDFAEdge = function(dfa, from_, t, to) {
  8460. if( this.debug) {
  8461. console.log("EDGE " + from_ + " -> " + to + " upon " + this.getTokenName(t));
  8462. }
  8463. if (to===null) {
  8464. return null;
  8465. }
  8466. to = this.addDFAState(dfa, to); // used existing if possible not incoming
  8467. if (from_===null || t < -1 || t > this.atn.maxTokenType) {
  8468. return to;
  8469. }
  8470. if (from_.edges===null) {
  8471. from_.edges = [];
  8472. }
  8473. from_.edges[t+1] = to; // connect
  8474. if (this.debug) {
  8475. var literalNames = this.parser===null ? null : this.parser.literalNames;
  8476. var symbolicNames = this.parser===null ? null : this.parser.symbolicNames;
  8477. console.log("DFA=\n" + dfa.toString(literalNames, symbolicNames));
  8478. }
  8479. return to;
  8480. };
  8481. //
  8482. // Add state {@code D} to the DFA if it is not already present, and return
  8483. // the actual instance stored in the DFA. If a state equivalent to {@code D}
  8484. // is already in the DFA, the existing state is returned. Otherwise this
  8485. // method returns {@code D} after adding it to the DFA.
  8486. //
  8487. // <p>If {@code D} is {@link //ERROR}, this method returns {@link //ERROR} and
  8488. // does not change the DFA.</p>
  8489. //
  8490. // @param dfa The dfa
  8491. // @param D The DFA state to add
  8492. // @return The state stored in the DFA. This will be either the existing
  8493. // state if {@code D} is already in the DFA, or {@code D} itself if the
  8494. // state was not already present.
  8495. //
  8496. ParserATNSimulator.prototype.addDFAState = function(dfa, D) {
  8497. if (D == ATNSimulator.ERROR) {
  8498. return D;
  8499. }
  8500. var existing = dfa.states.get(D);
  8501. if(existing!==null) {
  8502. return existing;
  8503. }
  8504. D.stateNumber = dfa.states.length;
  8505. if (! D.configs.readOnly) {
  8506. D.configs.optimizeConfigs(this);
  8507. D.configs.setReadonly(true);
  8508. }
  8509. dfa.states.add(D);
  8510. if (this.debug) {
  8511. console.log("adding new DFA state: " + D);
  8512. }
  8513. return D;
  8514. };
  8515. ParserATNSimulator.prototype.reportAttemptingFullContext = function(dfa, conflictingAlts, configs, startIndex, stopIndex) {
  8516. if (this.debug || this.retry_debug) {
  8517. var interval = new Interval(startIndex, stopIndex + 1);
  8518. console.log("reportAttemptingFullContext decision=" + dfa.decision + ":" + configs +
  8519. ", input=" + this.parser.getTokenStream().getText(interval));
  8520. }
  8521. if (this.parser!==null) {
  8522. this.parser.getErrorListenerDispatch().reportAttemptingFullContext(this.parser, dfa, startIndex, stopIndex, conflictingAlts, configs);
  8523. }
  8524. };
  8525. ParserATNSimulator.prototype.reportContextSensitivity = function(dfa, prediction, configs, startIndex, stopIndex) {
  8526. if (this.debug || this.retry_debug) {
  8527. var interval = new Interval(startIndex, stopIndex + 1);
  8528. console.log("reportContextSensitivity decision=" + dfa.decision + ":" + configs +
  8529. ", input=" + this.parser.getTokenStream().getText(interval));
  8530. }
  8531. if (this.parser!==null) {
  8532. this.parser.getErrorListenerDispatch().reportContextSensitivity(this.parser, dfa, startIndex, stopIndex, prediction, configs);
  8533. }
  8534. };
  8535. // If context sensitive parsing, we know it's ambiguity not conflict//
  8536. ParserATNSimulator.prototype.reportAmbiguity = function(dfa, D, startIndex, stopIndex,
  8537. exact, ambigAlts, configs ) {
  8538. if (this.debug || this.retry_debug) {
  8539. var interval = new Interval(startIndex, stopIndex + 1);
  8540. console.log("reportAmbiguity " + ambigAlts + ":" + configs +
  8541. ", input=" + this.parser.getTokenStream().getText(interval));
  8542. }
  8543. if (this.parser!==null) {
  8544. this.parser.getErrorListenerDispatch().reportAmbiguity(this.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs);
  8545. }
  8546. };
  8547. exports.ParserATNSimulator = ParserATNSimulator;
  8548. /***/ }),
  8549. /***/ "./node_modules/antlr4/atn/PredictionMode.js":
  8550. /*!***************************************************!*\
  8551. !*** ./node_modules/antlr4/atn/PredictionMode.js ***!
  8552. \***************************************************/
  8553. /*! no static exports found */
  8554. /***/ (function(module, exports, __webpack_require__) {
  8555. //
  8556. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  8557. * Use of this file is governed by the BSD 3-clause license that
  8558. * can be found in the LICENSE.txt file in the project root.
  8559. */
  8560. //
  8561. //
  8562. // This enumeration defines the prediction modes available in ANTLR 4 along with
  8563. // utility methods for analyzing configuration sets for conflicts and/or
  8564. // ambiguities.
  8565. var Set = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Set;
  8566. var Map = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Map;
  8567. var BitSet = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").BitSet;
  8568. var AltDict = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").AltDict;
  8569. var ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  8570. var RuleStopState = __webpack_require__(/*! ./ATNState */ "./node_modules/antlr4/atn/ATNState.js").RuleStopState;
  8571. var ATNConfigSet = __webpack_require__(/*! ./ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  8572. var ATNConfig = __webpack_require__(/*! ./ATNConfig */ "./node_modules/antlr4/atn/ATNConfig.js").ATNConfig;
  8573. var SemanticContext = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").SemanticContext;
  8574. var Hash = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").Hash;
  8575. var hashStuff = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").hashStuff;
  8576. var equalArrays = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").equalArrays;
  8577. function PredictionMode() {
  8578. return this;
  8579. }
  8580. //
  8581. // The SLL(*) prediction mode. This prediction mode ignores the current
  8582. // parser context when making predictions. This is the fastest prediction
  8583. // mode, and provides correct results for many grammars. This prediction
  8584. // mode is more powerful than the prediction mode provided by ANTLR 3, but
  8585. // may result in syntax errors for grammar and input combinations which are
  8586. // not SLL.
  8587. //
  8588. // <p>
  8589. // When using this prediction mode, the parser will either return a correct
  8590. // parse tree (i.e. the same parse tree that would be returned with the
  8591. // {@link //LL} prediction mode), or it will report a syntax error. If a
  8592. // syntax error is encountered when using the {@link //SLL} prediction mode,
  8593. // it may be due to either an actual syntax error in the input or indicate
  8594. // that the particular combination of grammar and input requires the more
  8595. // powerful {@link //LL} prediction abilities to complete successfully.</p>
  8596. //
  8597. // <p>
  8598. // This prediction mode does not provide any guarantees for prediction
  8599. // behavior for syntactically-incorrect inputs.</p>
  8600. //
  8601. PredictionMode.SLL = 0;
  8602. //
  8603. // The LL(*) prediction mode. This prediction mode allows the current parser
  8604. // context to be used for resolving SLL conflicts that occur during
  8605. // prediction. This is the fastest prediction mode that guarantees correct
  8606. // parse results for all combinations of grammars with syntactically correct
  8607. // inputs.
  8608. //
  8609. // <p>
  8610. // When using this prediction mode, the parser will make correct decisions
  8611. // for all syntactically-correct grammar and input combinations. However, in
  8612. // cases where the grammar is truly ambiguous this prediction mode might not
  8613. // report a precise answer for <em>exactly which</em> alternatives are
  8614. // ambiguous.</p>
  8615. //
  8616. // <p>
  8617. // This prediction mode does not provide any guarantees for prediction
  8618. // behavior for syntactically-incorrect inputs.</p>
  8619. //
  8620. PredictionMode.LL = 1;
  8621. //
  8622. // The LL(*) prediction mode with exact ambiguity detection. In addition to
  8623. // the correctness guarantees provided by the {@link //LL} prediction mode,
  8624. // this prediction mode instructs the prediction algorithm to determine the
  8625. // complete and exact set of ambiguous alternatives for every ambiguous
  8626. // decision encountered while parsing.
  8627. //
  8628. // <p>
  8629. // This prediction mode may be used for diagnosing ambiguities during
  8630. // grammar development. Due to the performance overhead of calculating sets
  8631. // of ambiguous alternatives, this prediction mode should be avoided when
  8632. // the exact results are not necessary.</p>
  8633. //
  8634. // <p>
  8635. // This prediction mode does not provide any guarantees for prediction
  8636. // behavior for syntactically-incorrect inputs.</p>
  8637. //
  8638. PredictionMode.LL_EXACT_AMBIG_DETECTION = 2;
  8639. //
  8640. // Computes the SLL prediction termination condition.
  8641. //
  8642. // <p>
  8643. // This method computes the SLL prediction termination condition for both of
  8644. // the following cases.</p>
  8645. //
  8646. // <ul>
  8647. // <li>The usual SLL+LL fallback upon SLL conflict</li>
  8648. // <li>Pure SLL without LL fallback</li>
  8649. // </ul>
  8650. //
  8651. // <p><strong>COMBINED SLL+LL PARSING</strong></p>
  8652. //
  8653. // <p>When LL-fallback is enabled upon SLL conflict, correct predictions are
  8654. // ensured regardless of how the termination condition is computed by this
  8655. // method. Due to the substantially higher cost of LL prediction, the
  8656. // prediction should only fall back to LL when the additional lookahead
  8657. // cannot lead to a unique SLL prediction.</p>
  8658. //
  8659. // <p>Assuming combined SLL+LL parsing, an SLL configuration set with only
  8660. // conflicting subsets should fall back to full LL, even if the
  8661. // configuration sets don't resolve to the same alternative (e.g.
  8662. // {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting
  8663. // configuration, SLL could continue with the hopes that more lookahead will
  8664. // resolve via one of those non-conflicting configurations.</p>
  8665. //
  8666. // <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)
  8667. // stops when it sees only conflicting configuration subsets. In contrast,
  8668. // full LL keeps going when there is uncertainty.</p>
  8669. //
  8670. // <p><strong>HEURISTIC</strong></p>
  8671. //
  8672. // <p>As a heuristic, we stop prediction when we see any conflicting subset
  8673. // unless we see a state that only has one alternative associated with it.
  8674. // The single-alt-state thing lets prediction continue upon rules like
  8675. // (otherwise, it would admit defeat too soon):</p>
  8676. //
  8677. // <p>{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}</p>
  8678. //
  8679. // <p>When the ATN simulation reaches the state before {@code ';'}, it has a
  8680. // DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally
  8681. // {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop
  8682. // processing this node because alternative to has another way to continue,
  8683. // via {@code [6|2|[]]}.</p>
  8684. //
  8685. // <p>It also let's us continue for this rule:</p>
  8686. //
  8687. // <p>{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}</p>
  8688. //
  8689. // <p>After matching input A, we reach the stop state for rule A, state 1.
  8690. // State 8 is the state right before B. Clearly alternatives 1 and 2
  8691. // conflict and no amount of further lookahead will separate the two.
  8692. // However, alternative 3 will be able to continue and so we do not stop
  8693. // working on this state. In the previous example, we're concerned with
  8694. // states associated with the conflicting alternatives. Here alt 3 is not
  8695. // associated with the conflicting configs, but since we can continue
  8696. // looking for input reasonably, don't declare the state done.</p>
  8697. //
  8698. // <p><strong>PURE SLL PARSING</strong></p>
  8699. //
  8700. // <p>To handle pure SLL parsing, all we have to do is make sure that we
  8701. // combine stack contexts for configurations that differ only by semantic
  8702. // predicate. From there, we can do the usual SLL termination heuristic.</p>
  8703. //
  8704. // <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>
  8705. //
  8706. // <p>SLL decisions don't evaluate predicates until after they reach DFA stop
  8707. // states because they need to create the DFA cache that works in all
  8708. // semantic situations. In contrast, full LL evaluates predicates collected
  8709. // during start state computation so it can ignore predicates thereafter.
  8710. // This means that SLL termination detection can totally ignore semantic
  8711. // predicates.</p>
  8712. //
  8713. // <p>Implementation-wise, {@link ATNConfigSet} combines stack contexts but not
  8714. // semantic predicate contexts so we might see two configurations like the
  8715. // following.</p>
  8716. //
  8717. // <p>{@code (s, 1, x, {}), (s, 1, x', {p})}</p>
  8718. //
  8719. // <p>Before testing these configurations against others, we have to merge
  8720. // {@code x} and {@code x'} (without modifying the existing configurations).
  8721. // For example, we test {@code (x+x')==x''} when looking for conflicts in
  8722. // the following configurations.</p>
  8723. //
  8724. // <p>{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}</p>
  8725. //
  8726. // <p>If the configuration set has predicates (as indicated by
  8727. // {@link ATNConfigSet//hasSemanticContext}), this algorithm makes a copy of
  8728. // the configurations to strip out all of the predicates so that a standard
  8729. // {@link ATNConfigSet} will merge everything ignoring predicates.</p>
  8730. //
  8731. PredictionMode.hasSLLConflictTerminatingPrediction = function( mode, configs) {
  8732. // Configs in rule stop states indicate reaching the end of the decision
  8733. // rule (local context) or end of start rule (full context). If all
  8734. // configs meet this condition, then none of the configurations is able
  8735. // to match additional input so we terminate prediction.
  8736. //
  8737. if (PredictionMode.allConfigsInRuleStopStates(configs)) {
  8738. return true;
  8739. }
  8740. // pure SLL mode parsing
  8741. if (mode === PredictionMode.SLL) {
  8742. // Don't bother with combining configs from different semantic
  8743. // contexts if we can fail over to full LL; costs more time
  8744. // since we'll often fail over anyway.
  8745. if (configs.hasSemanticContext) {
  8746. // dup configs, tossing out semantic predicates
  8747. var dup = new ATNConfigSet();
  8748. for(var i=0;i<configs.items.length;i++) {
  8749. var c = configs.items[i];
  8750. c = new ATNConfig({semanticContext:SemanticContext.NONE}, c);
  8751. dup.add(c);
  8752. }
  8753. configs = dup;
  8754. }
  8755. // now we have combined contexts for configs with dissimilar preds
  8756. }
  8757. // pure SLL or combined SLL+LL mode parsing
  8758. var altsets = PredictionMode.getConflictingAltSubsets(configs);
  8759. return PredictionMode.hasConflictingAltSet(altsets) && !PredictionMode.hasStateAssociatedWithOneAlt(configs);
  8760. };
  8761. // Checks if any configuration in {@code configs} is in a
  8762. // {@link RuleStopState}. Configurations meeting this condition have reached
  8763. // the end of the decision rule (local context) or end of start rule (full
  8764. // context).
  8765. //
  8766. // @param configs the configuration set to test
  8767. // @return {@code true} if any configuration in {@code configs} is in a
  8768. // {@link RuleStopState}, otherwise {@code false}
  8769. PredictionMode.hasConfigInRuleStopState = function(configs) {
  8770. for(var i=0;i<configs.items.length;i++) {
  8771. var c = configs.items[i];
  8772. if (c.state instanceof RuleStopState) {
  8773. return true;
  8774. }
  8775. }
  8776. return false;
  8777. };
  8778. // Checks if all configurations in {@code configs} are in a
  8779. // {@link RuleStopState}. Configurations meeting this condition have reached
  8780. // the end of the decision rule (local context) or end of start rule (full
  8781. // context).
  8782. //
  8783. // @param configs the configuration set to test
  8784. // @return {@code true} if all configurations in {@code configs} are in a
  8785. // {@link RuleStopState}, otherwise {@code false}
  8786. PredictionMode.allConfigsInRuleStopStates = function(configs) {
  8787. for(var i=0;i<configs.items.length;i++) {
  8788. var c = configs.items[i];
  8789. if (!(c.state instanceof RuleStopState)) {
  8790. return false;
  8791. }
  8792. }
  8793. return true;
  8794. };
  8795. //
  8796. // Full LL prediction termination.
  8797. //
  8798. // <p>Can we stop looking ahead during ATN simulation or is there some
  8799. // uncertainty as to which alternative we will ultimately pick, after
  8800. // consuming more input? Even if there are partial conflicts, we might know
  8801. // that everything is going to resolve to the same minimum alternative. That
  8802. // means we can stop since no more lookahead will change that fact. On the
  8803. // other hand, there might be multiple conflicts that resolve to different
  8804. // minimums. That means we need more look ahead to decide which of those
  8805. // alternatives we should predict.</p>
  8806. //
  8807. // <p>The basic idea is to split the set of configurations {@code C}, into
  8808. // conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with
  8809. // non-conflicting configurations. Two configurations conflict if they have
  8810. // identical {@link ATNConfig//state} and {@link ATNConfig//context} values
  8811. // but different {@link ATNConfig//alt} value, e.g. {@code (s, i, ctx, _)}
  8812. // and {@code (s, j, ctx, _)} for {@code i!=j}.</p>
  8813. //
  8814. // <p>Reduce these configuration subsets to the set of possible alternatives.
  8815. // You can compute the alternative subsets in one pass as follows:</p>
  8816. //
  8817. // <p>{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in
  8818. // {@code C} holding {@code s} and {@code ctx} fixed.</p>
  8819. //
  8820. // <p>Or in pseudo-code, for each configuration {@code c} in {@code C}:</p>
  8821. //
  8822. // <pre>
  8823. // map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not
  8824. // alt and not pred
  8825. // </pre>
  8826. //
  8827. // <p>The values in {@code map} are the set of {@code A_s,ctx} sets.</p>
  8828. //
  8829. // <p>If {@code |A_s,ctx|=1} then there is no conflict associated with
  8830. // {@code s} and {@code ctx}.</p>
  8831. //
  8832. // <p>Reduce the subsets to singletons by choosing a minimum of each subset. If
  8833. // the union of these alternative subsets is a singleton, then no amount of
  8834. // more lookahead will help us. We will always pick that alternative. If,
  8835. // however, there is more than one alternative, then we are uncertain which
  8836. // alternative to predict and must continue looking for resolution. We may
  8837. // or may not discover an ambiguity in the future, even if there are no
  8838. // conflicting subsets this round.</p>
  8839. //
  8840. // <p>The biggest sin is to terminate early because it means we've made a
  8841. // decision but were uncertain as to the eventual outcome. We haven't used
  8842. // enough lookahead. On the other hand, announcing a conflict too late is no
  8843. // big deal; you will still have the conflict. It's just inefficient. It
  8844. // might even look until the end of file.</p>
  8845. //
  8846. // <p>No special consideration for semantic predicates is required because
  8847. // predicates are evaluated on-the-fly for full LL prediction, ensuring that
  8848. // no configuration contains a semantic context during the termination
  8849. // check.</p>
  8850. //
  8851. // <p><strong>CONFLICTING CONFIGS</strong></p>
  8852. //
  8853. // <p>Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict
  8854. // when {@code i!=j} but {@code x=x'}. Because we merge all
  8855. // {@code (s, i, _)} configurations together, that means that there are at
  8856. // most {@code n} configurations associated with state {@code s} for
  8857. // {@code n} possible alternatives in the decision. The merged stacks
  8858. // complicate the comparison of configuration contexts {@code x} and
  8859. // {@code x'}. Sam checks to see if one is a subset of the other by calling
  8860. // merge and checking to see if the merged result is either {@code x} or
  8861. // {@code x'}. If the {@code x} associated with lowest alternative {@code i}
  8862. // is the superset, then {@code i} is the only possible prediction since the
  8863. // others resolve to {@code min(i)} as well. However, if {@code x} is
  8864. // associated with {@code j>i} then at least one stack configuration for
  8865. // {@code j} is not in conflict with alternative {@code i}. The algorithm
  8866. // should keep going, looking for more lookahead due to the uncertainty.</p>
  8867. //
  8868. // <p>For simplicity, I'm doing a equality check between {@code x} and
  8869. // {@code x'} that lets the algorithm continue to consume lookahead longer
  8870. // than necessary. The reason I like the equality is of course the
  8871. // simplicity but also because that is the test you need to detect the
  8872. // alternatives that are actually in conflict.</p>
  8873. //
  8874. // <p><strong>CONTINUE/STOP RULE</strong></p>
  8875. //
  8876. // <p>Continue if union of resolved alternative sets from non-conflicting and
  8877. // conflicting alternative subsets has more than one alternative. We are
  8878. // uncertain about which alternative to predict.</p>
  8879. //
  8880. // <p>The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which
  8881. // alternatives are still in the running for the amount of input we've
  8882. // consumed at this point. The conflicting sets let us to strip away
  8883. // configurations that won't lead to more states because we resolve
  8884. // conflicts to the configuration with a minimum alternate for the
  8885. // conflicting set.</p>
  8886. //
  8887. // <p><strong>CASES</strong></p>
  8888. //
  8889. // <ul>
  8890. //
  8891. // <li>no conflicts and more than 1 alternative in set =&gt; continue</li>
  8892. //
  8893. // <li> {@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s, 3, z)},
  8894. // {@code (s', 1, y)}, {@code (s', 2, y)} yields non-conflicting set
  8895. // {@code {3}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
  8896. // {@code {1,3}} =&gt; continue
  8897. // </li>
  8898. //
  8899. // <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
  8900. // {@code (s', 2, y)}, {@code (s'', 1, z)} yields non-conflicting set
  8901. // {@code {1}} U conflicting sets {@code min({1,2})} U {@code min({1,2})} =
  8902. // {@code {1}} =&gt; stop and predict 1</li>
  8903. //
  8904. // <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 1, y)},
  8905. // {@code (s', 2, y)} yields conflicting, reduced sets {@code {1}} U
  8906. // {@code {1}} = {@code {1}} =&gt; stop and predict 1, can announce
  8907. // ambiguity {@code {1,2}}</li>
  8908. //
  8909. // <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 2, y)},
  8910. // {@code (s', 3, y)} yields conflicting, reduced sets {@code {1}} U
  8911. // {@code {2}} = {@code {1,2}} =&gt; continue</li>
  8912. //
  8913. // <li>{@code (s, 1, x)}, {@code (s, 2, x)}, {@code (s', 3, y)},
  8914. // {@code (s', 4, y)} yields conflicting, reduced sets {@code {1}} U
  8915. // {@code {3}} = {@code {1,3}} =&gt; continue</li>
  8916. //
  8917. // </ul>
  8918. //
  8919. // <p><strong>EXACT AMBIGUITY DETECTION</strong></p>
  8920. //
  8921. // <p>If all states report the same conflicting set of alternatives, then we
  8922. // know we have the exact ambiguity set.</p>
  8923. //
  8924. // <p><code>|A_<em>i</em>|&gt;1</code> and
  8925. // <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>
  8926. //
  8927. // <p>In other words, we continue examining lookahead until all {@code A_i}
  8928. // have more than one alternative and all {@code A_i} are the same. If
  8929. // {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate
  8930. // because the resolved set is {@code {1}}. To determine what the real
  8931. // ambiguity is, we have to know whether the ambiguity is between one and
  8932. // two or one and three so we keep going. We can only stop prediction when
  8933. // we need exact ambiguity detection when the sets look like
  8934. // {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...</p>
  8935. //
  8936. PredictionMode.resolvesToJustOneViableAlt = function(altsets) {
  8937. return PredictionMode.getSingleViableAlt(altsets);
  8938. };
  8939. //
  8940. // Determines if every alternative subset in {@code altsets} contains more
  8941. // than one alternative.
  8942. //
  8943. // @param altsets a collection of alternative subsets
  8944. // @return {@code true} if every {@link BitSet} in {@code altsets} has
  8945. // {@link BitSet//cardinality cardinality} &gt; 1, otherwise {@code false}
  8946. //
  8947. PredictionMode.allSubsetsConflict = function(altsets) {
  8948. return ! PredictionMode.hasNonConflictingAltSet(altsets);
  8949. };
  8950. //
  8951. // Determines if any single alternative subset in {@code altsets} contains
  8952. // exactly one alternative.
  8953. //
  8954. // @param altsets a collection of alternative subsets
  8955. // @return {@code true} if {@code altsets} contains a {@link BitSet} with
  8956. // {@link BitSet//cardinality cardinality} 1, otherwise {@code false}
  8957. //
  8958. PredictionMode.hasNonConflictingAltSet = function(altsets) {
  8959. for(var i=0;i<altsets.length;i++) {
  8960. var alts = altsets[i];
  8961. if (alts.length===1) {
  8962. return true;
  8963. }
  8964. }
  8965. return false;
  8966. };
  8967. //
  8968. // Determines if any single alternative subset in {@code altsets} contains
  8969. // more than one alternative.
  8970. //
  8971. // @param altsets a collection of alternative subsets
  8972. // @return {@code true} if {@code altsets} contains a {@link BitSet} with
  8973. // {@link BitSet//cardinality cardinality} &gt; 1, otherwise {@code false}
  8974. //
  8975. PredictionMode.hasConflictingAltSet = function(altsets) {
  8976. for(var i=0;i<altsets.length;i++) {
  8977. var alts = altsets[i];
  8978. if (alts.length>1) {
  8979. return true;
  8980. }
  8981. }
  8982. return false;
  8983. };
  8984. //
  8985. // Determines if every alternative subset in {@code altsets} is equivalent.
  8986. //
  8987. // @param altsets a collection of alternative subsets
  8988. // @return {@code true} if every member of {@code altsets} is equal to the
  8989. // others, otherwise {@code false}
  8990. //
  8991. PredictionMode.allSubsetsEqual = function(altsets) {
  8992. var first = null;
  8993. for(var i=0;i<altsets.length;i++) {
  8994. var alts = altsets[i];
  8995. if (first === null) {
  8996. first = alts;
  8997. } else if (alts!==first) {
  8998. return false;
  8999. }
  9000. }
  9001. return true;
  9002. };
  9003. //
  9004. // Returns the unique alternative predicted by all alternative subsets in
  9005. // {@code altsets}. If no such alternative exists, this method returns
  9006. // {@link ATN//INVALID_ALT_NUMBER}.
  9007. //
  9008. // @param altsets a collection of alternative subsets
  9009. //
  9010. PredictionMode.getUniqueAlt = function(altsets) {
  9011. var all = PredictionMode.getAlts(altsets);
  9012. if (all.length===1) {
  9013. return all.minValue();
  9014. } else {
  9015. return ATN.INVALID_ALT_NUMBER;
  9016. }
  9017. };
  9018. // Gets the complete set of represented alternatives for a collection of
  9019. // alternative subsets. This method returns the union of each {@link BitSet}
  9020. // in {@code altsets}.
  9021. //
  9022. // @param altsets a collection of alternative subsets
  9023. // @return the set of represented alternatives in {@code altsets}
  9024. //
  9025. PredictionMode.getAlts = function(altsets) {
  9026. var all = new BitSet();
  9027. altsets.map( function(alts) { all.or(alts); });
  9028. return all;
  9029. };
  9030. //
  9031. // This function gets the conflicting alt subsets from a configuration set.
  9032. // For each configuration {@code c} in {@code configs}:
  9033. //
  9034. // <pre>
  9035. // map[c] U= c.{@link ATNConfig//alt alt} // map hash/equals uses s and x, not
  9036. // alt and not pred
  9037. // </pre>
  9038. PredictionMode.getConflictingAltSubsets = function(configs) {
  9039. var configToAlts = new Map();
  9040. configToAlts.hashFunction = function(cfg) { hashStuff(cfg.state.stateNumber, cfg.context); };
  9041. configToAlts.equalsFunction = function(c1, c2) { return c1.state.stateNumber==c2.state.stateNumber && c1.context.equals(c2.context);}
  9042. configs.items.map(function(cfg) {
  9043. var alts = configToAlts.get(cfg);
  9044. if (alts === null) {
  9045. alts = new BitSet();
  9046. configToAlts.put(cfg, alts);
  9047. }
  9048. alts.add(cfg.alt);
  9049. });
  9050. return configToAlts.getValues();
  9051. };
  9052. //
  9053. // Get a map from state to alt subset from a configuration set. For each
  9054. // configuration {@code c} in {@code configs}:
  9055. //
  9056. // <pre>
  9057. // map[c.{@link ATNConfig//state state}] U= c.{@link ATNConfig//alt alt}
  9058. // </pre>
  9059. //
  9060. PredictionMode.getStateToAltMap = function(configs) {
  9061. var m = new AltDict();
  9062. configs.items.map(function(c) {
  9063. var alts = m.get(c.state);
  9064. if (alts === null) {
  9065. alts = new BitSet();
  9066. m.put(c.state, alts);
  9067. }
  9068. alts.add(c.alt);
  9069. });
  9070. return m;
  9071. };
  9072. PredictionMode.hasStateAssociatedWithOneAlt = function(configs) {
  9073. var values = PredictionMode.getStateToAltMap(configs).values();
  9074. for(var i=0;i<values.length;i++) {
  9075. if (values[i].length===1) {
  9076. return true;
  9077. }
  9078. }
  9079. return false;
  9080. };
  9081. PredictionMode.getSingleViableAlt = function(altsets) {
  9082. var result = null;
  9083. for(var i=0;i<altsets.length;i++) {
  9084. var alts = altsets[i];
  9085. var minAlt = alts.minValue();
  9086. if(result===null) {
  9087. result = minAlt;
  9088. } else if(result!==minAlt) { // more than 1 viable alt
  9089. return ATN.INVALID_ALT_NUMBER;
  9090. }
  9091. }
  9092. return result;
  9093. };
  9094. exports.PredictionMode = PredictionMode;
  9095. /***/ }),
  9096. /***/ "./node_modules/antlr4/atn/SemanticContext.js":
  9097. /*!****************************************************!*\
  9098. !*** ./node_modules/antlr4/atn/SemanticContext.js ***!
  9099. \****************************************************/
  9100. /*! no static exports found */
  9101. /***/ (function(module, exports, __webpack_require__) {
  9102. //
  9103. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9104. * Use of this file is governed by the BSD 3-clause license that
  9105. * can be found in the LICENSE.txt file in the project root.
  9106. */
  9107. //
  9108. // A tree structure used to record the semantic context in which
  9109. // an ATN configuration is valid. It's either a single predicate,
  9110. // a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}.
  9111. //
  9112. // <p>I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of
  9113. // {@link SemanticContext} within the scope of this outer class.</p>
  9114. //
  9115. var Set = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Set;
  9116. var Hash = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").Hash;
  9117. function SemanticContext() {
  9118. return this;
  9119. }
  9120. SemanticContext.prototype.hashCode = function() {
  9121. var hash = new Hash();
  9122. this.updateHashCode(hash);
  9123. return hash.finish();
  9124. };
  9125. // For context independent predicates, we evaluate them without a local
  9126. // context (i.e., null context). That way, we can evaluate them without
  9127. // having to create proper rule-specific context during prediction (as
  9128. // opposed to the parser, which creates them naturally). In a practical
  9129. // sense, this avoids a cast exception from RuleContext to myruleContext.
  9130. //
  9131. // <p>For context dependent predicates, we must pass in a local context so that
  9132. // references such as $arg evaluate properly as _localctx.arg. We only
  9133. // capture context dependent predicates in the context in which we begin
  9134. // prediction, so we passed in the outer context here in case of context
  9135. // dependent predicate evaluation.</p>
  9136. //
  9137. SemanticContext.prototype.evaluate = function(parser, outerContext) {
  9138. };
  9139. //
  9140. // Evaluate the precedence predicates for the context and reduce the result.
  9141. //
  9142. // @param parser The parser instance.
  9143. // @param outerContext The current parser context object.
  9144. // @return The simplified semantic context after precedence predicates are
  9145. // evaluated, which will be one of the following values.
  9146. // <ul>
  9147. // <li>{@link //NONE}: if the predicate simplifies to {@code true} after
  9148. // precedence predicates are evaluated.</li>
  9149. // <li>{@code null}: if the predicate simplifies to {@code false} after
  9150. // precedence predicates are evaluated.</li>
  9151. // <li>{@code this}: if the semantic context is not changed as a result of
  9152. // precedence predicate evaluation.</li>
  9153. // <li>A non-{@code null} {@link SemanticContext}: the new simplified
  9154. // semantic context after precedence predicates are evaluated.</li>
  9155. // </ul>
  9156. //
  9157. SemanticContext.prototype.evalPrecedence = function(parser, outerContext) {
  9158. return this;
  9159. };
  9160. SemanticContext.andContext = function(a, b) {
  9161. if (a === null || a === SemanticContext.NONE) {
  9162. return b;
  9163. }
  9164. if (b === null || b === SemanticContext.NONE) {
  9165. return a;
  9166. }
  9167. var result = new AND(a, b);
  9168. if (result.opnds.length === 1) {
  9169. return result.opnds[0];
  9170. } else {
  9171. return result;
  9172. }
  9173. };
  9174. SemanticContext.orContext = function(a, b) {
  9175. if (a === null) {
  9176. return b;
  9177. }
  9178. if (b === null) {
  9179. return a;
  9180. }
  9181. if (a === SemanticContext.NONE || b === SemanticContext.NONE) {
  9182. return SemanticContext.NONE;
  9183. }
  9184. var result = new OR(a, b);
  9185. if (result.opnds.length === 1) {
  9186. return result.opnds[0];
  9187. } else {
  9188. return result;
  9189. }
  9190. };
  9191. function Predicate(ruleIndex, predIndex, isCtxDependent) {
  9192. SemanticContext.call(this);
  9193. this.ruleIndex = ruleIndex === undefined ? -1 : ruleIndex;
  9194. this.predIndex = predIndex === undefined ? -1 : predIndex;
  9195. this.isCtxDependent = isCtxDependent === undefined ? false : isCtxDependent; // e.g., $i ref in pred
  9196. return this;
  9197. }
  9198. Predicate.prototype = Object.create(SemanticContext.prototype);
  9199. Predicate.prototype.constructor = Predicate;
  9200. //The default {@link SemanticContext}, which is semantically equivalent to
  9201. //a predicate of the form {@code {true}?}.
  9202. //
  9203. SemanticContext.NONE = new Predicate();
  9204. Predicate.prototype.evaluate = function(parser, outerContext) {
  9205. var localctx = this.isCtxDependent ? outerContext : null;
  9206. return parser.sempred(localctx, this.ruleIndex, this.predIndex);
  9207. };
  9208. Predicate.prototype.updateHashCode = function(hash) {
  9209. hash.update(this.ruleIndex, this.predIndex, this.isCtxDependent);
  9210. };
  9211. Predicate.prototype.equals = function(other) {
  9212. if (this === other) {
  9213. return true;
  9214. } else if (!(other instanceof Predicate)) {
  9215. return false;
  9216. } else {
  9217. return this.ruleIndex === other.ruleIndex &&
  9218. this.predIndex === other.predIndex &&
  9219. this.isCtxDependent === other.isCtxDependent;
  9220. }
  9221. };
  9222. Predicate.prototype.toString = function() {
  9223. return "{" + this.ruleIndex + ":" + this.predIndex + "}?";
  9224. };
  9225. function PrecedencePredicate(precedence) {
  9226. SemanticContext.call(this);
  9227. this.precedence = precedence === undefined ? 0 : precedence;
  9228. }
  9229. PrecedencePredicate.prototype = Object.create(SemanticContext.prototype);
  9230. PrecedencePredicate.prototype.constructor = PrecedencePredicate;
  9231. PrecedencePredicate.prototype.evaluate = function(parser, outerContext) {
  9232. return parser.precpred(outerContext, this.precedence);
  9233. };
  9234. PrecedencePredicate.prototype.evalPrecedence = function(parser, outerContext) {
  9235. if (parser.precpred(outerContext, this.precedence)) {
  9236. return SemanticContext.NONE;
  9237. } else {
  9238. return null;
  9239. }
  9240. };
  9241. PrecedencePredicate.prototype.compareTo = function(other) {
  9242. return this.precedence - other.precedence;
  9243. };
  9244. PrecedencePredicate.prototype.updateHashCode = function(hash) {
  9245. hash.update(31);
  9246. };
  9247. PrecedencePredicate.prototype.equals = function(other) {
  9248. if (this === other) {
  9249. return true;
  9250. } else if (!(other instanceof PrecedencePredicate)) {
  9251. return false;
  9252. } else {
  9253. return this.precedence === other.precedence;
  9254. }
  9255. };
  9256. PrecedencePredicate.prototype.toString = function() {
  9257. return "{"+this.precedence+">=prec}?";
  9258. };
  9259. PrecedencePredicate.filterPrecedencePredicates = function(set) {
  9260. var result = [];
  9261. set.values().map( function(context) {
  9262. if (context instanceof PrecedencePredicate) {
  9263. result.push(context);
  9264. }
  9265. });
  9266. return result;
  9267. };
  9268. // A semantic context which is true whenever none of the contained contexts
  9269. // is false.
  9270. //
  9271. function AND(a, b) {
  9272. SemanticContext.call(this);
  9273. var operands = new Set();
  9274. if (a instanceof AND) {
  9275. a.opnds.map(function(o) {
  9276. operands.add(o);
  9277. });
  9278. } else {
  9279. operands.add(a);
  9280. }
  9281. if (b instanceof AND) {
  9282. b.opnds.map(function(o) {
  9283. operands.add(o);
  9284. });
  9285. } else {
  9286. operands.add(b);
  9287. }
  9288. var precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
  9289. if (precedencePredicates.length > 0) {
  9290. // interested in the transition with the lowest precedence
  9291. var reduced = null;
  9292. precedencePredicates.map( function(p) {
  9293. if(reduced===null || p.precedence<reduced.precedence) {
  9294. reduced = p;
  9295. }
  9296. });
  9297. operands.add(reduced);
  9298. }
  9299. this.opnds = operands.values();
  9300. return this;
  9301. }
  9302. AND.prototype = Object.create(SemanticContext.prototype);
  9303. AND.prototype.constructor = AND;
  9304. AND.prototype.equals = function(other) {
  9305. if (this === other) {
  9306. return true;
  9307. } else if (!(other instanceof AND)) {
  9308. return false;
  9309. } else {
  9310. return this.opnds === other.opnds;
  9311. }
  9312. };
  9313. AND.prototype.updateHashCode = function(hash) {
  9314. hash.update(this.opnds, "AND");
  9315. };
  9316. //
  9317. // {@inheritDoc}
  9318. //
  9319. // <p>
  9320. // The evaluation of predicates by this context is short-circuiting, but
  9321. // unordered.</p>
  9322. //
  9323. AND.prototype.evaluate = function(parser, outerContext) {
  9324. for (var i = 0; i < this.opnds.length; i++) {
  9325. if (!this.opnds[i].evaluate(parser, outerContext)) {
  9326. return false;
  9327. }
  9328. }
  9329. return true;
  9330. };
  9331. AND.prototype.evalPrecedence = function(parser, outerContext) {
  9332. var differs = false;
  9333. var operands = [];
  9334. for (var i = 0; i < this.opnds.length; i++) {
  9335. var context = this.opnds[i];
  9336. var evaluated = context.evalPrecedence(parser, outerContext);
  9337. differs |= (evaluated !== context);
  9338. if (evaluated === null) {
  9339. // The AND context is false if any element is false
  9340. return null;
  9341. } else if (evaluated !== SemanticContext.NONE) {
  9342. // Reduce the result by skipping true elements
  9343. operands.push(evaluated);
  9344. }
  9345. }
  9346. if (!differs) {
  9347. return this;
  9348. }
  9349. if (operands.length === 0) {
  9350. // all elements were true, so the AND context is true
  9351. return SemanticContext.NONE;
  9352. }
  9353. var result = null;
  9354. operands.map(function(o) {
  9355. result = result === null ? o : SemanticContext.andContext(result, o);
  9356. });
  9357. return result;
  9358. };
  9359. AND.prototype.toString = function() {
  9360. var s = "";
  9361. this.opnds.map(function(o) {
  9362. s += "&& " + o.toString();
  9363. });
  9364. return s.length > 3 ? s.slice(3) : s;
  9365. };
  9366. //
  9367. // A semantic context which is true whenever at least one of the contained
  9368. // contexts is true.
  9369. //
  9370. function OR(a, b) {
  9371. SemanticContext.call(this);
  9372. var operands = new Set();
  9373. if (a instanceof OR) {
  9374. a.opnds.map(function(o) {
  9375. operands.add(o);
  9376. });
  9377. } else {
  9378. operands.add(a);
  9379. }
  9380. if (b instanceof OR) {
  9381. b.opnds.map(function(o) {
  9382. operands.add(o);
  9383. });
  9384. } else {
  9385. operands.add(b);
  9386. }
  9387. var precedencePredicates = PrecedencePredicate.filterPrecedencePredicates(operands);
  9388. if (precedencePredicates.length > 0) {
  9389. // interested in the transition with the highest precedence
  9390. var s = precedencePredicates.sort(function(a, b) {
  9391. return a.compareTo(b);
  9392. });
  9393. var reduced = s[s.length-1];
  9394. operands.add(reduced);
  9395. }
  9396. this.opnds = operands.values();
  9397. return this;
  9398. }
  9399. OR.prototype = Object.create(SemanticContext.prototype);
  9400. OR.prototype.constructor = OR;
  9401. OR.prototype.constructor = function(other) {
  9402. if (this === other) {
  9403. return true;
  9404. } else if (!(other instanceof OR)) {
  9405. return false;
  9406. } else {
  9407. return this.opnds === other.opnds;
  9408. }
  9409. };
  9410. OR.prototype.updateHashCode = function(hash) {
  9411. hash.update(this.opnds, "OR");
  9412. };
  9413. // <p>
  9414. // The evaluation of predicates by this context is short-circuiting, but
  9415. // unordered.</p>
  9416. //
  9417. OR.prototype.evaluate = function(parser, outerContext) {
  9418. for (var i = 0; i < this.opnds.length; i++) {
  9419. if (this.opnds[i].evaluate(parser, outerContext)) {
  9420. return true;
  9421. }
  9422. }
  9423. return false;
  9424. };
  9425. OR.prototype.evalPrecedence = function(parser, outerContext) {
  9426. var differs = false;
  9427. var operands = [];
  9428. for (var i = 0; i < this.opnds.length; i++) {
  9429. var context = this.opnds[i];
  9430. var evaluated = context.evalPrecedence(parser, outerContext);
  9431. differs |= (evaluated !== context);
  9432. if (evaluated === SemanticContext.NONE) {
  9433. // The OR context is true if any element is true
  9434. return SemanticContext.NONE;
  9435. } else if (evaluated !== null) {
  9436. // Reduce the result by skipping false elements
  9437. operands.push(evaluated);
  9438. }
  9439. }
  9440. if (!differs) {
  9441. return this;
  9442. }
  9443. if (operands.length === 0) {
  9444. // all elements were false, so the OR context is false
  9445. return null;
  9446. }
  9447. var result = null;
  9448. operands.map(function(o) {
  9449. return result === null ? o : SemanticContext.orContext(result, o);
  9450. });
  9451. return result;
  9452. };
  9453. OR.prototype.toString = function() {
  9454. var s = "";
  9455. this.opnds.map(function(o) {
  9456. s += "|| " + o.toString();
  9457. });
  9458. return s.length > 3 ? s.slice(3) : s;
  9459. };
  9460. exports.SemanticContext = SemanticContext;
  9461. exports.PrecedencePredicate = PrecedencePredicate;
  9462. exports.Predicate = Predicate;
  9463. /***/ }),
  9464. /***/ "./node_modules/antlr4/atn/Transition.js":
  9465. /*!***********************************************!*\
  9466. !*** ./node_modules/antlr4/atn/Transition.js ***!
  9467. \***********************************************/
  9468. /*! no static exports found */
  9469. /***/ (function(module, exports, __webpack_require__) {
  9470. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9471. * Use of this file is governed by the BSD 3-clause license that
  9472. * can be found in the LICENSE.txt file in the project root.
  9473. */
  9474. //
  9475. // An ATN transition between any two ATN states. Subclasses define
  9476. // atom, set, epsilon, action, predicate, rule transitions.
  9477. //
  9478. // <p>This is a one way link. It emanates from a state (usually via a list of
  9479. // transitions) and has a target state.</p>
  9480. //
  9481. // <p>Since we never have to change the ATN transitions once we construct it,
  9482. // we can fix these transitions as specific classes. The DFA transitions
  9483. // on the other hand need to update the labels as it adds transitions to
  9484. // the states. We'll use the term Edge for the DFA to distinguish them from
  9485. // ATN transitions.</p>
  9486. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  9487. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  9488. var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  9489. var Predicate = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").Predicate;
  9490. var PrecedencePredicate = __webpack_require__(/*! ./SemanticContext */ "./node_modules/antlr4/atn/SemanticContext.js").PrecedencePredicate;
  9491. function Transition (target) {
  9492. // The target of this transition.
  9493. if (target===undefined || target===null) {
  9494. throw "target cannot be null.";
  9495. }
  9496. this.target = target;
  9497. // Are we epsilon, action, sempred?
  9498. this.isEpsilon = false;
  9499. this.label = null;
  9500. return this;
  9501. }
  9502. // constants for serialization
  9503. Transition.EPSILON = 1;
  9504. Transition.RANGE = 2;
  9505. Transition.RULE = 3;
  9506. Transition.PREDICATE = 4; // e.g., {isType(input.LT(1))}?
  9507. Transition.ATOM = 5;
  9508. Transition.ACTION = 6;
  9509. Transition.SET = 7; // ~(A|B) or ~atom, wildcard, which convert to next 2
  9510. Transition.NOT_SET = 8;
  9511. Transition.WILDCARD = 9;
  9512. Transition.PRECEDENCE = 10;
  9513. Transition.serializationNames = [
  9514. "INVALID",
  9515. "EPSILON",
  9516. "RANGE",
  9517. "RULE",
  9518. "PREDICATE",
  9519. "ATOM",
  9520. "ACTION",
  9521. "SET",
  9522. "NOT_SET",
  9523. "WILDCARD",
  9524. "PRECEDENCE"
  9525. ];
  9526. Transition.serializationTypes = {
  9527. EpsilonTransition: Transition.EPSILON,
  9528. RangeTransition: Transition.RANGE,
  9529. RuleTransition: Transition.RULE,
  9530. PredicateTransition: Transition.PREDICATE,
  9531. AtomTransition: Transition.ATOM,
  9532. ActionTransition: Transition.ACTION,
  9533. SetTransition: Transition.SET,
  9534. NotSetTransition: Transition.NOT_SET,
  9535. WildcardTransition: Transition.WILDCARD,
  9536. PrecedencePredicateTransition: Transition.PRECEDENCE
  9537. };
  9538. // TODO: make all transitions sets? no, should remove set edges
  9539. function AtomTransition(target, label) {
  9540. Transition.call(this, target);
  9541. this.label_ = label; // The token type or character value; or, signifies special label.
  9542. this.label = this.makeLabel();
  9543. this.serializationType = Transition.ATOM;
  9544. return this;
  9545. }
  9546. AtomTransition.prototype = Object.create(Transition.prototype);
  9547. AtomTransition.prototype.constructor = AtomTransition;
  9548. AtomTransition.prototype.makeLabel = function() {
  9549. var s = new IntervalSet();
  9550. s.addOne(this.label_);
  9551. return s;
  9552. };
  9553. AtomTransition.prototype.matches = function( symbol, minVocabSymbol, maxVocabSymbol) {
  9554. return this.label_ === symbol;
  9555. };
  9556. AtomTransition.prototype.toString = function() {
  9557. return this.label_;
  9558. };
  9559. function RuleTransition(ruleStart, ruleIndex, precedence, followState) {
  9560. Transition.call(this, ruleStart);
  9561. this.ruleIndex = ruleIndex; // ptr to the rule definition object for this rule ref
  9562. this.precedence = precedence;
  9563. this.followState = followState; // what node to begin computations following ref to rule
  9564. this.serializationType = Transition.RULE;
  9565. this.isEpsilon = true;
  9566. return this;
  9567. }
  9568. RuleTransition.prototype = Object.create(Transition.prototype);
  9569. RuleTransition.prototype.constructor = RuleTransition;
  9570. RuleTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9571. return false;
  9572. };
  9573. function EpsilonTransition(target, outermostPrecedenceReturn) {
  9574. Transition.call(this, target);
  9575. this.serializationType = Transition.EPSILON;
  9576. this.isEpsilon = true;
  9577. this.outermostPrecedenceReturn = outermostPrecedenceReturn;
  9578. return this;
  9579. }
  9580. EpsilonTransition.prototype = Object.create(Transition.prototype);
  9581. EpsilonTransition.prototype.constructor = EpsilonTransition;
  9582. EpsilonTransition.prototype.matches = function( symbol, minVocabSymbol, maxVocabSymbol) {
  9583. return false;
  9584. };
  9585. EpsilonTransition.prototype.toString = function() {
  9586. return "epsilon";
  9587. };
  9588. function RangeTransition(target, start, stop) {
  9589. Transition.call(this, target);
  9590. this.serializationType = Transition.RANGE;
  9591. this.start = start;
  9592. this.stop = stop;
  9593. this.label = this.makeLabel();
  9594. return this;
  9595. }
  9596. RangeTransition.prototype = Object.create(Transition.prototype);
  9597. RangeTransition.prototype.constructor = RangeTransition;
  9598. RangeTransition.prototype.makeLabel = function() {
  9599. var s = new IntervalSet();
  9600. s.addRange(this.start, this.stop);
  9601. return s;
  9602. };
  9603. RangeTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9604. return symbol >= this.start && symbol <= this.stop;
  9605. };
  9606. RangeTransition.prototype.toString = function() {
  9607. return "'" + String.fromCharCode(this.start) + "'..'" + String.fromCharCode(this.stop) + "'";
  9608. };
  9609. function AbstractPredicateTransition(target) {
  9610. Transition.call(this, target);
  9611. return this;
  9612. }
  9613. AbstractPredicateTransition.prototype = Object.create(Transition.prototype);
  9614. AbstractPredicateTransition.prototype.constructor = AbstractPredicateTransition;
  9615. function PredicateTransition(target, ruleIndex, predIndex, isCtxDependent) {
  9616. AbstractPredicateTransition.call(this, target);
  9617. this.serializationType = Transition.PREDICATE;
  9618. this.ruleIndex = ruleIndex;
  9619. this.predIndex = predIndex;
  9620. this.isCtxDependent = isCtxDependent; // e.g., $i ref in pred
  9621. this.isEpsilon = true;
  9622. return this;
  9623. }
  9624. PredicateTransition.prototype = Object.create(AbstractPredicateTransition.prototype);
  9625. PredicateTransition.prototype.constructor = PredicateTransition;
  9626. PredicateTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9627. return false;
  9628. };
  9629. PredicateTransition.prototype.getPredicate = function() {
  9630. return new Predicate(this.ruleIndex, this.predIndex, this.isCtxDependent);
  9631. };
  9632. PredicateTransition.prototype.toString = function() {
  9633. return "pred_" + this.ruleIndex + ":" + this.predIndex;
  9634. };
  9635. function ActionTransition(target, ruleIndex, actionIndex, isCtxDependent) {
  9636. Transition.call(this, target);
  9637. this.serializationType = Transition.ACTION;
  9638. this.ruleIndex = ruleIndex;
  9639. this.actionIndex = actionIndex===undefined ? -1 : actionIndex;
  9640. this.isCtxDependent = isCtxDependent===undefined ? false : isCtxDependent; // e.g., $i ref in pred
  9641. this.isEpsilon = true;
  9642. return this;
  9643. }
  9644. ActionTransition.prototype = Object.create(Transition.prototype);
  9645. ActionTransition.prototype.constructor = ActionTransition;
  9646. ActionTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9647. return false;
  9648. };
  9649. ActionTransition.prototype.toString = function() {
  9650. return "action_" + this.ruleIndex + ":" + this.actionIndex;
  9651. };
  9652. // A transition containing a set of values.
  9653. function SetTransition(target, set) {
  9654. Transition.call(this, target);
  9655. this.serializationType = Transition.SET;
  9656. if (set !==undefined && set !==null) {
  9657. this.label = set;
  9658. } else {
  9659. this.label = new IntervalSet();
  9660. this.label.addOne(Token.INVALID_TYPE);
  9661. }
  9662. return this;
  9663. }
  9664. SetTransition.prototype = Object.create(Transition.prototype);
  9665. SetTransition.prototype.constructor = SetTransition;
  9666. SetTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9667. return this.label.contains(symbol);
  9668. };
  9669. SetTransition.prototype.toString = function() {
  9670. return this.label.toString();
  9671. };
  9672. function NotSetTransition(target, set) {
  9673. SetTransition.call(this, target, set);
  9674. this.serializationType = Transition.NOT_SET;
  9675. return this;
  9676. }
  9677. NotSetTransition.prototype = Object.create(SetTransition.prototype);
  9678. NotSetTransition.prototype.constructor = NotSetTransition;
  9679. NotSetTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9680. return symbol >= minVocabSymbol && symbol <= maxVocabSymbol &&
  9681. !SetTransition.prototype.matches.call(this, symbol, minVocabSymbol, maxVocabSymbol);
  9682. };
  9683. NotSetTransition.prototype.toString = function() {
  9684. return '~' + SetTransition.prototype.toString.call(this);
  9685. };
  9686. function WildcardTransition(target) {
  9687. Transition.call(this, target);
  9688. this.serializationType = Transition.WILDCARD;
  9689. return this;
  9690. }
  9691. WildcardTransition.prototype = Object.create(Transition.prototype);
  9692. WildcardTransition.prototype.constructor = WildcardTransition;
  9693. WildcardTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9694. return symbol >= minVocabSymbol && symbol <= maxVocabSymbol;
  9695. };
  9696. WildcardTransition.prototype.toString = function() {
  9697. return ".";
  9698. };
  9699. function PrecedencePredicateTransition(target, precedence) {
  9700. AbstractPredicateTransition.call(this, target);
  9701. this.serializationType = Transition.PRECEDENCE;
  9702. this.precedence = precedence;
  9703. this.isEpsilon = true;
  9704. return this;
  9705. }
  9706. PrecedencePredicateTransition.prototype = Object.create(AbstractPredicateTransition.prototype);
  9707. PrecedencePredicateTransition.prototype.constructor = PrecedencePredicateTransition;
  9708. PrecedencePredicateTransition.prototype.matches = function(symbol, minVocabSymbol, maxVocabSymbol) {
  9709. return false;
  9710. };
  9711. PrecedencePredicateTransition.prototype.getPredicate = function() {
  9712. return new PrecedencePredicate(this.precedence);
  9713. };
  9714. PrecedencePredicateTransition.prototype.toString = function() {
  9715. return this.precedence + " >= _p";
  9716. };
  9717. exports.Transition = Transition;
  9718. exports.AtomTransition = AtomTransition;
  9719. exports.SetTransition = SetTransition;
  9720. exports.NotSetTransition = NotSetTransition;
  9721. exports.RuleTransition = RuleTransition;
  9722. exports.ActionTransition = ActionTransition;
  9723. exports.EpsilonTransition = EpsilonTransition;
  9724. exports.RangeTransition = RangeTransition;
  9725. exports.WildcardTransition = WildcardTransition;
  9726. exports.PredicateTransition = PredicateTransition;
  9727. exports.PrecedencePredicateTransition = PrecedencePredicateTransition;
  9728. exports.AbstractPredicateTransition = AbstractPredicateTransition;
  9729. /***/ }),
  9730. /***/ "./node_modules/antlr4/atn/index.js":
  9731. /*!******************************************!*\
  9732. !*** ./node_modules/antlr4/atn/index.js ***!
  9733. \******************************************/
  9734. /*! no static exports found */
  9735. /***/ (function(module, exports, __webpack_require__) {
  9736. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9737. * Use of this file is governed by the BSD 3-clause license that
  9738. * can be found in the LICENSE.txt file in the project root.
  9739. */
  9740. exports.ATN = __webpack_require__(/*! ./ATN */ "./node_modules/antlr4/atn/ATN.js").ATN;
  9741. exports.ATNDeserializer = __webpack_require__(/*! ./ATNDeserializer */ "./node_modules/antlr4/atn/ATNDeserializer.js").ATNDeserializer;
  9742. exports.LexerATNSimulator = __webpack_require__(/*! ./LexerATNSimulator */ "./node_modules/antlr4/atn/LexerATNSimulator.js").LexerATNSimulator;
  9743. exports.ParserATNSimulator = __webpack_require__(/*! ./ParserATNSimulator */ "./node_modules/antlr4/atn/ParserATNSimulator.js").ParserATNSimulator;
  9744. exports.PredictionMode = __webpack_require__(/*! ./PredictionMode */ "./node_modules/antlr4/atn/PredictionMode.js").PredictionMode;
  9745. /***/ }),
  9746. /***/ "./node_modules/antlr4/dfa/DFA.js":
  9747. /*!****************************************!*\
  9748. !*** ./node_modules/antlr4/dfa/DFA.js ***!
  9749. \****************************************/
  9750. /*! no static exports found */
  9751. /***/ (function(module, exports, __webpack_require__) {
  9752. //
  9753. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9754. * Use of this file is governed by the BSD 3-clause license that
  9755. * can be found in the LICENSE.txt file in the project root.
  9756. */
  9757. var Set = __webpack_require__(/*! ../Utils */ "./node_modules/antlr4/Utils.js").Set;
  9758. var DFAState = __webpack_require__(/*! ./DFAState */ "./node_modules/antlr4/dfa/DFAState.js").DFAState;
  9759. var StarLoopEntryState = __webpack_require__(/*! ../atn/ATNState */ "./node_modules/antlr4/atn/ATNState.js").StarLoopEntryState;
  9760. var ATNConfigSet = __webpack_require__(/*! ./../atn/ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  9761. var DFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").DFASerializer;
  9762. var LexerDFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").LexerDFASerializer;
  9763. function DFA(atnStartState, decision) {
  9764. if (decision === undefined) {
  9765. decision = 0;
  9766. }
  9767. // From which ATN state did we create this DFA?
  9768. this.atnStartState = atnStartState;
  9769. this.decision = decision;
  9770. // A set of all DFA states. Use {@link Map} so we can get old state back
  9771. // ({@link Set} only allows you to see if it's there).
  9772. this._states = new Set();
  9773. this.s0 = null;
  9774. // {@code true} if this DFA is for a precedence decision; otherwise,
  9775. // {@code false}. This is the backing field for {@link //isPrecedenceDfa},
  9776. // {@link //setPrecedenceDfa}.
  9777. this.precedenceDfa = false;
  9778. if (atnStartState instanceof StarLoopEntryState)
  9779. {
  9780. if (atnStartState.isPrecedenceDecision) {
  9781. this.precedenceDfa = true;
  9782. var precedenceState = new DFAState(null, new ATNConfigSet());
  9783. precedenceState.edges = [];
  9784. precedenceState.isAcceptState = false;
  9785. precedenceState.requiresFullContext = false;
  9786. this.s0 = precedenceState;
  9787. }
  9788. }
  9789. return this;
  9790. }
  9791. // Get the start state for a specific precedence value.
  9792. //
  9793. // @param precedence The current precedence.
  9794. // @return The start state corresponding to the specified precedence, or
  9795. // {@code null} if no start state exists for the specified precedence.
  9796. //
  9797. // @throws IllegalStateException if this is not a precedence DFA.
  9798. // @see //isPrecedenceDfa()
  9799. DFA.prototype.getPrecedenceStartState = function(precedence) {
  9800. if (!(this.precedenceDfa)) {
  9801. throw ("Only precedence DFAs may contain a precedence start state.");
  9802. }
  9803. // s0.edges is never null for a precedence DFA
  9804. if (precedence < 0 || precedence >= this.s0.edges.length) {
  9805. return null;
  9806. }
  9807. return this.s0.edges[precedence] || null;
  9808. };
  9809. // Set the start state for a specific precedence value.
  9810. //
  9811. // @param precedence The current precedence.
  9812. // @param startState The start state corresponding to the specified
  9813. // precedence.
  9814. //
  9815. // @throws IllegalStateException if this is not a precedence DFA.
  9816. // @see //isPrecedenceDfa()
  9817. //
  9818. DFA.prototype.setPrecedenceStartState = function(precedence, startState) {
  9819. if (!(this.precedenceDfa)) {
  9820. throw ("Only precedence DFAs may contain a precedence start state.");
  9821. }
  9822. if (precedence < 0) {
  9823. return;
  9824. }
  9825. // synchronization on s0 here is ok. when the DFA is turned into a
  9826. // precedence DFA, s0 will be initialized once and not updated again
  9827. // s0.edges is never null for a precedence DFA
  9828. this.s0.edges[precedence] = startState;
  9829. };
  9830. //
  9831. // Sets whether this is a precedence DFA. If the specified value differs
  9832. // from the current DFA configuration, the following actions are taken;
  9833. // otherwise no changes are made to the current DFA.
  9834. //
  9835. // <ul>
  9836. // <li>The {@link //states} map is cleared</li>
  9837. // <li>If {@code precedenceDfa} is {@code false}, the initial state
  9838. // {@link //s0} is set to {@code null}; otherwise, it is initialized to a new
  9839. // {@link DFAState} with an empty outgoing {@link DFAState//edges} array to
  9840. // store the start states for individual precedence values.</li>
  9841. // <li>The {@link //precedenceDfa} field is updated</li>
  9842. // </ul>
  9843. //
  9844. // @param precedenceDfa {@code true} if this is a precedence DFA; otherwise,
  9845. // {@code false}
  9846. DFA.prototype.setPrecedenceDfa = function(precedenceDfa) {
  9847. if (this.precedenceDfa!==precedenceDfa) {
  9848. this._states = new DFAStatesSet();
  9849. if (precedenceDfa) {
  9850. var precedenceState = new DFAState(null, new ATNConfigSet());
  9851. precedenceState.edges = [];
  9852. precedenceState.isAcceptState = false;
  9853. precedenceState.requiresFullContext = false;
  9854. this.s0 = precedenceState;
  9855. } else {
  9856. this.s0 = null;
  9857. }
  9858. this.precedenceDfa = precedenceDfa;
  9859. }
  9860. };
  9861. Object.defineProperty(DFA.prototype, "states", {
  9862. get : function() {
  9863. return this._states;
  9864. }
  9865. });
  9866. // Return a list of all states in this DFA, ordered by state number.
  9867. DFA.prototype.sortedStates = function() {
  9868. var list = this._states.values();
  9869. return list.sort(function(a, b) {
  9870. return a.stateNumber - b.stateNumber;
  9871. });
  9872. };
  9873. DFA.prototype.toString = function(literalNames, symbolicNames) {
  9874. literalNames = literalNames || null;
  9875. symbolicNames = symbolicNames || null;
  9876. if (this.s0 === null) {
  9877. return "";
  9878. }
  9879. var serializer = new DFASerializer(this, literalNames, symbolicNames);
  9880. return serializer.toString();
  9881. };
  9882. DFA.prototype.toLexerString = function() {
  9883. if (this.s0 === null) {
  9884. return "";
  9885. }
  9886. var serializer = new LexerDFASerializer(this);
  9887. return serializer.toString();
  9888. };
  9889. exports.DFA = DFA;
  9890. /***/ }),
  9891. /***/ "./node_modules/antlr4/dfa/DFASerializer.js":
  9892. /*!**************************************************!*\
  9893. !*** ./node_modules/antlr4/dfa/DFASerializer.js ***!
  9894. \**************************************************/
  9895. /*! no static exports found */
  9896. /***/ (function(module, exports) {
  9897. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9898. * Use of this file is governed by the BSD 3-clause license that
  9899. * can be found in the LICENSE.txt file in the project root.
  9900. */
  9901. // A DFA walker that knows how to dump them to serialized strings.#/
  9902. function DFASerializer(dfa, literalNames, symbolicNames) {
  9903. this.dfa = dfa;
  9904. this.literalNames = literalNames || [];
  9905. this.symbolicNames = symbolicNames || [];
  9906. return this;
  9907. }
  9908. DFASerializer.prototype.toString = function() {
  9909. if(this.dfa.s0 === null) {
  9910. return null;
  9911. }
  9912. var buf = "";
  9913. var states = this.dfa.sortedStates();
  9914. for(var i=0;i<states.length;i++) {
  9915. var s = states[i];
  9916. if(s.edges!==null) {
  9917. var n = s.edges.length;
  9918. for(var j=0;j<n;j++) {
  9919. var t = s.edges[j] || null;
  9920. if(t!==null && t.stateNumber !== 0x7FFFFFFF) {
  9921. buf = buf.concat(this.getStateString(s));
  9922. buf = buf.concat("-");
  9923. buf = buf.concat(this.getEdgeLabel(j));
  9924. buf = buf.concat("->");
  9925. buf = buf.concat(this.getStateString(t));
  9926. buf = buf.concat('\n');
  9927. }
  9928. }
  9929. }
  9930. }
  9931. return buf.length===0 ? null : buf;
  9932. };
  9933. DFASerializer.prototype.getEdgeLabel = function(i) {
  9934. if (i===0) {
  9935. return "EOF";
  9936. } else if(this.literalNames !==null || this.symbolicNames!==null) {
  9937. return this.literalNames[i-1] || this.symbolicNames[i-1];
  9938. } else {
  9939. return String.fromCharCode(i-1);
  9940. }
  9941. };
  9942. DFASerializer.prototype.getStateString = function(s) {
  9943. var baseStateStr = ( s.isAcceptState ? ":" : "") + "s" + s.stateNumber + ( s.requiresFullContext ? "^" : "");
  9944. if(s.isAcceptState) {
  9945. if (s.predicates !== null) {
  9946. return baseStateStr + "=>" + s.predicates.toString();
  9947. } else {
  9948. return baseStateStr + "=>" + s.prediction.toString();
  9949. }
  9950. } else {
  9951. return baseStateStr;
  9952. }
  9953. };
  9954. function LexerDFASerializer(dfa) {
  9955. DFASerializer.call(this, dfa, null);
  9956. return this;
  9957. }
  9958. LexerDFASerializer.prototype = Object.create(DFASerializer.prototype);
  9959. LexerDFASerializer.prototype.constructor = LexerDFASerializer;
  9960. LexerDFASerializer.prototype.getEdgeLabel = function(i) {
  9961. return "'" + String.fromCharCode(i) + "'";
  9962. };
  9963. exports.DFASerializer = DFASerializer;
  9964. exports.LexerDFASerializer = LexerDFASerializer;
  9965. /***/ }),
  9966. /***/ "./node_modules/antlr4/dfa/DFAState.js":
  9967. /*!*********************************************!*\
  9968. !*** ./node_modules/antlr4/dfa/DFAState.js ***!
  9969. \*********************************************/
  9970. /*! no static exports found */
  9971. /***/ (function(module, exports, __webpack_require__) {
  9972. //
  9973. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  9974. * Use of this file is governed by the BSD 3-clause license that
  9975. * can be found in the LICENSE.txt file in the project root.
  9976. */
  9977. ///
  9978. var ATNConfigSet = __webpack_require__(/*! ./../atn/ATNConfigSet */ "./node_modules/antlr4/atn/ATNConfigSet.js").ATNConfigSet;
  9979. var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
  9980. var Hash = Utils.Hash;
  9981. var Set = Utils.Set;
  9982. // Map a predicate to a predicted alternative.///
  9983. function PredPrediction(pred, alt) {
  9984. this.alt = alt;
  9985. this.pred = pred;
  9986. return this;
  9987. }
  9988. PredPrediction.prototype.toString = function() {
  9989. return "(" + this.pred + ", " + this.alt + ")";
  9990. };
  9991. // A DFA state represents a set of possible ATN configurations.
  9992. // As Aho, Sethi, Ullman p. 117 says "The DFA uses its state
  9993. // to keep track of all possible states the ATN can be in after
  9994. // reading each input symbol. That is to say, after reading
  9995. // input a1a2..an, the DFA is in a state that represents the
  9996. // subset T of the states of the ATN that are reachable from the
  9997. // ATN's start state along some path labeled a1a2..an."
  9998. // In conventional NFA&rarr;DFA conversion, therefore, the subset T
  9999. // would be a bitset representing the set of states the
  10000. // ATN could be in. We need to track the alt predicted by each
  10001. // state as well, however. More importantly, we need to maintain
  10002. // a stack of states, tracking the closure operations as they
  10003. // jump from rule to rule, emulating rule invocations (method calls).
  10004. // I have to add a stack to simulate the proper lookahead sequences for
  10005. // the underlying LL grammar from which the ATN was derived.
  10006. //
  10007. // <p>I use a set of ATNConfig objects not simple states. An ATNConfig
  10008. // is both a state (ala normal conversion) and a RuleContext describing
  10009. // the chain of rules (if any) followed to arrive at that state.</p>
  10010. //
  10011. // <p>A DFA state may have multiple references to a particular state,
  10012. // but with different ATN contexts (with same or different alts)
  10013. // meaning that state was reached via a different set of rule invocations.</p>
  10014. // /
  10015. function DFAState(stateNumber, configs) {
  10016. if (stateNumber === null) {
  10017. stateNumber = -1;
  10018. }
  10019. if (configs === null) {
  10020. configs = new ATNConfigSet();
  10021. }
  10022. this.stateNumber = stateNumber;
  10023. this.configs = configs;
  10024. // {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)
  10025. // {@link Token//EOF} maps to {@code edges[0]}.
  10026. this.edges = null;
  10027. this.isAcceptState = false;
  10028. // if accept state, what ttype do we match or alt do we predict?
  10029. // This is set to {@link ATN//INVALID_ALT_NUMBER} when {@link
  10030. // //predicates}{@code !=null} or
  10031. // {@link //requiresFullContext}.
  10032. this.prediction = 0;
  10033. this.lexerActionExecutor = null;
  10034. // Indicates that this state was created during SLL prediction that
  10035. // discovered a conflict between the configurations in the state. Future
  10036. // {@link ParserATNSimulator//execATN} invocations immediately jumped doing
  10037. // full context prediction if this field is true.
  10038. this.requiresFullContext = false;
  10039. // During SLL parsing, this is a list of predicates associated with the
  10040. // ATN configurations of the DFA state. When we have predicates,
  10041. // {@link //requiresFullContext} is {@code false} since full context
  10042. // prediction evaluates predicates
  10043. // on-the-fly. If this is not null, then {@link //prediction} is
  10044. // {@link ATN//INVALID_ALT_NUMBER}.
  10045. //
  10046. // <p>We only use these for non-{@link //requiresFullContext} but
  10047. // conflicting states. That
  10048. // means we know from the context (it's $ or we don't dip into outer
  10049. // context) that it's an ambiguity not a conflict.</p>
  10050. //
  10051. // <p>This list is computed by {@link
  10052. // ParserATNSimulator//predicateDFAState}.</p>
  10053. this.predicates = null;
  10054. return this;
  10055. }
  10056. // Get the set of all alts mentioned by all ATN configurations in this
  10057. // DFA state.
  10058. DFAState.prototype.getAltSet = function() {
  10059. var alts = new Set();
  10060. if (this.configs !== null) {
  10061. for (var i = 0; i < this.configs.length; i++) {
  10062. var c = this.configs[i];
  10063. alts.add(c.alt);
  10064. }
  10065. }
  10066. if (alts.length === 0) {
  10067. return null;
  10068. } else {
  10069. return alts;
  10070. }
  10071. };
  10072. // Two {@link DFAState} instances are equal if their ATN configuration sets
  10073. // are the same. This method is used to see if a state already exists.
  10074. //
  10075. // <p>Because the number of alternatives and number of ATN configurations are
  10076. // finite, there is a finite number of DFA states that can be processed.
  10077. // This is necessary to show that the algorithm terminates.</p>
  10078. //
  10079. // <p>Cannot test the DFA state numbers here because in
  10080. // {@link ParserATNSimulator//addDFAState} we need to know if any other state
  10081. // exists that has this exact set of ATN configurations. The
  10082. // {@link //stateNumber} is irrelevant.</p>
  10083. DFAState.prototype.equals = function(other) {
  10084. // compare set of ATN configurations in this set with other
  10085. return this === other ||
  10086. (other instanceof DFAState &&
  10087. this.configs.equals(other.configs));
  10088. };
  10089. DFAState.prototype.toString = function() {
  10090. var s = "" + this.stateNumber + ":" + this.configs;
  10091. if(this.isAcceptState) {
  10092. s = s + "=>";
  10093. if (this.predicates !== null)
  10094. s = s + this.predicates;
  10095. else
  10096. s = s + this.prediction;
  10097. }
  10098. return s;
  10099. };
  10100. DFAState.prototype.hashCode = function() {
  10101. var hash = new Hash();
  10102. hash.update(this.configs);
  10103. return hash.finish();
  10104. };
  10105. exports.DFAState = DFAState;
  10106. exports.PredPrediction = PredPrediction;
  10107. /***/ }),
  10108. /***/ "./node_modules/antlr4/dfa/index.js":
  10109. /*!******************************************!*\
  10110. !*** ./node_modules/antlr4/dfa/index.js ***!
  10111. \******************************************/
  10112. /*! no static exports found */
  10113. /***/ (function(module, exports, __webpack_require__) {
  10114. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  10115. * Use of this file is governed by the BSD 3-clause license that
  10116. * can be found in the LICENSE.txt file in the project root.
  10117. */
  10118. exports.DFA = __webpack_require__(/*! ./DFA */ "./node_modules/antlr4/dfa/DFA.js").DFA;
  10119. exports.DFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").DFASerializer;
  10120. exports.LexerDFASerializer = __webpack_require__(/*! ./DFASerializer */ "./node_modules/antlr4/dfa/DFASerializer.js").LexerDFASerializer;
  10121. exports.PredPrediction = __webpack_require__(/*! ./DFAState */ "./node_modules/antlr4/dfa/DFAState.js").PredPrediction;
  10122. /***/ }),
  10123. /***/ "./node_modules/antlr4/error/DiagnosticErrorListener.js":
  10124. /*!**************************************************************!*\
  10125. !*** ./node_modules/antlr4/error/DiagnosticErrorListener.js ***!
  10126. \**************************************************************/
  10127. /*! no static exports found */
  10128. /***/ (function(module, exports, __webpack_require__) {
  10129. //
  10130. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  10131. * Use of this file is governed by the BSD 3-clause license that
  10132. * can be found in the LICENSE.txt file in the project root.
  10133. */
  10134. //
  10135. //
  10136. // This implementation of {@link ANTLRErrorListener} can be used to identify
  10137. // certain potential correctness and performance problems in grammars. "Reports"
  10138. // are made by calling {@link Parser//notifyErrorListeners} with the appropriate
  10139. // message.
  10140. //
  10141. // <ul>
  10142. // <li><b>Ambiguities</b>: These are cases where more than one path through the
  10143. // grammar can match the input.</li>
  10144. // <li><b>Weak context sensitivity</b>: These are cases where full-context
  10145. // prediction resolved an SLL conflict to a unique alternative which equaled the
  10146. // minimum alternative of the SLL conflict.</li>
  10147. // <li><b>Strong (forced) context sensitivity</b>: These are cases where the
  10148. // full-context prediction resolved an SLL conflict to a unique alternative,
  10149. // <em>and</em> the minimum alternative of the SLL conflict was found to not be
  10150. // a truly viable alternative. Two-stage parsing cannot be used for inputs where
  10151. // this situation occurs.</li>
  10152. // </ul>
  10153. var BitSet = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js").BitSet;
  10154. var ErrorListener = __webpack_require__(/*! ./ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ErrorListener;
  10155. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  10156. function DiagnosticErrorListener(exactOnly) {
  10157. ErrorListener.call(this);
  10158. exactOnly = exactOnly || true;
  10159. // whether all ambiguities or only exact ambiguities are reported.
  10160. this.exactOnly = exactOnly;
  10161. return this;
  10162. }
  10163. DiagnosticErrorListener.prototype = Object.create(ErrorListener.prototype);
  10164. DiagnosticErrorListener.prototype.constructor = DiagnosticErrorListener;
  10165. DiagnosticErrorListener.prototype.reportAmbiguity = function(recognizer, dfa,
  10166. startIndex, stopIndex, exact, ambigAlts, configs) {
  10167. if (this.exactOnly && !exact) {
  10168. return;
  10169. }
  10170. var msg = "reportAmbiguity d=" +
  10171. this.getDecisionDescription(recognizer, dfa) +
  10172. ": ambigAlts=" +
  10173. this.getConflictingAlts(ambigAlts, configs) +
  10174. ", input='" +
  10175. recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'";
  10176. recognizer.notifyErrorListeners(msg);
  10177. };
  10178. DiagnosticErrorListener.prototype.reportAttemptingFullContext = function(
  10179. recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
  10180. var msg = "reportAttemptingFullContext d=" +
  10181. this.getDecisionDescription(recognizer, dfa) +
  10182. ", input='" +
  10183. recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'";
  10184. recognizer.notifyErrorListeners(msg);
  10185. };
  10186. DiagnosticErrorListener.prototype.reportContextSensitivity = function(
  10187. recognizer, dfa, startIndex, stopIndex, prediction, configs) {
  10188. var msg = "reportContextSensitivity d=" +
  10189. this.getDecisionDescription(recognizer, dfa) +
  10190. ", input='" +
  10191. recognizer.getTokenStream().getText(new Interval(startIndex, stopIndex)) + "'";
  10192. recognizer.notifyErrorListeners(msg);
  10193. };
  10194. DiagnosticErrorListener.prototype.getDecisionDescription = function(recognizer, dfa) {
  10195. var decision = dfa.decision;
  10196. var ruleIndex = dfa.atnStartState.ruleIndex;
  10197. var ruleNames = recognizer.ruleNames;
  10198. if (ruleIndex < 0 || ruleIndex >= ruleNames.length) {
  10199. return "" + decision;
  10200. }
  10201. var ruleName = ruleNames[ruleIndex] || null;
  10202. if (ruleName === null || ruleName.length === 0) {
  10203. return "" + decision;
  10204. }
  10205. return "" + decision + " (" + ruleName + ")";
  10206. };
  10207. //
  10208. // Computes the set of conflicting or ambiguous alternatives from a
  10209. // configuration set, if that information was not already provided by the
  10210. // parser.
  10211. //
  10212. // @param reportedAlts The set of conflicting or ambiguous alternatives, as
  10213. // reported by the parser.
  10214. // @param configs The conflicting or ambiguous configuration set.
  10215. // @return Returns {@code reportedAlts} if it is not {@code null}, otherwise
  10216. // returns the set of alternatives represented in {@code configs}.
  10217. //
  10218. DiagnosticErrorListener.prototype.getConflictingAlts = function(reportedAlts, configs) {
  10219. if (reportedAlts !== null) {
  10220. return reportedAlts;
  10221. }
  10222. var result = new BitSet();
  10223. for (var i = 0; i < configs.items.length; i++) {
  10224. result.add(configs.items[i].alt);
  10225. }
  10226. return "{" + result.values().join(", ") + "}";
  10227. };
  10228. exports.DiagnosticErrorListener = DiagnosticErrorListener;
  10229. /***/ }),
  10230. /***/ "./node_modules/antlr4/error/ErrorListener.js":
  10231. /*!****************************************************!*\
  10232. !*** ./node_modules/antlr4/error/ErrorListener.js ***!
  10233. \****************************************************/
  10234. /*! no static exports found */
  10235. /***/ (function(module, exports) {
  10236. //
  10237. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  10238. * Use of this file is governed by the BSD 3-clause license that
  10239. * can be found in the LICENSE.txt file in the project root.
  10240. */
  10241. // Provides an empty default implementation of {@link ANTLRErrorListener}. The
  10242. // default implementation of each method does nothing, but can be overridden as
  10243. // necessary.
  10244. function ErrorListener() {
  10245. return this;
  10246. }
  10247. ErrorListener.prototype.syntaxError = function(recognizer, offendingSymbol, line, column, msg, e) {
  10248. };
  10249. ErrorListener.prototype.reportAmbiguity = function(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {
  10250. };
  10251. ErrorListener.prototype.reportAttemptingFullContext = function(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
  10252. };
  10253. ErrorListener.prototype.reportContextSensitivity = function(recognizer, dfa, startIndex, stopIndex, prediction, configs) {
  10254. };
  10255. function ConsoleErrorListener() {
  10256. ErrorListener.call(this);
  10257. return this;
  10258. }
  10259. ConsoleErrorListener.prototype = Object.create(ErrorListener.prototype);
  10260. ConsoleErrorListener.prototype.constructor = ConsoleErrorListener;
  10261. //
  10262. // Provides a default instance of {@link ConsoleErrorListener}.
  10263. //
  10264. ConsoleErrorListener.INSTANCE = new ConsoleErrorListener();
  10265. //
  10266. // {@inheritDoc}
  10267. //
  10268. // <p>
  10269. // This implementation prints messages to {@link System//err} containing the
  10270. // values of {@code line}, {@code charPositionInLine}, and {@code msg} using
  10271. // the following format.</p>
  10272. //
  10273. // <pre>
  10274. // line <em>line</em>:<em>charPositionInLine</em> <em>msg</em>
  10275. // </pre>
  10276. //
  10277. ConsoleErrorListener.prototype.syntaxError = function(recognizer, offendingSymbol, line, column, msg, e) {
  10278. console.error("line " + line + ":" + column + " " + msg);
  10279. };
  10280. function ProxyErrorListener(delegates) {
  10281. ErrorListener.call(this);
  10282. if (delegates===null) {
  10283. throw "delegates";
  10284. }
  10285. this.delegates = delegates;
  10286. return this;
  10287. }
  10288. ProxyErrorListener.prototype = Object.create(ErrorListener.prototype);
  10289. ProxyErrorListener.prototype.constructor = ProxyErrorListener;
  10290. ProxyErrorListener.prototype.syntaxError = function(recognizer, offendingSymbol, line, column, msg, e) {
  10291. this.delegates.map(function(d) { d.syntaxError(recognizer, offendingSymbol, line, column, msg, e); });
  10292. };
  10293. ProxyErrorListener.prototype.reportAmbiguity = function(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) {
  10294. this.delegates.map(function(d) { d.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs); });
  10295. };
  10296. ProxyErrorListener.prototype.reportAttemptingFullContext = function(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) {
  10297. this.delegates.map(function(d) { d.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs); });
  10298. };
  10299. ProxyErrorListener.prototype.reportContextSensitivity = function(recognizer, dfa, startIndex, stopIndex, prediction, configs) {
  10300. this.delegates.map(function(d) { d.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs); });
  10301. };
  10302. exports.ErrorListener = ErrorListener;
  10303. exports.ConsoleErrorListener = ConsoleErrorListener;
  10304. exports.ProxyErrorListener = ProxyErrorListener;
  10305. /***/ }),
  10306. /***/ "./node_modules/antlr4/error/ErrorStrategy.js":
  10307. /*!****************************************************!*\
  10308. !*** ./node_modules/antlr4/error/ErrorStrategy.js ***!
  10309. \****************************************************/
  10310. /*! no static exports found */
  10311. /***/ (function(module, exports, __webpack_require__) {
  10312. //
  10313. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  10314. * Use of this file is governed by the BSD 3-clause license that
  10315. * can be found in the LICENSE.txt file in the project root.
  10316. */
  10317. //
  10318. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  10319. var Errors = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js");
  10320. var NoViableAltException = Errors.NoViableAltException;
  10321. var InputMismatchException = Errors.InputMismatchException;
  10322. var FailedPredicateException = Errors.FailedPredicateException;
  10323. var ParseCancellationException = Errors.ParseCancellationException;
  10324. var ATNState = __webpack_require__(/*! ./../atn/ATNState */ "./node_modules/antlr4/atn/ATNState.js").ATNState;
  10325. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  10326. var IntervalSet = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").IntervalSet;
  10327. function ErrorStrategy() {
  10328. }
  10329. ErrorStrategy.prototype.reset = function(recognizer){
  10330. };
  10331. ErrorStrategy.prototype.recoverInline = function(recognizer){
  10332. };
  10333. ErrorStrategy.prototype.recover = function(recognizer, e){
  10334. };
  10335. ErrorStrategy.prototype.sync = function(recognizer){
  10336. };
  10337. ErrorStrategy.prototype.inErrorRecoveryMode = function(recognizer){
  10338. };
  10339. ErrorStrategy.prototype.reportError = function(recognizer){
  10340. };
  10341. // This is the default implementation of {@link ANTLRErrorStrategy} used for
  10342. // error reporting and recovery in ANTLR parsers.
  10343. //
  10344. function DefaultErrorStrategy() {
  10345. ErrorStrategy.call(this);
  10346. // Indicates whether the error strategy is currently "recovering from an
  10347. // error". This is used to suppress reporting multiple error messages while
  10348. // attempting to recover from a detected syntax error.
  10349. //
  10350. // @see //inErrorRecoveryMode
  10351. //
  10352. this.errorRecoveryMode = false;
  10353. // The index into the input stream where the last error occurred.
  10354. // This is used to prevent infinite loops where an error is found
  10355. // but no token is consumed during recovery...another error is found,
  10356. // ad nauseum. This is a failsafe mechanism to guarantee that at least
  10357. // one token/tree node is consumed for two errors.
  10358. //
  10359. this.lastErrorIndex = -1;
  10360. this.lastErrorStates = null;
  10361. return this;
  10362. }
  10363. DefaultErrorStrategy.prototype = Object.create(ErrorStrategy.prototype);
  10364. DefaultErrorStrategy.prototype.constructor = DefaultErrorStrategy;
  10365. // <p>The default implementation simply calls {@link //endErrorCondition} to
  10366. // ensure that the handler is not in error recovery mode.</p>
  10367. DefaultErrorStrategy.prototype.reset = function(recognizer) {
  10368. this.endErrorCondition(recognizer);
  10369. };
  10370. //
  10371. // This method is called to enter error recovery mode when a recognition
  10372. // exception is reported.
  10373. //
  10374. // @param recognizer the parser instance
  10375. //
  10376. DefaultErrorStrategy.prototype.beginErrorCondition = function(recognizer) {
  10377. this.errorRecoveryMode = true;
  10378. };
  10379. DefaultErrorStrategy.prototype.inErrorRecoveryMode = function(recognizer) {
  10380. return this.errorRecoveryMode;
  10381. };
  10382. //
  10383. // This method is called to leave error recovery mode after recovering from
  10384. // a recognition exception.
  10385. //
  10386. // @param recognizer
  10387. //
  10388. DefaultErrorStrategy.prototype.endErrorCondition = function(recognizer) {
  10389. this.errorRecoveryMode = false;
  10390. this.lastErrorStates = null;
  10391. this.lastErrorIndex = -1;
  10392. };
  10393. //
  10394. // {@inheritDoc}
  10395. //
  10396. // <p>The default implementation simply calls {@link //endErrorCondition}.</p>
  10397. //
  10398. DefaultErrorStrategy.prototype.reportMatch = function(recognizer) {
  10399. this.endErrorCondition(recognizer);
  10400. };
  10401. //
  10402. // {@inheritDoc}
  10403. //
  10404. // <p>The default implementation returns immediately if the handler is already
  10405. // in error recovery mode. Otherwise, it calls {@link //beginErrorCondition}
  10406. // and dispatches the reporting task based on the runtime type of {@code e}
  10407. // according to the following table.</p>
  10408. //
  10409. // <ul>
  10410. // <li>{@link NoViableAltException}: Dispatches the call to
  10411. // {@link //reportNoViableAlternative}</li>
  10412. // <li>{@link InputMismatchException}: Dispatches the call to
  10413. // {@link //reportInputMismatch}</li>
  10414. // <li>{@link FailedPredicateException}: Dispatches the call to
  10415. // {@link //reportFailedPredicate}</li>
  10416. // <li>All other types: calls {@link Parser//notifyErrorListeners} to report
  10417. // the exception</li>
  10418. // </ul>
  10419. //
  10420. DefaultErrorStrategy.prototype.reportError = function(recognizer, e) {
  10421. // if we've already reported an error and have not matched a token
  10422. // yet successfully, don't report any errors.
  10423. if(this.inErrorRecoveryMode(recognizer)) {
  10424. return; // don't report spurious errors
  10425. }
  10426. this.beginErrorCondition(recognizer);
  10427. if ( e instanceof NoViableAltException ) {
  10428. this.reportNoViableAlternative(recognizer, e);
  10429. } else if ( e instanceof InputMismatchException ) {
  10430. this.reportInputMismatch(recognizer, e);
  10431. } else if ( e instanceof FailedPredicateException ) {
  10432. this.reportFailedPredicate(recognizer, e);
  10433. } else {
  10434. console.log("unknown recognition error type: " + e.constructor.name);
  10435. console.log(e.stack);
  10436. recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);
  10437. }
  10438. };
  10439. //
  10440. // {@inheritDoc}
  10441. //
  10442. // <p>The default implementation resynchronizes the parser by consuming tokens
  10443. // until we find one in the resynchronization set--loosely the set of tokens
  10444. // that can follow the current rule.</p>
  10445. //
  10446. DefaultErrorStrategy.prototype.recover = function(recognizer, e) {
  10447. if (this.lastErrorIndex===recognizer.getInputStream().index &&
  10448. this.lastErrorStates !== null && this.lastErrorStates.indexOf(recognizer.state)>=0) {
  10449. // uh oh, another error at same token index and previously-visited
  10450. // state in ATN; must be a case where LT(1) is in the recovery
  10451. // token set so nothing got consumed. Consume a single token
  10452. // at least to prevent an infinite loop; this is a failsafe.
  10453. recognizer.consume();
  10454. }
  10455. this.lastErrorIndex = recognizer._input.index;
  10456. if (this.lastErrorStates === null) {
  10457. this.lastErrorStates = [];
  10458. }
  10459. this.lastErrorStates.push(recognizer.state);
  10460. var followSet = this.getErrorRecoverySet(recognizer);
  10461. this.consumeUntil(recognizer, followSet);
  10462. };
  10463. // The default implementation of {@link ANTLRErrorStrategy//sync} makes sure
  10464. // that the current lookahead symbol is consistent with what were expecting
  10465. // at this point in the ATN. You can call this anytime but ANTLR only
  10466. // generates code to check before subrules/loops and each iteration.
  10467. //
  10468. // <p>Implements Jim Idle's magic sync mechanism in closures and optional
  10469. // subrules. E.g.,</p>
  10470. //
  10471. // <pre>
  10472. // a : sync ( stuff sync )* ;
  10473. // sync : {consume to what can follow sync} ;
  10474. // </pre>
  10475. //
  10476. // At the start of a sub rule upon error, {@link //sync} performs single
  10477. // token deletion, if possible. If it can't do that, it bails on the current
  10478. // rule and uses the default error recovery, which consumes until the
  10479. // resynchronization set of the current rule.
  10480. //
  10481. // <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block
  10482. // with an empty alternative), then the expected set includes what follows
  10483. // the subrule.</p>
  10484. //
  10485. // <p>During loop iteration, it consumes until it sees a token that can start a
  10486. // sub rule or what follows loop. Yes, that is pretty aggressive. We opt to
  10487. // stay in the loop as long as possible.</p>
  10488. //
  10489. // <p><strong>ORIGINS</strong></p>
  10490. //
  10491. // <p>Previous versions of ANTLR did a poor job of their recovery within loops.
  10492. // A single mismatch token or missing token would force the parser to bail
  10493. // out of the entire rules surrounding the loop. So, for rule</p>
  10494. //
  10495. // <pre>
  10496. // classDef : 'class' ID '{' member* '}'
  10497. // </pre>
  10498. //
  10499. // input with an extra token between members would force the parser to
  10500. // consume until it found the next class definition rather than the next
  10501. // member definition of the current class.
  10502. //
  10503. // <p>This functionality cost a little bit of effort because the parser has to
  10504. // compare token set at the start of the loop and at each iteration. If for
  10505. // some reason speed is suffering for you, you can turn off this
  10506. // functionality by simply overriding this method as a blank { }.</p>
  10507. //
  10508. DefaultErrorStrategy.prototype.sync = function(recognizer) {
  10509. // If already recovering, don't try to sync
  10510. if (this.inErrorRecoveryMode(recognizer)) {
  10511. return;
  10512. }
  10513. var s = recognizer._interp.atn.states[recognizer.state];
  10514. var la = recognizer.getTokenStream().LA(1);
  10515. // try cheaper subset first; might get lucky. seems to shave a wee bit off
  10516. var nextTokens = recognizer.atn.nextTokens(s);
  10517. if (nextTokens.contains(Token.EPSILON) || nextTokens.contains(la)) {
  10518. return;
  10519. }
  10520. switch (s.stateType) {
  10521. case ATNState.BLOCK_START:
  10522. case ATNState.STAR_BLOCK_START:
  10523. case ATNState.PLUS_BLOCK_START:
  10524. case ATNState.STAR_LOOP_ENTRY:
  10525. // report error and recover if possible
  10526. if( this.singleTokenDeletion(recognizer) !== null) {
  10527. return;
  10528. } else {
  10529. throw new InputMismatchException(recognizer);
  10530. }
  10531. break;
  10532. case ATNState.PLUS_LOOP_BACK:
  10533. case ATNState.STAR_LOOP_BACK:
  10534. this.reportUnwantedToken(recognizer);
  10535. var expecting = new IntervalSet();
  10536. expecting.addSet(recognizer.getExpectedTokens());
  10537. var whatFollowsLoopIterationOrRule = expecting.addSet(this.getErrorRecoverySet(recognizer));
  10538. this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule);
  10539. break;
  10540. default:
  10541. // do nothing if we can't identify the exact kind of ATN state
  10542. }
  10543. };
  10544. // This is called by {@link //reportError} when the exception is a
  10545. // {@link NoViableAltException}.
  10546. //
  10547. // @see //reportError
  10548. //
  10549. // @param recognizer the parser instance
  10550. // @param e the recognition exception
  10551. //
  10552. DefaultErrorStrategy.prototype.reportNoViableAlternative = function(recognizer, e) {
  10553. var tokens = recognizer.getTokenStream();
  10554. var input;
  10555. if(tokens !== null) {
  10556. if (e.startToken.type===Token.EOF) {
  10557. input = "<EOF>";
  10558. } else {
  10559. input = tokens.getText(new Interval(e.startToken.tokenIndex, e.offendingToken.tokenIndex));
  10560. }
  10561. } else {
  10562. input = "<unknown input>";
  10563. }
  10564. var msg = "no viable alternative at input " + this.escapeWSAndQuote(input);
  10565. recognizer.notifyErrorListeners(msg, e.offendingToken, e);
  10566. };
  10567. //
  10568. // This is called by {@link //reportError} when the exception is an
  10569. // {@link InputMismatchException}.
  10570. //
  10571. // @see //reportError
  10572. //
  10573. // @param recognizer the parser instance
  10574. // @param e the recognition exception
  10575. //
  10576. DefaultErrorStrategy.prototype.reportInputMismatch = function(recognizer, e) {
  10577. var msg = "mismatched input " + this.getTokenErrorDisplay(e.offendingToken) +
  10578. " expecting " + e.getExpectedTokens().toString(recognizer.literalNames, recognizer.symbolicNames);
  10579. recognizer.notifyErrorListeners(msg, e.offendingToken, e);
  10580. };
  10581. //
  10582. // This is called by {@link //reportError} when the exception is a
  10583. // {@link FailedPredicateException}.
  10584. //
  10585. // @see //reportError
  10586. //
  10587. // @param recognizer the parser instance
  10588. // @param e the recognition exception
  10589. //
  10590. DefaultErrorStrategy.prototype.reportFailedPredicate = function(recognizer, e) {
  10591. var ruleName = recognizer.ruleNames[recognizer._ctx.ruleIndex];
  10592. var msg = "rule " + ruleName + " " + e.message;
  10593. recognizer.notifyErrorListeners(msg, e.offendingToken, e);
  10594. };
  10595. // This method is called to report a syntax error which requires the removal
  10596. // of a token from the input stream. At the time this method is called, the
  10597. // erroneous symbol is current {@code LT(1)} symbol and has not yet been
  10598. // removed from the input stream. When this method returns,
  10599. // {@code recognizer} is in error recovery mode.
  10600. //
  10601. // <p>This method is called when {@link //singleTokenDeletion} identifies
  10602. // single-token deletion as a viable recovery strategy for a mismatched
  10603. // input error.</p>
  10604. //
  10605. // <p>The default implementation simply returns if the handler is already in
  10606. // error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to
  10607. // enter error recovery mode, followed by calling
  10608. // {@link Parser//notifyErrorListeners}.</p>
  10609. //
  10610. // @param recognizer the parser instance
  10611. //
  10612. DefaultErrorStrategy.prototype.reportUnwantedToken = function(recognizer) {
  10613. if (this.inErrorRecoveryMode(recognizer)) {
  10614. return;
  10615. }
  10616. this.beginErrorCondition(recognizer);
  10617. var t = recognizer.getCurrentToken();
  10618. var tokenName = this.getTokenErrorDisplay(t);
  10619. var expecting = this.getExpectedTokens(recognizer);
  10620. var msg = "extraneous input " + tokenName + " expecting " +
  10621. expecting.toString(recognizer.literalNames, recognizer.symbolicNames);
  10622. recognizer.notifyErrorListeners(msg, t, null);
  10623. };
  10624. // This method is called to report a syntax error which requires the
  10625. // insertion of a missing token into the input stream. At the time this
  10626. // method is called, the missing token has not yet been inserted. When this
  10627. // method returns, {@code recognizer} is in error recovery mode.
  10628. //
  10629. // <p>This method is called when {@link //singleTokenInsertion} identifies
  10630. // single-token insertion as a viable recovery strategy for a mismatched
  10631. // input error.</p>
  10632. //
  10633. // <p>The default implementation simply returns if the handler is already in
  10634. // error recovery mode. Otherwise, it calls {@link //beginErrorCondition} to
  10635. // enter error recovery mode, followed by calling
  10636. // {@link Parser//notifyErrorListeners}.</p>
  10637. //
  10638. // @param recognizer the parser instance
  10639. //
  10640. DefaultErrorStrategy.prototype.reportMissingToken = function(recognizer) {
  10641. if ( this.inErrorRecoveryMode(recognizer)) {
  10642. return;
  10643. }
  10644. this.beginErrorCondition(recognizer);
  10645. var t = recognizer.getCurrentToken();
  10646. var expecting = this.getExpectedTokens(recognizer);
  10647. var msg = "missing " + expecting.toString(recognizer.literalNames, recognizer.symbolicNames) +
  10648. " at " + this.getTokenErrorDisplay(t);
  10649. recognizer.notifyErrorListeners(msg, t, null);
  10650. };
  10651. // <p>The default implementation attempts to recover from the mismatched input
  10652. // by using single token insertion and deletion as described below. If the
  10653. // recovery attempt fails, this method throws an
  10654. // {@link InputMismatchException}.</p>
  10655. //
  10656. // <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>
  10657. //
  10658. // <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the
  10659. // right token, however, then assume {@code LA(1)} is some extra spurious
  10660. // token and delete it. Then consume and return the next token (which was
  10661. // the {@code LA(2)} token) as the successful result of the match operation.</p>
  10662. //
  10663. // <p>This recovery strategy is implemented by {@link
  10664. // //singleTokenDeletion}.</p>
  10665. //
  10666. // <p><strong>MISSING TOKEN</strong> (single token insertion)</p>
  10667. //
  10668. // <p>If current token (at {@code LA(1)}) is consistent with what could come
  10669. // after the expected {@code LA(1)} token, then assume the token is missing
  10670. // and use the parser's {@link TokenFactory} to create it on the fly. The
  10671. // "insertion" is performed by returning the created token as the successful
  10672. // result of the match operation.</p>
  10673. //
  10674. // <p>This recovery strategy is implemented by {@link
  10675. // //singleTokenInsertion}.</p>
  10676. //
  10677. // <p><strong>EXAMPLE</strong></p>
  10678. //
  10679. // <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When
  10680. // the parser returns from the nested call to {@code expr}, it will have
  10681. // call chain:</p>
  10682. //
  10683. // <pre>
  10684. // stat &rarr; expr &rarr; atom
  10685. // </pre>
  10686. //
  10687. // and it will be trying to match the {@code ')'} at this point in the
  10688. // derivation:
  10689. //
  10690. // <pre>
  10691. // =&gt; ID '=' '(' INT ')' ('+' atom)* ';'
  10692. // ^
  10693. // </pre>
  10694. //
  10695. // The attempt to match {@code ')'} will fail when it sees {@code ';'} and
  10696. // call {@link //recoverInline}. To recover, it sees that {@code LA(1)==';'}
  10697. // is in the set of tokens that can follow the {@code ')'} token reference
  10698. // in rule {@code atom}. It can assume that you forgot the {@code ')'}.
  10699. //
  10700. DefaultErrorStrategy.prototype.recoverInline = function(recognizer) {
  10701. // SINGLE TOKEN DELETION
  10702. var matchedSymbol = this.singleTokenDeletion(recognizer);
  10703. if (matchedSymbol !== null) {
  10704. // we have deleted the extra token.
  10705. // now, move past ttype token as if all were ok
  10706. recognizer.consume();
  10707. return matchedSymbol;
  10708. }
  10709. // SINGLE TOKEN INSERTION
  10710. if (this.singleTokenInsertion(recognizer)) {
  10711. return this.getMissingSymbol(recognizer);
  10712. }
  10713. // even that didn't work; must throw the exception
  10714. throw new InputMismatchException(recognizer);
  10715. };
  10716. //
  10717. // This method implements the single-token insertion inline error recovery
  10718. // strategy. It is called by {@link //recoverInline} if the single-token
  10719. // deletion strategy fails to recover from the mismatched input. If this
  10720. // method returns {@code true}, {@code recognizer} will be in error recovery
  10721. // mode.
  10722. //
  10723. // <p>This method determines whether or not single-token insertion is viable by
  10724. // checking if the {@code LA(1)} input symbol could be successfully matched
  10725. // if it were instead the {@code LA(2)} symbol. If this method returns
  10726. // {@code true}, the caller is responsible for creating and inserting a
  10727. // token with the correct type to produce this behavior.</p>
  10728. //
  10729. // @param recognizer the parser instance
  10730. // @return {@code true} if single-token insertion is a viable recovery
  10731. // strategy for the current mismatched input, otherwise {@code false}
  10732. //
  10733. DefaultErrorStrategy.prototype.singleTokenInsertion = function(recognizer) {
  10734. var currentSymbolType = recognizer.getTokenStream().LA(1);
  10735. // if current token is consistent with what could come after current
  10736. // ATN state, then we know we're missing a token; error recovery
  10737. // is free to conjure up and insert the missing token
  10738. var atn = recognizer._interp.atn;
  10739. var currentState = atn.states[recognizer.state];
  10740. var next = currentState.transitions[0].target;
  10741. var expectingAtLL2 = atn.nextTokens(next, recognizer._ctx);
  10742. if (expectingAtLL2.contains(currentSymbolType) ){
  10743. this.reportMissingToken(recognizer);
  10744. return true;
  10745. } else {
  10746. return false;
  10747. }
  10748. };
  10749. // This method implements the single-token deletion inline error recovery
  10750. // strategy. It is called by {@link //recoverInline} to attempt to recover
  10751. // from mismatched input. If this method returns null, the parser and error
  10752. // handler state will not have changed. If this method returns non-null,
  10753. // {@code recognizer} will <em>not</em> be in error recovery mode since the
  10754. // returned token was a successful match.
  10755. //
  10756. // <p>If the single-token deletion is successful, this method calls
  10757. // {@link //reportUnwantedToken} to report the error, followed by
  10758. // {@link Parser//consume} to actually "delete" the extraneous token. Then,
  10759. // before returning {@link //reportMatch} is called to signal a successful
  10760. // match.</p>
  10761. //
  10762. // @param recognizer the parser instance
  10763. // @return the successfully matched {@link Token} instance if single-token
  10764. // deletion successfully recovers from the mismatched input, otherwise
  10765. // {@code null}
  10766. //
  10767. DefaultErrorStrategy.prototype.singleTokenDeletion = function(recognizer) {
  10768. var nextTokenType = recognizer.getTokenStream().LA(2);
  10769. var expecting = this.getExpectedTokens(recognizer);
  10770. if (expecting.contains(nextTokenType)) {
  10771. this.reportUnwantedToken(recognizer);
  10772. // print("recoverFromMismatchedToken deleting " \
  10773. // + str(recognizer.getTokenStream().LT(1)) \
  10774. // + " since " + str(recognizer.getTokenStream().LT(2)) \
  10775. // + " is what we want", file=sys.stderr)
  10776. recognizer.consume(); // simply delete extra token
  10777. // we want to return the token we're actually matching
  10778. var matchedSymbol = recognizer.getCurrentToken();
  10779. this.reportMatch(recognizer); // we know current token is correct
  10780. return matchedSymbol;
  10781. } else {
  10782. return null;
  10783. }
  10784. };
  10785. // Conjure up a missing token during error recovery.
  10786. //
  10787. // The recognizer attempts to recover from single missing
  10788. // symbols. But, actions might refer to that missing symbol.
  10789. // For example, x=ID {f($x);}. The action clearly assumes
  10790. // that there has been an identifier matched previously and that
  10791. // $x points at that token. If that token is missing, but
  10792. // the next token in the stream is what we want we assume that
  10793. // this token is missing and we keep going. Because we
  10794. // have to return some token to replace the missing token,
  10795. // we have to conjure one up. This method gives the user control
  10796. // over the tokens returned for missing tokens. Mostly,
  10797. // you will want to create something special for identifier
  10798. // tokens. For literals such as '{' and ',', the default
  10799. // action in the parser or tree parser works. It simply creates
  10800. // a CommonToken of the appropriate type. The text will be the token.
  10801. // If you change what tokens must be created by the lexer,
  10802. // override this method to create the appropriate tokens.
  10803. //
  10804. DefaultErrorStrategy.prototype.getMissingSymbol = function(recognizer) {
  10805. var currentSymbol = recognizer.getCurrentToken();
  10806. var expecting = this.getExpectedTokens(recognizer);
  10807. var expectedTokenType = expecting.first(); // get any element
  10808. var tokenText;
  10809. if (expectedTokenType===Token.EOF) {
  10810. tokenText = "<missing EOF>";
  10811. } else {
  10812. tokenText = "<missing " + recognizer.literalNames[expectedTokenType] + ">";
  10813. }
  10814. var current = currentSymbol;
  10815. var lookback = recognizer.getTokenStream().LT(-1);
  10816. if (current.type===Token.EOF && lookback !== null) {
  10817. current = lookback;
  10818. }
  10819. return recognizer.getTokenFactory().create(current.source,
  10820. expectedTokenType, tokenText, Token.DEFAULT_CHANNEL,
  10821. -1, -1, current.line, current.column);
  10822. };
  10823. DefaultErrorStrategy.prototype.getExpectedTokens = function(recognizer) {
  10824. return recognizer.getExpectedTokens();
  10825. };
  10826. // How should a token be displayed in an error message? The default
  10827. // is to display just the text, but during development you might
  10828. // want to have a lot of information spit out. Override in that case
  10829. // to use t.toString() (which, for CommonToken, dumps everything about
  10830. // the token). This is better than forcing you to override a method in
  10831. // your token objects because you don't have to go modify your lexer
  10832. // so that it creates a new Java type.
  10833. //
  10834. DefaultErrorStrategy.prototype.getTokenErrorDisplay = function(t) {
  10835. if (t === null) {
  10836. return "<no token>";
  10837. }
  10838. var s = t.text;
  10839. if (s === null) {
  10840. if (t.type===Token.EOF) {
  10841. s = "<EOF>";
  10842. } else {
  10843. s = "<" + t.type + ">";
  10844. }
  10845. }
  10846. return this.escapeWSAndQuote(s);
  10847. };
  10848. DefaultErrorStrategy.prototype.escapeWSAndQuote = function(s) {
  10849. s = s.replace(/\n/g,"\\n");
  10850. s = s.replace(/\r/g,"\\r");
  10851. s = s.replace(/\t/g,"\\t");
  10852. return "'" + s + "'";
  10853. };
  10854. // Compute the error recovery set for the current rule. During
  10855. // rule invocation, the parser pushes the set of tokens that can
  10856. // follow that rule reference on the stack; this amounts to
  10857. // computing FIRST of what follows the rule reference in the
  10858. // enclosing rule. See LinearApproximator.FIRST().
  10859. // This local follow set only includes tokens
  10860. // from within the rule; i.e., the FIRST computation done by
  10861. // ANTLR stops at the end of a rule.
  10862. //
  10863. // EXAMPLE
  10864. //
  10865. // When you find a "no viable alt exception", the input is not
  10866. // consistent with any of the alternatives for rule r. The best
  10867. // thing to do is to consume tokens until you see something that
  10868. // can legally follow a call to r//or* any rule that called r.
  10869. // You don't want the exact set of viable next tokens because the
  10870. // input might just be missing a token--you might consume the
  10871. // rest of the input looking for one of the missing tokens.
  10872. //
  10873. // Consider grammar:
  10874. //
  10875. // a : '[' b ']'
  10876. // | '(' b ')'
  10877. // ;
  10878. // b : c '^' INT ;
  10879. // c : ID
  10880. // | INT
  10881. // ;
  10882. //
  10883. // At each rule invocation, the set of tokens that could follow
  10884. // that rule is pushed on a stack. Here are the various
  10885. // context-sensitive follow sets:
  10886. //
  10887. // FOLLOW(b1_in_a) = FIRST(']') = ']'
  10888. // FOLLOW(b2_in_a) = FIRST(')') = ')'
  10889. // FOLLOW(c_in_b) = FIRST('^') = '^'
  10890. //
  10891. // Upon erroneous input "[]", the call chain is
  10892. //
  10893. // a -> b -> c
  10894. //
  10895. // and, hence, the follow context stack is:
  10896. //
  10897. // depth follow set start of rule execution
  10898. // 0 <EOF> a (from main())
  10899. // 1 ']' b
  10900. // 2 '^' c
  10901. //
  10902. // Notice that ')' is not included, because b would have to have
  10903. // been called from a different context in rule a for ')' to be
  10904. // included.
  10905. //
  10906. // For error recovery, we cannot consider FOLLOW(c)
  10907. // (context-sensitive or otherwise). We need the combined set of
  10908. // all context-sensitive FOLLOW sets--the set of all tokens that
  10909. // could follow any reference in the call chain. We need to
  10910. // resync to one of those tokens. Note that FOLLOW(c)='^' and if
  10911. // we resync'd to that token, we'd consume until EOF. We need to
  10912. // sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.
  10913. // In this case, for input "[]", LA(1) is ']' and in the set, so we would
  10914. // not consume anything. After printing an error, rule c would
  10915. // return normally. Rule b would not find the required '^' though.
  10916. // At this point, it gets a mismatched token error and throws an
  10917. // exception (since LA(1) is not in the viable following token
  10918. // set). The rule exception handler tries to recover, but finds
  10919. // the same recovery set and doesn't consume anything. Rule b
  10920. // exits normally returning to rule a. Now it finds the ']' (and
  10921. // with the successful match exits errorRecovery mode).
  10922. //
  10923. // So, you can see that the parser walks up the call chain looking
  10924. // for the token that was a member of the recovery set.
  10925. //
  10926. // Errors are not generated in errorRecovery mode.
  10927. //
  10928. // ANTLR's error recovery mechanism is based upon original ideas:
  10929. //
  10930. // "Algorithms + Data Structures = Programs" by Niklaus Wirth
  10931. //
  10932. // and
  10933. //
  10934. // "A note on error recovery in recursive descent parsers":
  10935. // http://portal.acm.org/citation.cfm?id=947902.947905
  10936. //
  10937. // Later, Josef Grosch had some good ideas:
  10938. //
  10939. // "Efficient and Comfortable Error Recovery in Recursive Descent
  10940. // Parsers":
  10941. // ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
  10942. //
  10943. // Like Grosch I implement context-sensitive FOLLOW sets that are combined
  10944. // at run-time upon error to avoid overhead during parsing.
  10945. //
  10946. DefaultErrorStrategy.prototype.getErrorRecoverySet = function(recognizer) {
  10947. var atn = recognizer._interp.atn;
  10948. var ctx = recognizer._ctx;
  10949. var recoverSet = new IntervalSet();
  10950. while (ctx !== null && ctx.invokingState>=0) {
  10951. // compute what follows who invoked us
  10952. var invokingState = atn.states[ctx.invokingState];
  10953. var rt = invokingState.transitions[0];
  10954. var follow = atn.nextTokens(rt.followState);
  10955. recoverSet.addSet(follow);
  10956. ctx = ctx.parentCtx;
  10957. }
  10958. recoverSet.removeOne(Token.EPSILON);
  10959. return recoverSet;
  10960. };
  10961. // Consume tokens until one matches the given token set.//
  10962. DefaultErrorStrategy.prototype.consumeUntil = function(recognizer, set) {
  10963. var ttype = recognizer.getTokenStream().LA(1);
  10964. while( ttype !== Token.EOF && !set.contains(ttype)) {
  10965. recognizer.consume();
  10966. ttype = recognizer.getTokenStream().LA(1);
  10967. }
  10968. };
  10969. //
  10970. // This implementation of {@link ANTLRErrorStrategy} responds to syntax errors
  10971. // by immediately canceling the parse operation with a
  10972. // {@link ParseCancellationException}. The implementation ensures that the
  10973. // {@link ParserRuleContext//exception} field is set for all parse tree nodes
  10974. // that were not completed prior to encountering the error.
  10975. //
  10976. // <p>
  10977. // This error strategy is useful in the following scenarios.</p>
  10978. //
  10979. // <ul>
  10980. // <li><strong>Two-stage parsing:</strong> This error strategy allows the first
  10981. // stage of two-stage parsing to immediately terminate if an error is
  10982. // encountered, and immediately fall back to the second stage. In addition to
  10983. // avoiding wasted work by attempting to recover from errors here, the empty
  10984. // implementation of {@link BailErrorStrategy//sync} improves the performance of
  10985. // the first stage.</li>
  10986. // <li><strong>Silent validation:</strong> When syntax errors are not being
  10987. // reported or logged, and the parse result is simply ignored if errors occur,
  10988. // the {@link BailErrorStrategy} avoids wasting work on recovering from errors
  10989. // when the result will be ignored either way.</li>
  10990. // </ul>
  10991. //
  10992. // <p>
  10993. // {@code myparser.setErrorHandler(new BailErrorStrategy());}</p>
  10994. //
  10995. // @see Parser//setErrorHandler(ANTLRErrorStrategy)
  10996. //
  10997. function BailErrorStrategy() {
  10998. DefaultErrorStrategy.call(this);
  10999. return this;
  11000. }
  11001. BailErrorStrategy.prototype = Object.create(DefaultErrorStrategy.prototype);
  11002. BailErrorStrategy.prototype.constructor = BailErrorStrategy;
  11003. // Instead of recovering from exception {@code e}, re-throw it wrapped
  11004. // in a {@link ParseCancellationException} so it is not caught by the
  11005. // rule function catches. Use {@link Exception//getCause()} to get the
  11006. // original {@link RecognitionException}.
  11007. //
  11008. BailErrorStrategy.prototype.recover = function(recognizer, e) {
  11009. var context = recognizer._ctx;
  11010. while (context !== null) {
  11011. context.exception = e;
  11012. context = context.parentCtx;
  11013. }
  11014. throw new ParseCancellationException(e);
  11015. };
  11016. // Make sure we don't attempt to recover inline; if the parser
  11017. // successfully recovers, it won't throw an exception.
  11018. //
  11019. BailErrorStrategy.prototype.recoverInline = function(recognizer) {
  11020. this.recover(recognizer, new InputMismatchException(recognizer));
  11021. };
  11022. // Make sure we don't attempt to recover from problems in subrules.//
  11023. BailErrorStrategy.prototype.sync = function(recognizer) {
  11024. // pass
  11025. };
  11026. exports.BailErrorStrategy = BailErrorStrategy;
  11027. exports.DefaultErrorStrategy = DefaultErrorStrategy;
  11028. /***/ }),
  11029. /***/ "./node_modules/antlr4/error/Errors.js":
  11030. /*!*********************************************!*\
  11031. !*** ./node_modules/antlr4/error/Errors.js ***!
  11032. \*********************************************/
  11033. /*! no static exports found */
  11034. /***/ (function(module, exports, __webpack_require__) {
  11035. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  11036. * Use of this file is governed by the BSD 3-clause license that
  11037. * can be found in the LICENSE.txt file in the project root.
  11038. */
  11039. // The root of the ANTLR exception hierarchy. In general, ANTLR tracks just
  11040. // 3 kinds of errors: prediction errors, failed predicate errors, and
  11041. // mismatched input errors. In each case, the parser knows where it is
  11042. // in the input, where it is in the ATN, the rule invocation stack,
  11043. // and what kind of problem occurred.
  11044. var PredicateTransition = __webpack_require__(/*! ./../atn/Transition */ "./node_modules/antlr4/atn/Transition.js").PredicateTransition;
  11045. function RecognitionException(params) {
  11046. Error.call(this);
  11047. if (!!Error.captureStackTrace) {
  11048. Error.captureStackTrace(this, RecognitionException);
  11049. } else {
  11050. var stack = new Error().stack;
  11051. }
  11052. this.message = params.message;
  11053. this.recognizer = params.recognizer;
  11054. this.input = params.input;
  11055. this.ctx = params.ctx;
  11056. // The current {@link Token} when an error occurred. Since not all streams
  11057. // support accessing symbols by index, we have to track the {@link Token}
  11058. // instance itself.
  11059. this.offendingToken = null;
  11060. // Get the ATN state number the parser was in at the time the error
  11061. // occurred. For {@link NoViableAltException} and
  11062. // {@link LexerNoViableAltException} exceptions, this is the
  11063. // {@link DecisionState} number. For others, it is the state whose outgoing
  11064. // edge we couldn't match.
  11065. this.offendingState = -1;
  11066. if (this.recognizer!==null) {
  11067. this.offendingState = this.recognizer.state;
  11068. }
  11069. return this;
  11070. }
  11071. RecognitionException.prototype = Object.create(Error.prototype);
  11072. RecognitionException.prototype.constructor = RecognitionException;
  11073. // <p>If the state number is not known, this method returns -1.</p>
  11074. //
  11075. // Gets the set of input symbols which could potentially follow the
  11076. // previously matched symbol at the time this exception was thrown.
  11077. //
  11078. // <p>If the set of expected tokens is not known and could not be computed,
  11079. // this method returns {@code null}.</p>
  11080. //
  11081. // @return The set of token types that could potentially follow the current
  11082. // state in the ATN, or {@code null} if the information is not available.
  11083. // /
  11084. RecognitionException.prototype.getExpectedTokens = function() {
  11085. if (this.recognizer!==null) {
  11086. return this.recognizer.atn.getExpectedTokens(this.offendingState, this.ctx);
  11087. } else {
  11088. return null;
  11089. }
  11090. };
  11091. RecognitionException.prototype.toString = function() {
  11092. return this.message;
  11093. };
  11094. function LexerNoViableAltException(lexer, input, startIndex, deadEndConfigs) {
  11095. RecognitionException.call(this, {message:"", recognizer:lexer, input:input, ctx:null});
  11096. this.startIndex = startIndex;
  11097. this.deadEndConfigs = deadEndConfigs;
  11098. return this;
  11099. }
  11100. LexerNoViableAltException.prototype = Object.create(RecognitionException.prototype);
  11101. LexerNoViableAltException.prototype.constructor = LexerNoViableAltException;
  11102. LexerNoViableAltException.prototype.toString = function() {
  11103. var symbol = "";
  11104. if (this.startIndex >= 0 && this.startIndex < this.input.size) {
  11105. symbol = this.input.getText((this.startIndex,this.startIndex));
  11106. }
  11107. return "LexerNoViableAltException" + symbol;
  11108. };
  11109. // Indicates that the parser could not decide which of two or more paths
  11110. // to take based upon the remaining input. It tracks the starting token
  11111. // of the offending input and also knows where the parser was
  11112. // in the various paths when the error. Reported by reportNoViableAlternative()
  11113. //
  11114. function NoViableAltException(recognizer, input, startToken, offendingToken, deadEndConfigs, ctx) {
  11115. ctx = ctx || recognizer._ctx;
  11116. offendingToken = offendingToken || recognizer.getCurrentToken();
  11117. startToken = startToken || recognizer.getCurrentToken();
  11118. input = input || recognizer.getInputStream();
  11119. RecognitionException.call(this, {message:"", recognizer:recognizer, input:input, ctx:ctx});
  11120. // Which configurations did we try at input.index() that couldn't match
  11121. // input.LT(1)?//
  11122. this.deadEndConfigs = deadEndConfigs;
  11123. // The token object at the start index; the input stream might
  11124. // not be buffering tokens so get a reference to it. (At the
  11125. // time the error occurred, of course the stream needs to keep a
  11126. // buffer all of the tokens but later we might not have access to those.)
  11127. this.startToken = startToken;
  11128. this.offendingToken = offendingToken;
  11129. }
  11130. NoViableAltException.prototype = Object.create(RecognitionException.prototype);
  11131. NoViableAltException.prototype.constructor = NoViableAltException;
  11132. // This signifies any kind of mismatched input exceptions such as
  11133. // when the current input does not match the expected token.
  11134. //
  11135. function InputMismatchException(recognizer) {
  11136. RecognitionException.call(this, {message:"", recognizer:recognizer, input:recognizer.getInputStream(), ctx:recognizer._ctx});
  11137. this.offendingToken = recognizer.getCurrentToken();
  11138. }
  11139. InputMismatchException.prototype = Object.create(RecognitionException.prototype);
  11140. InputMismatchException.prototype.constructor = InputMismatchException;
  11141. // A semantic predicate failed during validation. Validation of predicates
  11142. // occurs when normally parsing the alternative just like matching a token.
  11143. // Disambiguating predicate evaluation occurs when we test a predicate during
  11144. // prediction.
  11145. function FailedPredicateException(recognizer, predicate, message) {
  11146. RecognitionException.call(this, {message:this.formatMessage(predicate,message || null), recognizer:recognizer,
  11147. input:recognizer.getInputStream(), ctx:recognizer._ctx});
  11148. var s = recognizer._interp.atn.states[recognizer.state];
  11149. var trans = s.transitions[0];
  11150. if (trans instanceof PredicateTransition) {
  11151. this.ruleIndex = trans.ruleIndex;
  11152. this.predicateIndex = trans.predIndex;
  11153. } else {
  11154. this.ruleIndex = 0;
  11155. this.predicateIndex = 0;
  11156. }
  11157. this.predicate = predicate;
  11158. this.offendingToken = recognizer.getCurrentToken();
  11159. return this;
  11160. }
  11161. FailedPredicateException.prototype = Object.create(RecognitionException.prototype);
  11162. FailedPredicateException.prototype.constructor = FailedPredicateException;
  11163. FailedPredicateException.prototype.formatMessage = function(predicate, message) {
  11164. if (message !==null) {
  11165. return message;
  11166. } else {
  11167. return "failed predicate: {" + predicate + "}?";
  11168. }
  11169. };
  11170. function ParseCancellationException() {
  11171. Error.call(this);
  11172. Error.captureStackTrace(this, ParseCancellationException);
  11173. return this;
  11174. }
  11175. ParseCancellationException.prototype = Object.create(Error.prototype);
  11176. ParseCancellationException.prototype.constructor = ParseCancellationException;
  11177. exports.RecognitionException = RecognitionException;
  11178. exports.NoViableAltException = NoViableAltException;
  11179. exports.LexerNoViableAltException = LexerNoViableAltException;
  11180. exports.InputMismatchException = InputMismatchException;
  11181. exports.FailedPredicateException = FailedPredicateException;
  11182. exports.ParseCancellationException = ParseCancellationException;
  11183. /***/ }),
  11184. /***/ "./node_modules/antlr4/error/index.js":
  11185. /*!********************************************!*\
  11186. !*** ./node_modules/antlr4/error/index.js ***!
  11187. \********************************************/
  11188. /*! no static exports found */
  11189. /***/ (function(module, exports, __webpack_require__) {
  11190. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  11191. * Use of this file is governed by the BSD 3-clause license that
  11192. * can be found in the LICENSE.txt file in the project root.
  11193. */
  11194. exports.RecognitionException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").RecognitionException;
  11195. exports.NoViableAltException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").NoViableAltException;
  11196. exports.LexerNoViableAltException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").LexerNoViableAltException;
  11197. exports.InputMismatchException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").InputMismatchException;
  11198. exports.FailedPredicateException = __webpack_require__(/*! ./Errors */ "./node_modules/antlr4/error/Errors.js").FailedPredicateException;
  11199. exports.DiagnosticErrorListener = __webpack_require__(/*! ./DiagnosticErrorListener */ "./node_modules/antlr4/error/DiagnosticErrorListener.js").DiagnosticErrorListener;
  11200. exports.BailErrorStrategy = __webpack_require__(/*! ./ErrorStrategy */ "./node_modules/antlr4/error/ErrorStrategy.js").BailErrorStrategy;
  11201. exports.ErrorListener = __webpack_require__(/*! ./ErrorListener */ "./node_modules/antlr4/error/ErrorListener.js").ErrorListener;
  11202. /***/ }),
  11203. /***/ "./node_modules/antlr4/index.js":
  11204. /*!**************************************!*\
  11205. !*** ./node_modules/antlr4/index.js ***!
  11206. \**************************************/
  11207. /*! no static exports found */
  11208. /***/ (function(module, exports, __webpack_require__) {
  11209. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  11210. * Use of this file is governed by the BSD 3-clause license that
  11211. * can be found in the LICENSE.txt file in the project root.
  11212. */
  11213. exports.atn = __webpack_require__(/*! ./atn/index */ "./node_modules/antlr4/atn/index.js");
  11214. exports.codepointat = __webpack_require__(/*! ./polyfills/codepointat */ "./node_modules/antlr4/polyfills/codepointat.js");
  11215. exports.dfa = __webpack_require__(/*! ./dfa/index */ "./node_modules/antlr4/dfa/index.js");
  11216. exports.fromcodepoint = __webpack_require__(/*! ./polyfills/fromcodepoint */ "./node_modules/antlr4/polyfills/fromcodepoint.js");
  11217. exports.tree = __webpack_require__(/*! ./tree/index */ "./node_modules/antlr4/tree/index.js");
  11218. exports.error = __webpack_require__(/*! ./error/index */ "./node_modules/antlr4/error/index.js");
  11219. exports.Token = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").Token;
  11220. exports.CharStreams = __webpack_require__(/*! ./CharStreams */ "./node_modules/antlr4/CharStreams.js").CharStreams;
  11221. exports.CommonToken = __webpack_require__(/*! ./Token */ "./node_modules/antlr4/Token.js").CommonToken;
  11222. exports.InputStream = __webpack_require__(/*! ./InputStream */ "./node_modules/antlr4/InputStream.js").InputStream;
  11223. exports.FileStream = __webpack_require__(/*! ./FileStream */ "./node_modules/antlr4/FileStream.js").FileStream;
  11224. exports.CommonTokenStream = __webpack_require__(/*! ./CommonTokenStream */ "./node_modules/antlr4/CommonTokenStream.js").CommonTokenStream;
  11225. exports.Lexer = __webpack_require__(/*! ./Lexer */ "./node_modules/antlr4/Lexer.js").Lexer;
  11226. exports.Parser = __webpack_require__(/*! ./Parser */ "./node_modules/antlr4/Parser.js").Parser;
  11227. var pc = __webpack_require__(/*! ./PredictionContext */ "./node_modules/antlr4/PredictionContext.js");
  11228. exports.PredictionContextCache = pc.PredictionContextCache;
  11229. exports.ParserRuleContext = __webpack_require__(/*! ./ParserRuleContext */ "./node_modules/antlr4/ParserRuleContext.js").ParserRuleContext;
  11230. exports.Interval = __webpack_require__(/*! ./IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  11231. exports.Utils = __webpack_require__(/*! ./Utils */ "./node_modules/antlr4/Utils.js");
  11232. /***/ }),
  11233. /***/ "./node_modules/antlr4/polyfills/codepointat.js":
  11234. /*!******************************************************!*\
  11235. !*** ./node_modules/antlr4/polyfills/codepointat.js ***!
  11236. \******************************************************/
  11237. /*! no static exports found */
  11238. /***/ (function(module, exports) {
  11239. /*! https://mths.be/codepointat v0.2.0 by @mathias */
  11240. if (!String.prototype.codePointAt) {
  11241. (function() {
  11242. 'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
  11243. var defineProperty = (function() {
  11244. // IE 8 only supports `Object.defineProperty` on DOM elements
  11245. try {
  11246. var object = {};
  11247. var $defineProperty = Object.defineProperty;
  11248. var result = $defineProperty(object, object, object) && $defineProperty;
  11249. } catch(error) {}
  11250. return result;
  11251. }());
  11252. var codePointAt = function(position) {
  11253. if (this == null) {
  11254. throw TypeError();
  11255. }
  11256. var string = String(this);
  11257. var size = string.length;
  11258. // `ToInteger`
  11259. var index = position ? Number(position) : 0;
  11260. if (index != index) { // better `isNaN`
  11261. index = 0;
  11262. }
  11263. // Account for out-of-bounds indices:
  11264. if (index < 0 || index >= size) {
  11265. return undefined;
  11266. }
  11267. // Get the first code unit
  11268. var first = string.charCodeAt(index);
  11269. var second;
  11270. if ( // check if it’s the start of a surrogate pair
  11271. first >= 0xD800 && first <= 0xDBFF && // high surrogate
  11272. size > index + 1 // there is a next code unit
  11273. ) {
  11274. second = string.charCodeAt(index + 1);
  11275. if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
  11276. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  11277. return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  11278. }
  11279. }
  11280. return first;
  11281. };
  11282. if (defineProperty) {
  11283. defineProperty(String.prototype, 'codePointAt', {
  11284. 'value': codePointAt,
  11285. 'configurable': true,
  11286. 'writable': true
  11287. });
  11288. } else {
  11289. String.prototype.codePointAt = codePointAt;
  11290. }
  11291. }());
  11292. }
  11293. /***/ }),
  11294. /***/ "./node_modules/antlr4/polyfills/fromcodepoint.js":
  11295. /*!********************************************************!*\
  11296. !*** ./node_modules/antlr4/polyfills/fromcodepoint.js ***!
  11297. \********************************************************/
  11298. /*! no static exports found */
  11299. /***/ (function(module, exports) {
  11300. /*! https://mths.be/fromcodepoint v0.2.1 by @mathias */
  11301. if (!String.fromCodePoint) {
  11302. (function() {
  11303. var defineProperty = (function() {
  11304. // IE 8 only supports `Object.defineProperty` on DOM elements
  11305. try {
  11306. var object = {};
  11307. var $defineProperty = Object.defineProperty;
  11308. var result = $defineProperty(object, object, object) && $defineProperty;
  11309. } catch(error) {}
  11310. return result;
  11311. }());
  11312. var stringFromCharCode = String.fromCharCode;
  11313. var floor = Math.floor;
  11314. var fromCodePoint = function(_) {
  11315. var MAX_SIZE = 0x4000;
  11316. var codeUnits = [];
  11317. var highSurrogate;
  11318. var lowSurrogate;
  11319. var index = -1;
  11320. var length = arguments.length;
  11321. if (!length) {
  11322. return '';
  11323. }
  11324. var result = '';
  11325. while (++index < length) {
  11326. var codePoint = Number(arguments[index]);
  11327. if (
  11328. !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
  11329. codePoint < 0 || // not a valid Unicode code point
  11330. codePoint > 0x10FFFF || // not a valid Unicode code point
  11331. floor(codePoint) != codePoint // not an integer
  11332. ) {
  11333. throw RangeError('Invalid code point: ' + codePoint);
  11334. }
  11335. if (codePoint <= 0xFFFF) { // BMP code point
  11336. codeUnits.push(codePoint);
  11337. } else { // Astral code point; split in surrogate halves
  11338. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  11339. codePoint -= 0x10000;
  11340. highSurrogate = (codePoint >> 10) + 0xD800;
  11341. lowSurrogate = (codePoint % 0x400) + 0xDC00;
  11342. codeUnits.push(highSurrogate, lowSurrogate);
  11343. }
  11344. if (index + 1 == length || codeUnits.length > MAX_SIZE) {
  11345. result += stringFromCharCode.apply(null, codeUnits);
  11346. codeUnits.length = 0;
  11347. }
  11348. }
  11349. return result;
  11350. };
  11351. if (defineProperty) {
  11352. defineProperty(String, 'fromCodePoint', {
  11353. 'value': fromCodePoint,
  11354. 'configurable': true,
  11355. 'writable': true
  11356. });
  11357. } else {
  11358. String.fromCodePoint = fromCodePoint;
  11359. }
  11360. }());
  11361. }
  11362. /***/ }),
  11363. /***/ "./node_modules/antlr4/tree/Tree.js":
  11364. /*!******************************************!*\
  11365. !*** ./node_modules/antlr4/tree/Tree.js ***!
  11366. \******************************************/
  11367. /*! no static exports found */
  11368. /***/ (function(module, exports, __webpack_require__) {
  11369. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  11370. * Use of this file is governed by the BSD 3-clause license that
  11371. * can be found in the LICENSE.txt file in the project root.
  11372. */
  11373. ///
  11374. // The basic notion of a tree has a parent, a payload, and a list of children.
  11375. // It is the most abstract interface for all the trees used by ANTLR.
  11376. ///
  11377. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  11378. var Interval = __webpack_require__(/*! ./../IntervalSet */ "./node_modules/antlr4/IntervalSet.js").Interval;
  11379. var INVALID_INTERVAL = new Interval(-1, -2);
  11380. var Utils = __webpack_require__(/*! ../Utils.js */ "./node_modules/antlr4/Utils.js");
  11381. function Tree() {
  11382. return this;
  11383. }
  11384. function SyntaxTree() {
  11385. Tree.call(this);
  11386. return this;
  11387. }
  11388. SyntaxTree.prototype = Object.create(Tree.prototype);
  11389. SyntaxTree.prototype.constructor = SyntaxTree;
  11390. function ParseTree() {
  11391. SyntaxTree.call(this);
  11392. return this;
  11393. }
  11394. ParseTree.prototype = Object.create(SyntaxTree.prototype);
  11395. ParseTree.prototype.constructor = ParseTree;
  11396. function RuleNode() {
  11397. ParseTree.call(this);
  11398. return this;
  11399. }
  11400. RuleNode.prototype = Object.create(ParseTree.prototype);
  11401. RuleNode.prototype.constructor = RuleNode;
  11402. function TerminalNode() {
  11403. ParseTree.call(this);
  11404. return this;
  11405. }
  11406. TerminalNode.prototype = Object.create(ParseTree.prototype);
  11407. TerminalNode.prototype.constructor = TerminalNode;
  11408. function ErrorNode() {
  11409. TerminalNode.call(this);
  11410. return this;
  11411. }
  11412. ErrorNode.prototype = Object.create(TerminalNode.prototype);
  11413. ErrorNode.prototype.constructor = ErrorNode;
  11414. function ParseTreeVisitor() {
  11415. return this;
  11416. }
  11417. ParseTreeVisitor.prototype.visit = function(ctx) {
  11418. if (Array.isArray(ctx)) {
  11419. return ctx.map(function(child) {
  11420. return child.accept(this);
  11421. }, this);
  11422. } else {
  11423. return ctx.accept(this);
  11424. }
  11425. };
  11426. ParseTreeVisitor.prototype.visitChildren = function(ctx) {
  11427. if (ctx.children) {
  11428. return this.visit(ctx.children);
  11429. } else {
  11430. return null;
  11431. }
  11432. }
  11433. ParseTreeVisitor.prototype.visitTerminal = function(node) {
  11434. };
  11435. ParseTreeVisitor.prototype.visitErrorNode = function(node) {
  11436. };
  11437. function ParseTreeListener() {
  11438. return this;
  11439. }
  11440. ParseTreeListener.prototype.visitTerminal = function(node) {
  11441. };
  11442. ParseTreeListener.prototype.visitErrorNode = function(node) {
  11443. };
  11444. ParseTreeListener.prototype.enterEveryRule = function(node) {
  11445. };
  11446. ParseTreeListener.prototype.exitEveryRule = function(node) {
  11447. };
  11448. function TerminalNodeImpl(symbol) {
  11449. TerminalNode.call(this);
  11450. this.parentCtx = null;
  11451. this.symbol = symbol;
  11452. return this;
  11453. }
  11454. TerminalNodeImpl.prototype = Object.create(TerminalNode.prototype);
  11455. TerminalNodeImpl.prototype.constructor = TerminalNodeImpl;
  11456. TerminalNodeImpl.prototype.getChild = function(i) {
  11457. return null;
  11458. };
  11459. TerminalNodeImpl.prototype.getSymbol = function() {
  11460. return this.symbol;
  11461. };
  11462. TerminalNodeImpl.prototype.getParent = function() {
  11463. return this.parentCtx;
  11464. };
  11465. TerminalNodeImpl.prototype.getPayload = function() {
  11466. return this.symbol;
  11467. };
  11468. TerminalNodeImpl.prototype.getSourceInterval = function() {
  11469. if (this.symbol === null) {
  11470. return INVALID_INTERVAL;
  11471. }
  11472. var tokenIndex = this.symbol.tokenIndex;
  11473. return new Interval(tokenIndex, tokenIndex);
  11474. };
  11475. TerminalNodeImpl.prototype.getChildCount = function() {
  11476. return 0;
  11477. };
  11478. TerminalNodeImpl.prototype.accept = function(visitor) {
  11479. return visitor.visitTerminal(this);
  11480. };
  11481. TerminalNodeImpl.prototype.getText = function() {
  11482. return this.symbol.text;
  11483. };
  11484. TerminalNodeImpl.prototype.toString = function() {
  11485. if (this.symbol.type === Token.EOF) {
  11486. return "<EOF>";
  11487. } else {
  11488. return this.symbol.text;
  11489. }
  11490. };
  11491. // Represents a token that was consumed during resynchronization
  11492. // rather than during a valid match operation. For example,
  11493. // we will create this kind of a node during single token insertion
  11494. // and deletion as well as during "consume until error recovery set"
  11495. // upon no viable alternative exceptions.
  11496. function ErrorNodeImpl(token) {
  11497. TerminalNodeImpl.call(this, token);
  11498. return this;
  11499. }
  11500. ErrorNodeImpl.prototype = Object.create(TerminalNodeImpl.prototype);
  11501. ErrorNodeImpl.prototype.constructor = ErrorNodeImpl;
  11502. ErrorNodeImpl.prototype.isErrorNode = function() {
  11503. return true;
  11504. };
  11505. ErrorNodeImpl.prototype.accept = function(visitor) {
  11506. return visitor.visitErrorNode(this);
  11507. };
  11508. function ParseTreeWalker() {
  11509. return this;
  11510. }
  11511. ParseTreeWalker.prototype.walk = function(listener, t) {
  11512. var errorNode = t instanceof ErrorNode ||
  11513. (t.isErrorNode !== undefined && t.isErrorNode());
  11514. if (errorNode) {
  11515. listener.visitErrorNode(t);
  11516. } else if (t instanceof TerminalNode) {
  11517. listener.visitTerminal(t);
  11518. } else {
  11519. this.enterRule(listener, t);
  11520. for (var i = 0; i < t.getChildCount(); i++) {
  11521. var child = t.getChild(i);
  11522. this.walk(listener, child);
  11523. }
  11524. this.exitRule(listener, t);
  11525. }
  11526. };
  11527. //
  11528. // The discovery of a rule node, involves sending two events: the generic
  11529. // {@link ParseTreeListener//enterEveryRule} and a
  11530. // {@link RuleContext}-specific event. First we trigger the generic and then
  11531. // the rule specific. We to them in reverse order upon finishing the node.
  11532. //
  11533. ParseTreeWalker.prototype.enterRule = function(listener, r) {
  11534. var ctx = r.getRuleContext();
  11535. listener.enterEveryRule(ctx);
  11536. ctx.enterRule(listener);
  11537. };
  11538. ParseTreeWalker.prototype.exitRule = function(listener, r) {
  11539. var ctx = r.getRuleContext();
  11540. ctx.exitRule(listener);
  11541. listener.exitEveryRule(ctx);
  11542. };
  11543. ParseTreeWalker.DEFAULT = new ParseTreeWalker();
  11544. exports.RuleNode = RuleNode;
  11545. exports.ErrorNode = ErrorNode;
  11546. exports.TerminalNode = TerminalNode;
  11547. exports.ErrorNodeImpl = ErrorNodeImpl;
  11548. exports.TerminalNodeImpl = TerminalNodeImpl;
  11549. exports.ParseTreeListener = ParseTreeListener;
  11550. exports.ParseTreeVisitor = ParseTreeVisitor;
  11551. exports.ParseTreeWalker = ParseTreeWalker;
  11552. exports.INVALID_INTERVAL = INVALID_INTERVAL;
  11553. /***/ }),
  11554. /***/ "./node_modules/antlr4/tree/Trees.js":
  11555. /*!*******************************************!*\
  11556. !*** ./node_modules/antlr4/tree/Trees.js ***!
  11557. \*******************************************/
  11558. /*! no static exports found */
  11559. /***/ (function(module, exports, __webpack_require__) {
  11560. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  11561. * Use of this file is governed by the BSD 3-clause license that
  11562. * can be found in the LICENSE.txt file in the project root.
  11563. */
  11564. var Utils = __webpack_require__(/*! ./../Utils */ "./node_modules/antlr4/Utils.js");
  11565. var Token = __webpack_require__(/*! ./../Token */ "./node_modules/antlr4/Token.js").Token;
  11566. var RuleNode = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js").RuleNode;
  11567. var ErrorNode = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js").ErrorNode;
  11568. var TerminalNode = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js").TerminalNode;
  11569. var ParserRuleContext = __webpack_require__(/*! ./../ParserRuleContext */ "./node_modules/antlr4/ParserRuleContext.js").ParserRuleContext;
  11570. var RuleContext = __webpack_require__(/*! ./../RuleContext */ "./node_modules/antlr4/RuleContext.js").RuleContext;
  11571. var INVALID_ALT_NUMBER = __webpack_require__(/*! ./../atn/ATN */ "./node_modules/antlr4/atn/ATN.js").INVALID_ALT_NUMBER;
  11572. /** A set of utility routines useful for all kinds of ANTLR trees. */
  11573. function Trees() {
  11574. }
  11575. // Print out a whole tree in LISP form. {@link //getNodeText} is used on the
  11576. // node payloads to get the text for the nodes. Detect
  11577. // parse trees and extract data appropriately.
  11578. Trees.toStringTree = function(tree, ruleNames, recog) {
  11579. ruleNames = ruleNames || null;
  11580. recog = recog || null;
  11581. if(recog!==null) {
  11582. ruleNames = recog.ruleNames;
  11583. }
  11584. var s = Trees.getNodeText(tree, ruleNames);
  11585. s = Utils.escapeWhitespace(s, false);
  11586. var c = tree.getChildCount();
  11587. if(c===0) {
  11588. return s;
  11589. }
  11590. var res = "(" + s + ' ';
  11591. if(c>0) {
  11592. s = Trees.toStringTree(tree.getChild(0), ruleNames);
  11593. res = res.concat(s);
  11594. }
  11595. for(var i=1;i<c;i++) {
  11596. s = Trees.toStringTree(tree.getChild(i), ruleNames);
  11597. res = res.concat(' ' + s);
  11598. }
  11599. res = res.concat(")");
  11600. return res;
  11601. };
  11602. Trees.getNodeText = function(t, ruleNames, recog) {
  11603. ruleNames = ruleNames || null;
  11604. recog = recog || null;
  11605. if(recog!==null) {
  11606. ruleNames = recog.ruleNames;
  11607. }
  11608. if(ruleNames!==null) {
  11609. if (t instanceof RuleContext) {
  11610. var altNumber = t.getAltNumber();
  11611. if ( altNumber!=INVALID_ALT_NUMBER ) {
  11612. return ruleNames[t.ruleIndex]+":"+altNumber;
  11613. }
  11614. return ruleNames[t.ruleIndex];
  11615. } else if ( t instanceof ErrorNode) {
  11616. return t.toString();
  11617. } else if(t instanceof TerminalNode) {
  11618. if(t.symbol!==null) {
  11619. return t.symbol.text;
  11620. }
  11621. }
  11622. }
  11623. // no recog for rule names
  11624. var payload = t.getPayload();
  11625. if (payload instanceof Token ) {
  11626. return payload.text;
  11627. }
  11628. return t.getPayload().toString();
  11629. };
  11630. // Return ordered list of all children of this node
  11631. Trees.getChildren = function(t) {
  11632. var list = [];
  11633. for(var i=0;i<t.getChildCount();i++) {
  11634. list.push(t.getChild(i));
  11635. }
  11636. return list;
  11637. };
  11638. // Return a list of all ancestors of this node. The first node of
  11639. // list is the root and the last is the parent of this node.
  11640. //
  11641. Trees.getAncestors = function(t) {
  11642. var ancestors = [];
  11643. t = t.getParent();
  11644. while(t!==null) {
  11645. ancestors = [t].concat(ancestors);
  11646. t = t.getParent();
  11647. }
  11648. return ancestors;
  11649. };
  11650. Trees.findAllTokenNodes = function(t, ttype) {
  11651. return Trees.findAllNodes(t, ttype, true);
  11652. };
  11653. Trees.findAllRuleNodes = function(t, ruleIndex) {
  11654. return Trees.findAllNodes(t, ruleIndex, false);
  11655. };
  11656. Trees.findAllNodes = function(t, index, findTokens) {
  11657. var nodes = [];
  11658. Trees._findAllNodes(t, index, findTokens, nodes);
  11659. return nodes;
  11660. };
  11661. Trees._findAllNodes = function(t, index, findTokens, nodes) {
  11662. // check this node (the root) first
  11663. if(findTokens && (t instanceof TerminalNode)) {
  11664. if(t.symbol.type===index) {
  11665. nodes.push(t);
  11666. }
  11667. } else if(!findTokens && (t instanceof ParserRuleContext)) {
  11668. if(t.ruleIndex===index) {
  11669. nodes.push(t);
  11670. }
  11671. }
  11672. // check children
  11673. for(var i=0;i<t.getChildCount();i++) {
  11674. Trees._findAllNodes(t.getChild(i), index, findTokens, nodes);
  11675. }
  11676. };
  11677. Trees.descendants = function(t) {
  11678. var nodes = [t];
  11679. for(var i=0;i<t.getChildCount();i++) {
  11680. nodes = nodes.concat(Trees.descendants(t.getChild(i)));
  11681. }
  11682. return nodes;
  11683. };
  11684. exports.Trees = Trees;
  11685. /***/ }),
  11686. /***/ "./node_modules/antlr4/tree/index.js":
  11687. /*!*******************************************!*\
  11688. !*** ./node_modules/antlr4/tree/index.js ***!
  11689. \*******************************************/
  11690. /*! no static exports found */
  11691. /***/ (function(module, exports, __webpack_require__) {
  11692. /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
  11693. * Use of this file is governed by the BSD 3-clause license that
  11694. * can be found in the LICENSE.txt file in the project root.
  11695. */
  11696. var Tree = __webpack_require__(/*! ./Tree */ "./node_modules/antlr4/tree/Tree.js");
  11697. exports.Trees = __webpack_require__(/*! ./Trees */ "./node_modules/antlr4/tree/Trees.js").Trees;
  11698. exports.RuleNode = Tree.RuleNode;
  11699. exports.ParseTreeListener = Tree.ParseTreeListener;
  11700. exports.ParseTreeVisitor = Tree.ParseTreeVisitor;
  11701. exports.ParseTreeWalker = Tree.ParseTreeWalker;
  11702. /***/ }),
  11703. /***/ "./node_modules/codemirror/addon/edit/closebrackets.js":
  11704. /*!*************************************************************!*\
  11705. !*** ./node_modules/codemirror/addon/edit/closebrackets.js ***!
  11706. \*************************************************************/
  11707. /*! no static exports found */
  11708. /***/ (function(module, exports, __webpack_require__) {
  11709. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11710. // Distributed under an MIT license: https://codemirror.net/LICENSE
  11711. (function(mod) {
  11712. if (true) // CommonJS
  11713. mod(__webpack_require__(/*! ../../lib/codemirror */ "./node_modules/codemirror/lib/codemirror.js"));
  11714. else {}
  11715. })(function(CodeMirror) {
  11716. var defaults = {
  11717. pairs: "()[]{}''\"\"",
  11718. closeBefore: ")]}'\":;>",
  11719. triples: "",
  11720. explode: "[]{}"
  11721. };
  11722. var Pos = CodeMirror.Pos;
  11723. CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
  11724. if (old && old != CodeMirror.Init) {
  11725. cm.removeKeyMap(keyMap);
  11726. cm.state.closeBrackets = null;
  11727. }
  11728. if (val) {
  11729. ensureBound(getOption(val, "pairs"))
  11730. cm.state.closeBrackets = val;
  11731. cm.addKeyMap(keyMap);
  11732. }
  11733. });
  11734. function getOption(conf, name) {
  11735. if (name == "pairs" && typeof conf == "string") return conf;
  11736. if (typeof conf == "object" && conf[name] != null) return conf[name];
  11737. return defaults[name];
  11738. }
  11739. var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
  11740. function ensureBound(chars) {
  11741. for (var i = 0; i < chars.length; i++) {
  11742. var ch = chars.charAt(i), key = "'" + ch + "'"
  11743. if (!keyMap[key]) keyMap[key] = handler(ch)
  11744. }
  11745. }
  11746. ensureBound(defaults.pairs + "`")
  11747. function handler(ch) {
  11748. return function(cm) { return handleChar(cm, ch); };
  11749. }
  11750. function getConfig(cm) {
  11751. var deflt = cm.state.closeBrackets;
  11752. if (!deflt || deflt.override) return deflt;
  11753. var mode = cm.getModeAt(cm.getCursor());
  11754. return mode.closeBrackets || deflt;
  11755. }
  11756. function handleBackspace(cm) {
  11757. var conf = getConfig(cm);
  11758. if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
  11759. var pairs = getOption(conf, "pairs");
  11760. var ranges = cm.listSelections();
  11761. for (var i = 0; i < ranges.length; i++) {
  11762. if (!ranges[i].empty()) return CodeMirror.Pass;
  11763. var around = charsAround(cm, ranges[i].head);
  11764. if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
  11765. }
  11766. for (var i = ranges.length - 1; i >= 0; i--) {
  11767. var cur = ranges[i].head;
  11768. cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete");
  11769. }
  11770. }
  11771. function handleEnter(cm) {
  11772. var conf = getConfig(cm);
  11773. var explode = conf && getOption(conf, "explode");
  11774. if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;
  11775. var ranges = cm.listSelections();
  11776. for (var i = 0; i < ranges.length; i++) {
  11777. if (!ranges[i].empty()) return CodeMirror.Pass;
  11778. var around = charsAround(cm, ranges[i].head);
  11779. if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
  11780. }
  11781. cm.operation(function() {
  11782. var linesep = cm.lineSeparator() || "\n";
  11783. cm.replaceSelection(linesep + linesep, null);
  11784. cm.execCommand("goCharLeft");
  11785. ranges = cm.listSelections();
  11786. for (var i = 0; i < ranges.length; i++) {
  11787. var line = ranges[i].head.line;
  11788. cm.indentLine(line, null, true);
  11789. cm.indentLine(line + 1, null, true);
  11790. }
  11791. });
  11792. }
  11793. function contractSelection(sel) {
  11794. var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
  11795. return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
  11796. head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
  11797. }
  11798. function handleChar(cm, ch) {
  11799. var conf = getConfig(cm);
  11800. if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
  11801. var pairs = getOption(conf, "pairs");
  11802. var pos = pairs.indexOf(ch);
  11803. if (pos == -1) return CodeMirror.Pass;
  11804. var closeBefore = getOption(conf,"closeBefore");
  11805. var triples = getOption(conf, "triples");
  11806. var identical = pairs.charAt(pos + 1) == ch;
  11807. var ranges = cm.listSelections();
  11808. var opening = pos % 2 == 0;
  11809. var type;
  11810. for (var i = 0; i < ranges.length; i++) {
  11811. var range = ranges[i], cur = range.head, curType;
  11812. var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
  11813. if (opening && !range.empty()) {
  11814. curType = "surround";
  11815. } else if ((identical || !opening) && next == ch) {
  11816. if (identical && stringStartsAfter(cm, cur))
  11817. curType = "both";
  11818. else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
  11819. curType = "skipThree";
  11820. else
  11821. curType = "skip";
  11822. } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
  11823. cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) {
  11824. if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass;
  11825. curType = "addFour";
  11826. } else if (identical) {
  11827. var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur)
  11828. if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";
  11829. else return CodeMirror.Pass;
  11830. } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) {
  11831. curType = "both";
  11832. } else {
  11833. return CodeMirror.Pass;
  11834. }
  11835. if (!type) type = curType;
  11836. else if (type != curType) return CodeMirror.Pass;
  11837. }
  11838. var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
  11839. var right = pos % 2 ? ch : pairs.charAt(pos + 1);
  11840. cm.operation(function() {
  11841. if (type == "skip") {
  11842. cm.execCommand("goCharRight");
  11843. } else if (type == "skipThree") {
  11844. for (var i = 0; i < 3; i++)
  11845. cm.execCommand("goCharRight");
  11846. } else if (type == "surround") {
  11847. var sels = cm.getSelections();
  11848. for (var i = 0; i < sels.length; i++)
  11849. sels[i] = left + sels[i] + right;
  11850. cm.replaceSelections(sels, "around");
  11851. sels = cm.listSelections().slice();
  11852. for (var i = 0; i < sels.length; i++)
  11853. sels[i] = contractSelection(sels[i]);
  11854. cm.setSelections(sels);
  11855. } else if (type == "both") {
  11856. cm.replaceSelection(left + right, null);
  11857. cm.triggerElectric(left + right);
  11858. cm.execCommand("goCharLeft");
  11859. } else if (type == "addFour") {
  11860. cm.replaceSelection(left + left + left + left, "before");
  11861. cm.execCommand("goCharRight");
  11862. }
  11863. });
  11864. }
  11865. function charsAround(cm, pos) {
  11866. var str = cm.getRange(Pos(pos.line, pos.ch - 1),
  11867. Pos(pos.line, pos.ch + 1));
  11868. return str.length == 2 ? str : null;
  11869. }
  11870. function stringStartsAfter(cm, pos) {
  11871. var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
  11872. return /\bstring/.test(token.type) && token.start == pos.ch &&
  11873. (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos)))
  11874. }
  11875. });
  11876. /***/ }),
  11877. /***/ "./node_modules/codemirror/addon/edit/matchbrackets.js":
  11878. /*!*************************************************************!*\
  11879. !*** ./node_modules/codemirror/addon/edit/matchbrackets.js ***!
  11880. \*************************************************************/
  11881. /*! no static exports found */
  11882. /***/ (function(module, exports, __webpack_require__) {
  11883. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11884. // Distributed under an MIT license: https://codemirror.net/LICENSE
  11885. (function(mod) {
  11886. if (true) // CommonJS
  11887. mod(__webpack_require__(/*! ../../lib/codemirror */ "./node_modules/codemirror/lib/codemirror.js"));
  11888. else {}
  11889. })(function(CodeMirror) {
  11890. var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
  11891. (document.documentMode == null || document.documentMode < 8);
  11892. var Pos = CodeMirror.Pos;
  11893. var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<", "<": ">>", ">": "<<"};
  11894. function bracketRegex(config) {
  11895. return config && config.bracketRegex || /[(){}[\]]/
  11896. }
  11897. function findMatchingBracket(cm, where, config) {
  11898. var line = cm.getLineHandle(where.line), pos = where.ch - 1;
  11899. var afterCursor = config && config.afterCursor
  11900. if (afterCursor == null)
  11901. afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)
  11902. var re = bracketRegex(config)
  11903. // A cursor is defined as between two characters, but in in vim command mode
  11904. // (i.e. not insert mode), the cursor is visually represented as a
  11905. // highlighted box on top of the 2nd character. Otherwise, we allow matches
  11906. // from before or after the cursor.
  11907. var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) ||
  11908. re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)];
  11909. if (!match) return null;
  11910. var dir = match.charAt(1) == ">" ? 1 : -1;
  11911. if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;
  11912. var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
  11913. var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
  11914. if (found == null) return null;
  11915. return {from: Pos(where.line, pos), to: found && found.pos,
  11916. match: found && found.ch == match.charAt(0), forward: dir > 0};
  11917. }
  11918. // bracketRegex is used to specify which type of bracket to scan
  11919. // should be a regexp, e.g. /[[\]]/
  11920. //
  11921. // Note: If "where" is on an open bracket, then this bracket is ignored.
  11922. //
  11923. // Returns false when no bracket was found, null when it reached
  11924. // maxScanLines and gave up
  11925. function scanForBracket(cm, where, dir, style, config) {
  11926. var maxScanLen = (config && config.maxScanLineLength) || 10000;
  11927. var maxScanLines = (config && config.maxScanLines) || 1000;
  11928. var stack = [];
  11929. var re = bracketRegex(config)
  11930. var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
  11931. : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
  11932. for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
  11933. var line = cm.getLine(lineNo);
  11934. if (!line) continue;
  11935. var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
  11936. if (line.length > maxScanLen) continue;
  11937. if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
  11938. for (; pos != end; pos += dir) {
  11939. var ch = line.charAt(pos);
  11940. if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
  11941. var match = matching[ch];
  11942. if (match && (match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
  11943. else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
  11944. else stack.pop();
  11945. }
  11946. }
  11947. }
  11948. return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
  11949. }
  11950. function matchBrackets(cm, autoclear, config) {
  11951. // Disable brace matching in long lines, since it'll cause hugely slow updates
  11952. var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
  11953. var marks = [], ranges = cm.listSelections();
  11954. for (var i = 0; i < ranges.length; i++) {
  11955. var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
  11956. if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
  11957. var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
  11958. marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
  11959. if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
  11960. marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
  11961. }
  11962. }
  11963. if (marks.length) {
  11964. // Kludge to work around the IE bug from issue #1193, where text
  11965. // input stops going to the textare whever this fires.
  11966. if (ie_lt8 && cm.state.focused) cm.focus();
  11967. var clear = function() {
  11968. cm.operation(function() {
  11969. for (var i = 0; i < marks.length; i++) marks[i].clear();
  11970. });
  11971. };
  11972. if (autoclear) setTimeout(clear, 800);
  11973. else return clear;
  11974. }
  11975. }
  11976. function doMatchBrackets(cm) {
  11977. cm.operation(function() {
  11978. if (cm.state.matchBrackets.currentlyHighlighted) {
  11979. cm.state.matchBrackets.currentlyHighlighted();
  11980. cm.state.matchBrackets.currentlyHighlighted = null;
  11981. }
  11982. cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
  11983. });
  11984. }
  11985. CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
  11986. function clear(cm) {
  11987. if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
  11988. cm.state.matchBrackets.currentlyHighlighted();
  11989. cm.state.matchBrackets.currentlyHighlighted = null;
  11990. }
  11991. }
  11992. if (old && old != CodeMirror.Init) {
  11993. cm.off("cursorActivity", doMatchBrackets);
  11994. cm.off("focus", doMatchBrackets)
  11995. cm.off("blur", clear)
  11996. clear(cm);
  11997. }
  11998. if (val) {
  11999. cm.state.matchBrackets = typeof val == "object" ? val : {};
  12000. cm.on("cursorActivity", doMatchBrackets);
  12001. cm.on("focus", doMatchBrackets)
  12002. cm.on("blur", clear)
  12003. }
  12004. });
  12005. CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
  12006. CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){
  12007. // Backwards-compatibility kludge
  12008. if (oldConfig || typeof config == "boolean") {
  12009. if (!oldConfig) {
  12010. config = config ? {strict: true} : null
  12011. } else {
  12012. oldConfig.strict = config
  12013. config = oldConfig
  12014. }
  12015. }
  12016. return findMatchingBracket(this, pos, config)
  12017. });
  12018. CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
  12019. return scanForBracket(this, pos, dir, style, config);
  12020. });
  12021. });
  12022. /***/ }),
  12023. /***/ "./node_modules/codemirror/addon/selection/active-line.js":
  12024. /*!****************************************************************!*\
  12025. !*** ./node_modules/codemirror/addon/selection/active-line.js ***!
  12026. \****************************************************************/
  12027. /*! no static exports found */
  12028. /***/ (function(module, exports, __webpack_require__) {
  12029. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  12030. // Distributed under an MIT license: https://codemirror.net/LICENSE
  12031. (function(mod) {
  12032. if (true) // CommonJS
  12033. mod(__webpack_require__(/*! ../../lib/codemirror */ "./node_modules/codemirror/lib/codemirror.js"));
  12034. else {}
  12035. })(function(CodeMirror) {
  12036. "use strict";
  12037. var WRAP_CLASS = "CodeMirror-activeline";
  12038. var BACK_CLASS = "CodeMirror-activeline-background";
  12039. var GUTT_CLASS = "CodeMirror-activeline-gutter";
  12040. CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
  12041. var prev = old == CodeMirror.Init ? false : old;
  12042. if (val == prev) return
  12043. if (prev) {
  12044. cm.off("beforeSelectionChange", selectionChange);
  12045. clearActiveLines(cm);
  12046. delete cm.state.activeLines;
  12047. }
  12048. if (val) {
  12049. cm.state.activeLines = [];
  12050. updateActiveLines(cm, cm.listSelections());
  12051. cm.on("beforeSelectionChange", selectionChange);
  12052. }
  12053. });
  12054. function clearActiveLines(cm) {
  12055. for (var i = 0; i < cm.state.activeLines.length; i++) {
  12056. cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
  12057. cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
  12058. cm.removeLineClass(cm.state.activeLines[i], "gutter", GUTT_CLASS);
  12059. }
  12060. }
  12061. function sameArray(a, b) {
  12062. if (a.length != b.length) return false;
  12063. for (var i = 0; i < a.length; i++)
  12064. if (a[i] != b[i]) return false;
  12065. return true;
  12066. }
  12067. function updateActiveLines(cm, ranges) {
  12068. var active = [];
  12069. for (var i = 0; i < ranges.length; i++) {
  12070. var range = ranges[i];
  12071. var option = cm.getOption("styleActiveLine");
  12072. if (typeof option == "object" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())
  12073. continue
  12074. var line = cm.getLineHandleVisualStart(range.head.line);
  12075. if (active[active.length - 1] != line) active.push(line);
  12076. }
  12077. if (sameArray(cm.state.activeLines, active)) return;
  12078. cm.operation(function() {
  12079. clearActiveLines(cm);
  12080. for (var i = 0; i < active.length; i++) {
  12081. cm.addLineClass(active[i], "wrap", WRAP_CLASS);
  12082. cm.addLineClass(active[i], "background", BACK_CLASS);
  12083. cm.addLineClass(active[i], "gutter", GUTT_CLASS);
  12084. }
  12085. cm.state.activeLines = active;
  12086. });
  12087. }
  12088. function selectionChange(cm, sel) {
  12089. updateActiveLines(cm, sel.ranges);
  12090. }
  12091. });
  12092. /***/ }),
  12093. /***/ "./node_modules/codemirror/lib/codemirror.js":
  12094. /*!***************************************************!*\
  12095. !*** ./node_modules/codemirror/lib/codemirror.js ***!
  12096. \***************************************************/
  12097. /*! no static exports found */
  12098. /***/ (function(module, exports, __webpack_require__) {
  12099. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  12100. // Distributed under an MIT license: https://codemirror.net/LICENSE
  12101. // This is CodeMirror (https://codemirror.net), a code editor
  12102. // implemented in JavaScript on top of the browser's DOM.
  12103. //
  12104. // You can find some technical background for some of the code below
  12105. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  12106. (function (global, factory) {
  12107. true ? module.exports = factory() :
  12108. undefined;
  12109. }(this, (function () { 'use strict';
  12110. // Kludges for bugs and behavior differences that can't be feature
  12111. // detected are enabled based on userAgent etc sniffing.
  12112. var userAgent = navigator.userAgent;
  12113. var platform = navigator.platform;
  12114. var gecko = /gecko\/\d/i.test(userAgent);
  12115. var ie_upto10 = /MSIE \d/.test(userAgent);
  12116. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  12117. var edge = /Edge\/(\d+)/.exec(userAgent);
  12118. var ie = ie_upto10 || ie_11up || edge;
  12119. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  12120. var webkit = !edge && /WebKit\//.test(userAgent);
  12121. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  12122. var chrome = !edge && /Chrome\//.test(userAgent);
  12123. var presto = /Opera\//.test(userAgent);
  12124. var safari = /Apple Computer/.test(navigator.vendor);
  12125. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  12126. var phantom = /PhantomJS/.test(userAgent);
  12127. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  12128. var android = /Android/.test(userAgent);
  12129. // This is woefully incomplete. Suggestions for alternative methods welcome.
  12130. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  12131. var mac = ios || /Mac/.test(platform);
  12132. var chromeOS = /\bCrOS\b/.test(userAgent);
  12133. var windows = /win/i.test(platform);
  12134. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  12135. if (presto_version) { presto_version = Number(presto_version[1]); }
  12136. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  12137. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  12138. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  12139. var captureRightClick = gecko || (ie && ie_version >= 9);
  12140. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  12141. var rmClass = function(node, cls) {
  12142. var current = node.className;
  12143. var match = classTest(cls).exec(current);
  12144. if (match) {
  12145. var after = current.slice(match.index + match[0].length);
  12146. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  12147. }
  12148. };
  12149. function removeChildren(e) {
  12150. for (var count = e.childNodes.length; count > 0; --count)
  12151. { e.removeChild(e.firstChild); }
  12152. return e
  12153. }
  12154. function removeChildrenAndAdd(parent, e) {
  12155. return removeChildren(parent).appendChild(e)
  12156. }
  12157. function elt(tag, content, className, style) {
  12158. var e = document.createElement(tag);
  12159. if (className) { e.className = className; }
  12160. if (style) { e.style.cssText = style; }
  12161. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  12162. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  12163. return e
  12164. }
  12165. // wrapper for elt, which removes the elt from the accessibility tree
  12166. function eltP(tag, content, className, style) {
  12167. var e = elt(tag, content, className, style);
  12168. e.setAttribute("role", "presentation");
  12169. return e
  12170. }
  12171. var range;
  12172. if (document.createRange) { range = function(node, start, end, endNode) {
  12173. var r = document.createRange();
  12174. r.setEnd(endNode || node, end);
  12175. r.setStart(node, start);
  12176. return r
  12177. }; }
  12178. else { range = function(node, start, end) {
  12179. var r = document.body.createTextRange();
  12180. try { r.moveToElementText(node.parentNode); }
  12181. catch(e) { return r }
  12182. r.collapse(true);
  12183. r.moveEnd("character", end);
  12184. r.moveStart("character", start);
  12185. return r
  12186. }; }
  12187. function contains(parent, child) {
  12188. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  12189. { child = child.parentNode; }
  12190. if (parent.contains)
  12191. { return parent.contains(child) }
  12192. do {
  12193. if (child.nodeType == 11) { child = child.host; }
  12194. if (child == parent) { return true }
  12195. } while (child = child.parentNode)
  12196. }
  12197. function activeElt() {
  12198. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  12199. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  12200. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  12201. var activeElement;
  12202. try {
  12203. activeElement = document.activeElement;
  12204. } catch(e) {
  12205. activeElement = document.body || null;
  12206. }
  12207. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  12208. { activeElement = activeElement.shadowRoot.activeElement; }
  12209. return activeElement
  12210. }
  12211. function addClass(node, cls) {
  12212. var current = node.className;
  12213. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  12214. }
  12215. function joinClasses(a, b) {
  12216. var as = a.split(" ");
  12217. for (var i = 0; i < as.length; i++)
  12218. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  12219. return b
  12220. }
  12221. var selectInput = function(node) { node.select(); };
  12222. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  12223. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  12224. else if (ie) // Suppress mysterious IE10 errors
  12225. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  12226. function bind(f) {
  12227. var args = Array.prototype.slice.call(arguments, 1);
  12228. return function(){return f.apply(null, args)}
  12229. }
  12230. function copyObj(obj, target, overwrite) {
  12231. if (!target) { target = {}; }
  12232. for (var prop in obj)
  12233. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  12234. { target[prop] = obj[prop]; } }
  12235. return target
  12236. }
  12237. // Counts the column offset in a string, taking tabs into account.
  12238. // Used mostly to find indentation.
  12239. function countColumn(string, end, tabSize, startIndex, startValue) {
  12240. if (end == null) {
  12241. end = string.search(/[^\s\u00a0]/);
  12242. if (end == -1) { end = string.length; }
  12243. }
  12244. for (var i = startIndex || 0, n = startValue || 0;;) {
  12245. var nextTab = string.indexOf("\t", i);
  12246. if (nextTab < 0 || nextTab >= end)
  12247. { return n + (end - i) }
  12248. n += nextTab - i;
  12249. n += tabSize - (n % tabSize);
  12250. i = nextTab + 1;
  12251. }
  12252. }
  12253. var Delayed = function() {
  12254. this.id = null;
  12255. this.f = null;
  12256. this.time = 0;
  12257. this.handler = bind(this.onTimeout, this);
  12258. };
  12259. Delayed.prototype.onTimeout = function (self) {
  12260. self.id = 0;
  12261. if (self.time <= +new Date) {
  12262. self.f();
  12263. } else {
  12264. setTimeout(self.handler, self.time - +new Date);
  12265. }
  12266. };
  12267. Delayed.prototype.set = function (ms, f) {
  12268. this.f = f;
  12269. var time = +new Date + ms;
  12270. if (!this.id || time < this.time) {
  12271. clearTimeout(this.id);
  12272. this.id = setTimeout(this.handler, ms);
  12273. this.time = time;
  12274. }
  12275. };
  12276. function indexOf(array, elt) {
  12277. for (var i = 0; i < array.length; ++i)
  12278. { if (array[i] == elt) { return i } }
  12279. return -1
  12280. }
  12281. // Number of pixels added to scroller and sizer to hide scrollbar
  12282. var scrollerGap = 50;
  12283. // Returned or thrown by various protocols to signal 'I'm not
  12284. // handling this'.
  12285. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  12286. // Reused option objects for setSelection & friends
  12287. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  12288. // The inverse of countColumn -- find the offset that corresponds to
  12289. // a particular column.
  12290. function findColumn(string, goal, tabSize) {
  12291. for (var pos = 0, col = 0;;) {
  12292. var nextTab = string.indexOf("\t", pos);
  12293. if (nextTab == -1) { nextTab = string.length; }
  12294. var skipped = nextTab - pos;
  12295. if (nextTab == string.length || col + skipped >= goal)
  12296. { return pos + Math.min(skipped, goal - col) }
  12297. col += nextTab - pos;
  12298. col += tabSize - (col % tabSize);
  12299. pos = nextTab + 1;
  12300. if (col >= goal) { return pos }
  12301. }
  12302. }
  12303. var spaceStrs = [""];
  12304. function spaceStr(n) {
  12305. while (spaceStrs.length <= n)
  12306. { spaceStrs.push(lst(spaceStrs) + " "); }
  12307. return spaceStrs[n]
  12308. }
  12309. function lst(arr) { return arr[arr.length-1] }
  12310. function map(array, f) {
  12311. var out = [];
  12312. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  12313. return out
  12314. }
  12315. function insertSorted(array, value, score) {
  12316. var pos = 0, priority = score(value);
  12317. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  12318. array.splice(pos, 0, value);
  12319. }
  12320. function nothing() {}
  12321. function createObj(base, props) {
  12322. var inst;
  12323. if (Object.create) {
  12324. inst = Object.create(base);
  12325. } else {
  12326. nothing.prototype = base;
  12327. inst = new nothing();
  12328. }
  12329. if (props) { copyObj(props, inst); }
  12330. return inst
  12331. }
  12332. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  12333. function isWordCharBasic(ch) {
  12334. return /\w/.test(ch) || ch > "\x80" &&
  12335. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  12336. }
  12337. function isWordChar(ch, helper) {
  12338. if (!helper) { return isWordCharBasic(ch) }
  12339. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  12340. return helper.test(ch)
  12341. }
  12342. function isEmpty(obj) {
  12343. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  12344. return true
  12345. }
  12346. // Extending unicode characters. A series of a non-extending char +
  12347. // any number of extending chars is treated as a single unit as far
  12348. // as editing and measuring is concerned. This is not fully correct,
  12349. // since some scripts/fonts/browsers also treat other configurations
  12350. // of code points as a group.
  12351. 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]/;
  12352. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  12353. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  12354. function skipExtendingChars(str, pos, dir) {
  12355. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  12356. return pos
  12357. }
  12358. // Returns the value from the range [`from`; `to`] that satisfies
  12359. // `pred` and is closest to `from`. Assumes that at least `to`
  12360. // satisfies `pred`. Supports `from` being greater than `to`.
  12361. function findFirst(pred, from, to) {
  12362. // At any point we are certain `to` satisfies `pred`, don't know
  12363. // whether `from` does.
  12364. var dir = from > to ? -1 : 1;
  12365. for (;;) {
  12366. if (from == to) { return from }
  12367. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  12368. if (mid == from) { return pred(mid) ? from : to }
  12369. if (pred(mid)) { to = mid; }
  12370. else { from = mid + dir; }
  12371. }
  12372. }
  12373. // BIDI HELPERS
  12374. function iterateBidiSections(order, from, to, f) {
  12375. if (!order) { return f(from, to, "ltr", 0) }
  12376. var found = false;
  12377. for (var i = 0; i < order.length; ++i) {
  12378. var part = order[i];
  12379. if (part.from < to && part.to > from || from == to && part.to == from) {
  12380. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  12381. found = true;
  12382. }
  12383. }
  12384. if (!found) { f(from, to, "ltr"); }
  12385. }
  12386. var bidiOther = null;
  12387. function getBidiPartAt(order, ch, sticky) {
  12388. var found;
  12389. bidiOther = null;
  12390. for (var i = 0; i < order.length; ++i) {
  12391. var cur = order[i];
  12392. if (cur.from < ch && cur.to > ch) { return i }
  12393. if (cur.to == ch) {
  12394. if (cur.from != cur.to && sticky == "before") { found = i; }
  12395. else { bidiOther = i; }
  12396. }
  12397. if (cur.from == ch) {
  12398. if (cur.from != cur.to && sticky != "before") { found = i; }
  12399. else { bidiOther = i; }
  12400. }
  12401. }
  12402. return found != null ? found : bidiOther
  12403. }
  12404. // Bidirectional ordering algorithm
  12405. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  12406. // that this (partially) implements.
  12407. // One-char codes used for character types:
  12408. // L (L): Left-to-Right
  12409. // R (R): Right-to-Left
  12410. // r (AL): Right-to-Left Arabic
  12411. // 1 (EN): European Number
  12412. // + (ES): European Number Separator
  12413. // % (ET): European Number Terminator
  12414. // n (AN): Arabic Number
  12415. // , (CS): Common Number Separator
  12416. // m (NSM): Non-Spacing Mark
  12417. // b (BN): Boundary Neutral
  12418. // s (B): Paragraph Separator
  12419. // t (S): Segment Separator
  12420. // w (WS): Whitespace
  12421. // N (ON): Other Neutrals
  12422. // Returns null if characters are ordered as they appear
  12423. // (left-to-right), or an array of sections ({from, to, level}
  12424. // objects) in the order in which they occur visually.
  12425. var bidiOrdering = (function() {
  12426. // Character types for codepoints 0 to 0xff
  12427. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  12428. // Character types for codepoints 0x600 to 0x6f9
  12429. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  12430. function charType(code) {
  12431. if (code <= 0xf7) { return lowTypes.charAt(code) }
  12432. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  12433. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  12434. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  12435. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  12436. else if (code == 0x200c) { return "b" }
  12437. else { return "L" }
  12438. }
  12439. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  12440. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  12441. function BidiSpan(level, from, to) {
  12442. this.level = level;
  12443. this.from = from; this.to = to;
  12444. }
  12445. return function(str, direction) {
  12446. var outerType = direction == "ltr" ? "L" : "R";
  12447. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  12448. var len = str.length, types = [];
  12449. for (var i = 0; i < len; ++i)
  12450. { types.push(charType(str.charCodeAt(i))); }
  12451. // W1. Examine each non-spacing mark (NSM) in the level run, and
  12452. // change the type of the NSM to the type of the previous
  12453. // character. If the NSM is at the start of the level run, it will
  12454. // get the type of sor.
  12455. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  12456. var type = types[i$1];
  12457. if (type == "m") { types[i$1] = prev; }
  12458. else { prev = type; }
  12459. }
  12460. // W2. Search backwards from each instance of a European number
  12461. // until the first strong type (R, L, AL, or sor) is found. If an
  12462. // AL is found, change the type of the European number to Arabic
  12463. // number.
  12464. // W3. Change all ALs to R.
  12465. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  12466. var type$1 = types[i$2];
  12467. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  12468. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  12469. }
  12470. // W4. A single European separator between two European numbers
  12471. // changes to a European number. A single common separator between
  12472. // two numbers of the same type changes to that type.
  12473. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  12474. var type$2 = types[i$3];
  12475. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  12476. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  12477. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  12478. prev$1 = type$2;
  12479. }
  12480. // W5. A sequence of European terminators adjacent to European
  12481. // numbers changes to all European numbers.
  12482. // W6. Otherwise, separators and terminators change to Other
  12483. // Neutral.
  12484. for (var i$4 = 0; i$4 < len; ++i$4) {
  12485. var type$3 = types[i$4];
  12486. if (type$3 == ",") { types[i$4] = "N"; }
  12487. else if (type$3 == "%") {
  12488. var end = (void 0);
  12489. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  12490. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  12491. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  12492. i$4 = end - 1;
  12493. }
  12494. }
  12495. // W7. Search backwards from each instance of a European number
  12496. // until the first strong type (R, L, or sor) is found. If an L is
  12497. // found, then change the type of the European number to L.
  12498. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  12499. var type$4 = types[i$5];
  12500. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  12501. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  12502. }
  12503. // N1. A sequence of neutrals takes the direction of the
  12504. // surrounding strong text if the text on both sides has the same
  12505. // direction. European and Arabic numbers act as if they were R in
  12506. // terms of their influence on neutrals. Start-of-level-run (sor)
  12507. // and end-of-level-run (eor) are used at level run boundaries.
  12508. // N2. Any remaining neutrals take the embedding direction.
  12509. for (var i$6 = 0; i$6 < len; ++i$6) {
  12510. if (isNeutral.test(types[i$6])) {
  12511. var end$1 = (void 0);
  12512. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  12513. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  12514. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  12515. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  12516. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  12517. i$6 = end$1 - 1;
  12518. }
  12519. }
  12520. // Here we depart from the documented algorithm, in order to avoid
  12521. // building up an actual levels array. Since there are only three
  12522. // levels (0, 1, 2) in an implementation that doesn't take
  12523. // explicit embedding into account, we can build up the order on
  12524. // the fly, without following the level-based algorithm.
  12525. var order = [], m;
  12526. for (var i$7 = 0; i$7 < len;) {
  12527. if (countsAsLeft.test(types[i$7])) {
  12528. var start = i$7;
  12529. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  12530. order.push(new BidiSpan(0, start, i$7));
  12531. } else {
  12532. var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  12533. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  12534. for (var j$2 = pos; j$2 < i$7;) {
  12535. if (countsAsNum.test(types[j$2])) {
  12536. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  12537. var nstart = j$2;
  12538. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  12539. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  12540. at += isRTL;
  12541. pos = j$2;
  12542. } else { ++j$2; }
  12543. }
  12544. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  12545. }
  12546. }
  12547. if (direction == "ltr") {
  12548. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  12549. order[0].from = m[0].length;
  12550. order.unshift(new BidiSpan(0, 0, m[0].length));
  12551. }
  12552. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  12553. lst(order).to -= m[0].length;
  12554. order.push(new BidiSpan(0, len - m[0].length, len));
  12555. }
  12556. }
  12557. return direction == "rtl" ? order.reverse() : order
  12558. }
  12559. })();
  12560. // Get the bidi ordering for the given line (and cache it). Returns
  12561. // false for lines that are fully left-to-right, and an array of
  12562. // BidiSpan objects otherwise.
  12563. function getOrder(line, direction) {
  12564. var order = line.order;
  12565. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  12566. return order
  12567. }
  12568. // EVENT HANDLING
  12569. // Lightweight event framework. on/off also work on DOM nodes,
  12570. // registering native DOM handlers.
  12571. var noHandlers = [];
  12572. var on = function(emitter, type, f) {
  12573. if (emitter.addEventListener) {
  12574. emitter.addEventListener(type, f, false);
  12575. } else if (emitter.attachEvent) {
  12576. emitter.attachEvent("on" + type, f);
  12577. } else {
  12578. var map = emitter._handlers || (emitter._handlers = {});
  12579. map[type] = (map[type] || noHandlers).concat(f);
  12580. }
  12581. };
  12582. function getHandlers(emitter, type) {
  12583. return emitter._handlers && emitter._handlers[type] || noHandlers
  12584. }
  12585. function off(emitter, type, f) {
  12586. if (emitter.removeEventListener) {
  12587. emitter.removeEventListener(type, f, false);
  12588. } else if (emitter.detachEvent) {
  12589. emitter.detachEvent("on" + type, f);
  12590. } else {
  12591. var map = emitter._handlers, arr = map && map[type];
  12592. if (arr) {
  12593. var index = indexOf(arr, f);
  12594. if (index > -1)
  12595. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  12596. }
  12597. }
  12598. }
  12599. function signal(emitter, type /*, values...*/) {
  12600. var handlers = getHandlers(emitter, type);
  12601. if (!handlers.length) { return }
  12602. var args = Array.prototype.slice.call(arguments, 2);
  12603. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  12604. }
  12605. // The DOM events that CodeMirror handles can be overridden by
  12606. // registering a (non-DOM) handler on the editor for the event name,
  12607. // and preventDefault-ing the event in that handler.
  12608. function signalDOMEvent(cm, e, override) {
  12609. if (typeof e == "string")
  12610. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  12611. signal(cm, override || e.type, cm, e);
  12612. return e_defaultPrevented(e) || e.codemirrorIgnore
  12613. }
  12614. function signalCursorActivity(cm) {
  12615. var arr = cm._handlers && cm._handlers.cursorActivity;
  12616. if (!arr) { return }
  12617. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  12618. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  12619. { set.push(arr[i]); } }
  12620. }
  12621. function hasHandler(emitter, type) {
  12622. return getHandlers(emitter, type).length > 0
  12623. }
  12624. // Add on and off methods to a constructor's prototype, to make
  12625. // registering events on such objects more convenient.
  12626. function eventMixin(ctor) {
  12627. ctor.prototype.on = function(type, f) {on(this, type, f);};
  12628. ctor.prototype.off = function(type, f) {off(this, type, f);};
  12629. }
  12630. // Due to the fact that we still support jurassic IE versions, some
  12631. // compatibility wrappers are needed.
  12632. function e_preventDefault(e) {
  12633. if (e.preventDefault) { e.preventDefault(); }
  12634. else { e.returnValue = false; }
  12635. }
  12636. function e_stopPropagation(e) {
  12637. if (e.stopPropagation) { e.stopPropagation(); }
  12638. else { e.cancelBubble = true; }
  12639. }
  12640. function e_defaultPrevented(e) {
  12641. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  12642. }
  12643. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  12644. function e_target(e) {return e.target || e.srcElement}
  12645. function e_button(e) {
  12646. var b = e.which;
  12647. if (b == null) {
  12648. if (e.button & 1) { b = 1; }
  12649. else if (e.button & 2) { b = 3; }
  12650. else if (e.button & 4) { b = 2; }
  12651. }
  12652. if (mac && e.ctrlKey && b == 1) { b = 3; }
  12653. return b
  12654. }
  12655. // Detect drag-and-drop
  12656. var dragAndDrop = function() {
  12657. // There is *some* kind of drag-and-drop support in IE6-8, but I
  12658. // couldn't get it to work yet.
  12659. if (ie && ie_version < 9) { return false }
  12660. var div = elt('div');
  12661. return "draggable" in div || "dragDrop" in div
  12662. }();
  12663. var zwspSupported;
  12664. function zeroWidthElement(measure) {
  12665. if (zwspSupported == null) {
  12666. var test = elt("span", "\u200b");
  12667. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  12668. if (measure.firstChild.offsetHeight != 0)
  12669. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  12670. }
  12671. var node = zwspSupported ? elt("span", "\u200b") :
  12672. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  12673. node.setAttribute("cm-text", "");
  12674. return node
  12675. }
  12676. // Feature-detect IE's crummy client rect reporting for bidi text
  12677. var badBidiRects;
  12678. function hasBadBidiRects(measure) {
  12679. if (badBidiRects != null) { return badBidiRects }
  12680. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  12681. var r0 = range(txt, 0, 1).getBoundingClientRect();
  12682. var r1 = range(txt, 1, 2).getBoundingClientRect();
  12683. removeChildren(measure);
  12684. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  12685. return badBidiRects = (r1.right - r0.right < 3)
  12686. }
  12687. // See if "".split is the broken IE version, if so, provide an
  12688. // alternative way to split lines.
  12689. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  12690. var pos = 0, result = [], l = string.length;
  12691. while (pos <= l) {
  12692. var nl = string.indexOf("\n", pos);
  12693. if (nl == -1) { nl = string.length; }
  12694. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  12695. var rt = line.indexOf("\r");
  12696. if (rt != -1) {
  12697. result.push(line.slice(0, rt));
  12698. pos += rt + 1;
  12699. } else {
  12700. result.push(line);
  12701. pos = nl + 1;
  12702. }
  12703. }
  12704. return result
  12705. } : function (string) { return string.split(/\r\n?|\n/); };
  12706. var hasSelection = window.getSelection ? function (te) {
  12707. try { return te.selectionStart != te.selectionEnd }
  12708. catch(e) { return false }
  12709. } : function (te) {
  12710. var range;
  12711. try {range = te.ownerDocument.selection.createRange();}
  12712. catch(e) {}
  12713. if (!range || range.parentElement() != te) { return false }
  12714. return range.compareEndPoints("StartToEnd", range) != 0
  12715. };
  12716. var hasCopyEvent = (function () {
  12717. var e = elt("div");
  12718. if ("oncopy" in e) { return true }
  12719. e.setAttribute("oncopy", "return;");
  12720. return typeof e.oncopy == "function"
  12721. })();
  12722. var badZoomedRects = null;
  12723. function hasBadZoomedRects(measure) {
  12724. if (badZoomedRects != null) { return badZoomedRects }
  12725. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  12726. var normal = node.getBoundingClientRect();
  12727. var fromRange = range(node, 0, 1).getBoundingClientRect();
  12728. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  12729. }
  12730. // Known modes, by name and by MIME
  12731. var modes = {}, mimeModes = {};
  12732. // Extra arguments are stored as the mode's dependencies, which is
  12733. // used by (legacy) mechanisms like loadmode.js to automatically
  12734. // load a mode. (Preferred mechanism is the require/define calls.)
  12735. function defineMode(name, mode) {
  12736. if (arguments.length > 2)
  12737. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  12738. modes[name] = mode;
  12739. }
  12740. function defineMIME(mime, spec) {
  12741. mimeModes[mime] = spec;
  12742. }
  12743. // Given a MIME type, a {name, ...options} config object, or a name
  12744. // string, return a mode config object.
  12745. function resolveMode(spec) {
  12746. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  12747. spec = mimeModes[spec];
  12748. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  12749. var found = mimeModes[spec.name];
  12750. if (typeof found == "string") { found = {name: found}; }
  12751. spec = createObj(found, spec);
  12752. spec.name = found.name;
  12753. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  12754. return resolveMode("application/xml")
  12755. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  12756. return resolveMode("application/json")
  12757. }
  12758. if (typeof spec == "string") { return {name: spec} }
  12759. else { return spec || {name: "null"} }
  12760. }
  12761. // Given a mode spec (anything that resolveMode accepts), find and
  12762. // initialize an actual mode object.
  12763. function getMode(options, spec) {
  12764. spec = resolveMode(spec);
  12765. var mfactory = modes[spec.name];
  12766. if (!mfactory) { return getMode(options, "text/plain") }
  12767. var modeObj = mfactory(options, spec);
  12768. if (modeExtensions.hasOwnProperty(spec.name)) {
  12769. var exts = modeExtensions[spec.name];
  12770. for (var prop in exts) {
  12771. if (!exts.hasOwnProperty(prop)) { continue }
  12772. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  12773. modeObj[prop] = exts[prop];
  12774. }
  12775. }
  12776. modeObj.name = spec.name;
  12777. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  12778. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  12779. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  12780. return modeObj
  12781. }
  12782. // This can be used to attach properties to mode objects from
  12783. // outside the actual mode definition.
  12784. var modeExtensions = {};
  12785. function extendMode(mode, properties) {
  12786. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  12787. copyObj(properties, exts);
  12788. }
  12789. function copyState(mode, state) {
  12790. if (state === true) { return state }
  12791. if (mode.copyState) { return mode.copyState(state) }
  12792. var nstate = {};
  12793. for (var n in state) {
  12794. var val = state[n];
  12795. if (val instanceof Array) { val = val.concat([]); }
  12796. nstate[n] = val;
  12797. }
  12798. return nstate
  12799. }
  12800. // Given a mode and a state (for that mode), find the inner mode and
  12801. // state at the position that the state refers to.
  12802. function innerMode(mode, state) {
  12803. var info;
  12804. while (mode.innerMode) {
  12805. info = mode.innerMode(state);
  12806. if (!info || info.mode == mode) { break }
  12807. state = info.state;
  12808. mode = info.mode;
  12809. }
  12810. return info || {mode: mode, state: state}
  12811. }
  12812. function startState(mode, a1, a2) {
  12813. return mode.startState ? mode.startState(a1, a2) : true
  12814. }
  12815. // STRING STREAM
  12816. // Fed to the mode parsers, provides helper functions to make
  12817. // parsers more succinct.
  12818. var StringStream = function(string, tabSize, lineOracle) {
  12819. this.pos = this.start = 0;
  12820. this.string = string;
  12821. this.tabSize = tabSize || 8;
  12822. this.lastColumnPos = this.lastColumnValue = 0;
  12823. this.lineStart = 0;
  12824. this.lineOracle = lineOracle;
  12825. };
  12826. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  12827. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  12828. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  12829. StringStream.prototype.next = function () {
  12830. if (this.pos < this.string.length)
  12831. { return this.string.charAt(this.pos++) }
  12832. };
  12833. StringStream.prototype.eat = function (match) {
  12834. var ch = this.string.charAt(this.pos);
  12835. var ok;
  12836. if (typeof match == "string") { ok = ch == match; }
  12837. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  12838. if (ok) {++this.pos; return ch}
  12839. };
  12840. StringStream.prototype.eatWhile = function (match) {
  12841. var start = this.pos;
  12842. while (this.eat(match)){}
  12843. return this.pos > start
  12844. };
  12845. StringStream.prototype.eatSpace = function () {
  12846. var start = this.pos;
  12847. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  12848. return this.pos > start
  12849. };
  12850. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  12851. StringStream.prototype.skipTo = function (ch) {
  12852. var found = this.string.indexOf(ch, this.pos);
  12853. if (found > -1) {this.pos = found; return true}
  12854. };
  12855. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  12856. StringStream.prototype.column = function () {
  12857. if (this.lastColumnPos < this.start) {
  12858. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  12859. this.lastColumnPos = this.start;
  12860. }
  12861. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  12862. };
  12863. StringStream.prototype.indentation = function () {
  12864. return countColumn(this.string, null, this.tabSize) -
  12865. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  12866. };
  12867. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  12868. if (typeof pattern == "string") {
  12869. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  12870. var substr = this.string.substr(this.pos, pattern.length);
  12871. if (cased(substr) == cased(pattern)) {
  12872. if (consume !== false) { this.pos += pattern.length; }
  12873. return true
  12874. }
  12875. } else {
  12876. var match = this.string.slice(this.pos).match(pattern);
  12877. if (match && match.index > 0) { return null }
  12878. if (match && consume !== false) { this.pos += match[0].length; }
  12879. return match
  12880. }
  12881. };
  12882. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  12883. StringStream.prototype.hideFirstChars = function (n, inner) {
  12884. this.lineStart += n;
  12885. try { return inner() }
  12886. finally { this.lineStart -= n; }
  12887. };
  12888. StringStream.prototype.lookAhead = function (n) {
  12889. var oracle = this.lineOracle;
  12890. return oracle && oracle.lookAhead(n)
  12891. };
  12892. StringStream.prototype.baseToken = function () {
  12893. var oracle = this.lineOracle;
  12894. return oracle && oracle.baseToken(this.pos)
  12895. };
  12896. // Find the line object corresponding to the given line number.
  12897. function getLine(doc, n) {
  12898. n -= doc.first;
  12899. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  12900. var chunk = doc;
  12901. while (!chunk.lines) {
  12902. for (var i = 0;; ++i) {
  12903. var child = chunk.children[i], sz = child.chunkSize();
  12904. if (n < sz) { chunk = child; break }
  12905. n -= sz;
  12906. }
  12907. }
  12908. return chunk.lines[n]
  12909. }
  12910. // Get the part of a document between two positions, as an array of
  12911. // strings.
  12912. function getBetween(doc, start, end) {
  12913. var out = [], n = start.line;
  12914. doc.iter(start.line, end.line + 1, function (line) {
  12915. var text = line.text;
  12916. if (n == end.line) { text = text.slice(0, end.ch); }
  12917. if (n == start.line) { text = text.slice(start.ch); }
  12918. out.push(text);
  12919. ++n;
  12920. });
  12921. return out
  12922. }
  12923. // Get the lines between from and to, as array of strings.
  12924. function getLines(doc, from, to) {
  12925. var out = [];
  12926. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  12927. return out
  12928. }
  12929. // Update the height of a line, propagating the height change
  12930. // upwards to parent nodes.
  12931. function updateLineHeight(line, height) {
  12932. var diff = height - line.height;
  12933. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  12934. }
  12935. // Given a line object, find its line number by walking up through
  12936. // its parent links.
  12937. function lineNo(line) {
  12938. if (line.parent == null) { return null }
  12939. var cur = line.parent, no = indexOf(cur.lines, line);
  12940. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  12941. for (var i = 0;; ++i) {
  12942. if (chunk.children[i] == cur) { break }
  12943. no += chunk.children[i].chunkSize();
  12944. }
  12945. }
  12946. return no + cur.first
  12947. }
  12948. // Find the line at the given vertical position, using the height
  12949. // information in the document tree.
  12950. function lineAtHeight(chunk, h) {
  12951. var n = chunk.first;
  12952. outer: do {
  12953. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  12954. var child = chunk.children[i$1], ch = child.height;
  12955. if (h < ch) { chunk = child; continue outer }
  12956. h -= ch;
  12957. n += child.chunkSize();
  12958. }
  12959. return n
  12960. } while (!chunk.lines)
  12961. var i = 0;
  12962. for (; i < chunk.lines.length; ++i) {
  12963. var line = chunk.lines[i], lh = line.height;
  12964. if (h < lh) { break }
  12965. h -= lh;
  12966. }
  12967. return n + i
  12968. }
  12969. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  12970. function lineNumberFor(options, i) {
  12971. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  12972. }
  12973. // A Pos instance represents a position within the text.
  12974. function Pos(line, ch, sticky) {
  12975. if ( sticky === void 0 ) sticky = null;
  12976. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  12977. this.line = line;
  12978. this.ch = ch;
  12979. this.sticky = sticky;
  12980. }
  12981. // Compare two positions, return 0 if they are the same, a negative
  12982. // number when a is less, and a positive number otherwise.
  12983. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  12984. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  12985. function copyPos(x) {return Pos(x.line, x.ch)}
  12986. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  12987. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  12988. // Most of the external API clips given positions to make sure they
  12989. // actually exist within the document.
  12990. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  12991. function clipPos(doc, pos) {
  12992. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  12993. var last = doc.first + doc.size - 1;
  12994. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  12995. return clipToLen(pos, getLine(doc, pos.line).text.length)
  12996. }
  12997. function clipToLen(pos, linelen) {
  12998. var ch = pos.ch;
  12999. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  13000. else if (ch < 0) { return Pos(pos.line, 0) }
  13001. else { return pos }
  13002. }
  13003. function clipPosArray(doc, array) {
  13004. var out = [];
  13005. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  13006. return out
  13007. }
  13008. var SavedContext = function(state, lookAhead) {
  13009. this.state = state;
  13010. this.lookAhead = lookAhead;
  13011. };
  13012. var Context = function(doc, state, line, lookAhead) {
  13013. this.state = state;
  13014. this.doc = doc;
  13015. this.line = line;
  13016. this.maxLookAhead = lookAhead || 0;
  13017. this.baseTokens = null;
  13018. this.baseTokenPos = 1;
  13019. };
  13020. Context.prototype.lookAhead = function (n) {
  13021. var line = this.doc.getLine(this.line + n);
  13022. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  13023. return line
  13024. };
  13025. Context.prototype.baseToken = function (n) {
  13026. if (!this.baseTokens) { return null }
  13027. while (this.baseTokens[this.baseTokenPos] <= n)
  13028. { this.baseTokenPos += 2; }
  13029. var type = this.baseTokens[this.baseTokenPos + 1];
  13030. return {type: type && type.replace(/( |^)overlay .*/, ""),
  13031. size: this.baseTokens[this.baseTokenPos] - n}
  13032. };
  13033. Context.prototype.nextLine = function () {
  13034. this.line++;
  13035. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  13036. };
  13037. Context.fromSaved = function (doc, saved, line) {
  13038. if (saved instanceof SavedContext)
  13039. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  13040. else
  13041. { return new Context(doc, copyState(doc.mode, saved), line) }
  13042. };
  13043. Context.prototype.save = function (copy) {
  13044. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  13045. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  13046. };
  13047. // Compute a style array (an array starting with a mode generation
  13048. // -- for invalidation -- followed by pairs of end positions and
  13049. // style strings), which is used to highlight the tokens on the
  13050. // line.
  13051. function highlightLine(cm, line, context, forceToEnd) {
  13052. // A styles array always starts with a number identifying the
  13053. // mode/overlays that it is based on (for easy invalidation).
  13054. var st = [cm.state.modeGen], lineClasses = {};
  13055. // Compute the base array of styles
  13056. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  13057. lineClasses, forceToEnd);
  13058. var state = context.state;
  13059. // Run overlays, adjust style array.
  13060. var loop = function ( o ) {
  13061. context.baseTokens = st;
  13062. var overlay = cm.state.overlays[o], i = 1, at = 0;
  13063. context.state = true;
  13064. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  13065. var start = i;
  13066. // Ensure there's a token end at the current position, and that i points at it
  13067. while (at < end) {
  13068. var i_end = st[i];
  13069. if (i_end > end)
  13070. { st.splice(i, 1, end, st[i+1], i_end); }
  13071. i += 2;
  13072. at = Math.min(end, i_end);
  13073. }
  13074. if (!style) { return }
  13075. if (overlay.opaque) {
  13076. st.splice(start, i - start, end, "overlay " + style);
  13077. i = start + 2;
  13078. } else {
  13079. for (; start < i; start += 2) {
  13080. var cur = st[start+1];
  13081. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  13082. }
  13083. }
  13084. }, lineClasses);
  13085. context.state = state;
  13086. context.baseTokens = null;
  13087. context.baseTokenPos = 1;
  13088. };
  13089. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  13090. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  13091. }
  13092. function getLineStyles(cm, line, updateFrontier) {
  13093. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  13094. var context = getContextBefore(cm, lineNo(line));
  13095. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  13096. var result = highlightLine(cm, line, context);
  13097. if (resetState) { context.state = resetState; }
  13098. line.stateAfter = context.save(!resetState);
  13099. line.styles = result.styles;
  13100. if (result.classes) { line.styleClasses = result.classes; }
  13101. else if (line.styleClasses) { line.styleClasses = null; }
  13102. if (updateFrontier === cm.doc.highlightFrontier)
  13103. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  13104. }
  13105. return line.styles
  13106. }
  13107. function getContextBefore(cm, n, precise) {
  13108. var doc = cm.doc, display = cm.display;
  13109. if (!doc.mode.startState) { return new Context(doc, true, n) }
  13110. var start = findStartLine(cm, n, precise);
  13111. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  13112. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  13113. doc.iter(start, n, function (line) {
  13114. processLine(cm, line.text, context);
  13115. var pos = context.line;
  13116. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  13117. context.nextLine();
  13118. });
  13119. if (precise) { doc.modeFrontier = context.line; }
  13120. return context
  13121. }
  13122. // Lightweight form of highlight -- proceed over this line and
  13123. // update state, but don't save a style array. Used for lines that
  13124. // aren't currently visible.
  13125. function processLine(cm, text, context, startAt) {
  13126. var mode = cm.doc.mode;
  13127. var stream = new StringStream(text, cm.options.tabSize, context);
  13128. stream.start = stream.pos = startAt || 0;
  13129. if (text == "") { callBlankLine(mode, context.state); }
  13130. while (!stream.eol()) {
  13131. readToken(mode, stream, context.state);
  13132. stream.start = stream.pos;
  13133. }
  13134. }
  13135. function callBlankLine(mode, state) {
  13136. if (mode.blankLine) { return mode.blankLine(state) }
  13137. if (!mode.innerMode) { return }
  13138. var inner = innerMode(mode, state);
  13139. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  13140. }
  13141. function readToken(mode, stream, state, inner) {
  13142. for (var i = 0; i < 10; i++) {
  13143. if (inner) { inner[0] = innerMode(mode, state).mode; }
  13144. var style = mode.token(stream, state);
  13145. if (stream.pos > stream.start) { return style }
  13146. }
  13147. throw new Error("Mode " + mode.name + " failed to advance stream.")
  13148. }
  13149. var Token = function(stream, type, state) {
  13150. this.start = stream.start; this.end = stream.pos;
  13151. this.string = stream.current();
  13152. this.type = type || null;
  13153. this.state = state;
  13154. };
  13155. // Utility for getTokenAt and getLineTokens
  13156. function takeToken(cm, pos, precise, asArray) {
  13157. var doc = cm.doc, mode = doc.mode, style;
  13158. pos = clipPos(doc, pos);
  13159. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  13160. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  13161. if (asArray) { tokens = []; }
  13162. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  13163. stream.start = stream.pos;
  13164. style = readToken(mode, stream, context.state);
  13165. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  13166. }
  13167. return asArray ? tokens : new Token(stream, style, context.state)
  13168. }
  13169. function extractLineClasses(type, output) {
  13170. if (type) { for (;;) {
  13171. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  13172. if (!lineClass) { break }
  13173. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  13174. var prop = lineClass[1] ? "bgClass" : "textClass";
  13175. if (output[prop] == null)
  13176. { output[prop] = lineClass[2]; }
  13177. else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  13178. { output[prop] += " " + lineClass[2]; }
  13179. } }
  13180. return type
  13181. }
  13182. // Run the given mode's parser over a line, calling f for each token.
  13183. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  13184. var flattenSpans = mode.flattenSpans;
  13185. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  13186. var curStart = 0, curStyle = null;
  13187. var stream = new StringStream(text, cm.options.tabSize, context), style;
  13188. var inner = cm.options.addModeClass && [null];
  13189. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  13190. while (!stream.eol()) {
  13191. if (stream.pos > cm.options.maxHighlightLength) {
  13192. flattenSpans = false;
  13193. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  13194. stream.pos = text.length;
  13195. style = null;
  13196. } else {
  13197. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  13198. }
  13199. if (inner) {
  13200. var mName = inner[0].name;
  13201. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  13202. }
  13203. if (!flattenSpans || curStyle != style) {
  13204. while (curStart < stream.start) {
  13205. curStart = Math.min(stream.start, curStart + 5000);
  13206. f(curStart, curStyle);
  13207. }
  13208. curStyle = style;
  13209. }
  13210. stream.start = stream.pos;
  13211. }
  13212. while (curStart < stream.pos) {
  13213. // Webkit seems to refuse to render text nodes longer than 57444
  13214. // characters, and returns inaccurate measurements in nodes
  13215. // starting around 5000 chars.
  13216. var pos = Math.min(stream.pos, curStart + 5000);
  13217. f(pos, curStyle);
  13218. curStart = pos;
  13219. }
  13220. }
  13221. // Finds the line to start with when starting a parse. Tries to
  13222. // find a line with a stateAfter, so that it can start with a
  13223. // valid state. If that fails, it returns the line with the
  13224. // smallest indentation, which tends to need the least context to
  13225. // parse correctly.
  13226. function findStartLine(cm, n, precise) {
  13227. var minindent, minline, doc = cm.doc;
  13228. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  13229. for (var search = n; search > lim; --search) {
  13230. if (search <= doc.first) { return doc.first }
  13231. var line = getLine(doc, search - 1), after = line.stateAfter;
  13232. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  13233. { return search }
  13234. var indented = countColumn(line.text, null, cm.options.tabSize);
  13235. if (minline == null || minindent > indented) {
  13236. minline = search - 1;
  13237. minindent = indented;
  13238. }
  13239. }
  13240. return minline
  13241. }
  13242. function retreatFrontier(doc, n) {
  13243. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  13244. if (doc.highlightFrontier < n - 10) { return }
  13245. var start = doc.first;
  13246. for (var line = n - 1; line > start; line--) {
  13247. var saved = getLine(doc, line).stateAfter;
  13248. // change is on 3
  13249. // state on line 1 looked ahead 2 -- so saw 3
  13250. // test 1 + 2 < 3 should cover this
  13251. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  13252. start = line + 1;
  13253. break
  13254. }
  13255. }
  13256. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  13257. }
  13258. // Optimize some code when these features are not used.
  13259. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  13260. function seeReadOnlySpans() {
  13261. sawReadOnlySpans = true;
  13262. }
  13263. function seeCollapsedSpans() {
  13264. sawCollapsedSpans = true;
  13265. }
  13266. // TEXTMARKER SPANS
  13267. function MarkedSpan(marker, from, to) {
  13268. this.marker = marker;
  13269. this.from = from; this.to = to;
  13270. }
  13271. // Search an array of spans for a span matching the given marker.
  13272. function getMarkedSpanFor(spans, marker) {
  13273. if (spans) { for (var i = 0; i < spans.length; ++i) {
  13274. var span = spans[i];
  13275. if (span.marker == marker) { return span }
  13276. } }
  13277. }
  13278. // Remove a span from an array, returning undefined if no spans are
  13279. // left (we don't store arrays for lines without spans).
  13280. function removeMarkedSpan(spans, span) {
  13281. var r;
  13282. for (var i = 0; i < spans.length; ++i)
  13283. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  13284. return r
  13285. }
  13286. // Add a span to a line.
  13287. function addMarkedSpan(line, span) {
  13288. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  13289. span.marker.attachLine(line);
  13290. }
  13291. // Used for the algorithm that adjusts markers for a change in the
  13292. // document. These functions cut an array of spans at a given
  13293. // character position, returning an array of remaining chunks (or
  13294. // undefined if nothing remains).
  13295. function markedSpansBefore(old, startCh, isInsert) {
  13296. var nw;
  13297. if (old) { for (var i = 0; i < old.length; ++i) {
  13298. var span = old[i], marker = span.marker;
  13299. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  13300. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  13301. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  13302. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  13303. }
  13304. } }
  13305. return nw
  13306. }
  13307. function markedSpansAfter(old, endCh, isInsert) {
  13308. var nw;
  13309. if (old) { for (var i = 0; i < old.length; ++i) {
  13310. var span = old[i], marker = span.marker;
  13311. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  13312. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  13313. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  13314. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  13315. span.to == null ? null : span.to - endCh));
  13316. }
  13317. } }
  13318. return nw
  13319. }
  13320. // Given a change object, compute the new set of marker spans that
  13321. // cover the line in which the change took place. Removes spans
  13322. // entirely within the change, reconnects spans belonging to the
  13323. // same marker that appear on both sides of the change, and cuts off
  13324. // spans partially within the change. Returns an array of span
  13325. // arrays with one element for each line in (after) the change.
  13326. function stretchSpansOverChange(doc, change) {
  13327. if (change.full) { return null }
  13328. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  13329. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  13330. if (!oldFirst && !oldLast) { return null }
  13331. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  13332. // Get the spans that 'stick out' on both sides
  13333. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  13334. var last = markedSpansAfter(oldLast, endCh, isInsert);
  13335. // Next, merge those two ends
  13336. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  13337. if (first) {
  13338. // Fix up .to properties of first
  13339. for (var i = 0; i < first.length; ++i) {
  13340. var span = first[i];
  13341. if (span.to == null) {
  13342. var found = getMarkedSpanFor(last, span.marker);
  13343. if (!found) { span.to = startCh; }
  13344. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  13345. }
  13346. }
  13347. }
  13348. if (last) {
  13349. // Fix up .from in last (or move them into first in case of sameLine)
  13350. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  13351. var span$1 = last[i$1];
  13352. if (span$1.to != null) { span$1.to += offset; }
  13353. if (span$1.from == null) {
  13354. var found$1 = getMarkedSpanFor(first, span$1.marker);
  13355. if (!found$1) {
  13356. span$1.from = offset;
  13357. if (sameLine) { (first || (first = [])).push(span$1); }
  13358. }
  13359. } else {
  13360. span$1.from += offset;
  13361. if (sameLine) { (first || (first = [])).push(span$1); }
  13362. }
  13363. }
  13364. }
  13365. // Make sure we didn't create any zero-length spans
  13366. if (first) { first = clearEmptySpans(first); }
  13367. if (last && last != first) { last = clearEmptySpans(last); }
  13368. var newMarkers = [first];
  13369. if (!sameLine) {
  13370. // Fill gap with whole-line-spans
  13371. var gap = change.text.length - 2, gapMarkers;
  13372. if (gap > 0 && first)
  13373. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  13374. { if (first[i$2].to == null)
  13375. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  13376. for (var i$3 = 0; i$3 < gap; ++i$3)
  13377. { newMarkers.push(gapMarkers); }
  13378. newMarkers.push(last);
  13379. }
  13380. return newMarkers
  13381. }
  13382. // Remove spans that are empty and don't have a clearWhenEmpty
  13383. // option of false.
  13384. function clearEmptySpans(spans) {
  13385. for (var i = 0; i < spans.length; ++i) {
  13386. var span = spans[i];
  13387. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  13388. { spans.splice(i--, 1); }
  13389. }
  13390. if (!spans.length) { return null }
  13391. return spans
  13392. }
  13393. // Used to 'clip' out readOnly ranges when making a change.
  13394. function removeReadOnlyRanges(doc, from, to) {
  13395. var markers = null;
  13396. doc.iter(from.line, to.line + 1, function (line) {
  13397. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  13398. var mark = line.markedSpans[i].marker;
  13399. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  13400. { (markers || (markers = [])).push(mark); }
  13401. } }
  13402. });
  13403. if (!markers) { return null }
  13404. var parts = [{from: from, to: to}];
  13405. for (var i = 0; i < markers.length; ++i) {
  13406. var mk = markers[i], m = mk.find(0);
  13407. for (var j = 0; j < parts.length; ++j) {
  13408. var p = parts[j];
  13409. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  13410. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  13411. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  13412. { newParts.push({from: p.from, to: m.from}); }
  13413. if (dto > 0 || !mk.inclusiveRight && !dto)
  13414. { newParts.push({from: m.to, to: p.to}); }
  13415. parts.splice.apply(parts, newParts);
  13416. j += newParts.length - 3;
  13417. }
  13418. }
  13419. return parts
  13420. }
  13421. // Connect or disconnect spans from a line.
  13422. function detachMarkedSpans(line) {
  13423. var spans = line.markedSpans;
  13424. if (!spans) { return }
  13425. for (var i = 0; i < spans.length; ++i)
  13426. { spans[i].marker.detachLine(line); }
  13427. line.markedSpans = null;
  13428. }
  13429. function attachMarkedSpans(line, spans) {
  13430. if (!spans) { return }
  13431. for (var i = 0; i < spans.length; ++i)
  13432. { spans[i].marker.attachLine(line); }
  13433. line.markedSpans = spans;
  13434. }
  13435. // Helpers used when computing which overlapping collapsed span
  13436. // counts as the larger one.
  13437. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  13438. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  13439. // Returns a number indicating which of two overlapping collapsed
  13440. // spans is larger (and thus includes the other). Falls back to
  13441. // comparing ids when the spans cover exactly the same range.
  13442. function compareCollapsedMarkers(a, b) {
  13443. var lenDiff = a.lines.length - b.lines.length;
  13444. if (lenDiff != 0) { return lenDiff }
  13445. var aPos = a.find(), bPos = b.find();
  13446. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  13447. if (fromCmp) { return -fromCmp }
  13448. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  13449. if (toCmp) { return toCmp }
  13450. return b.id - a.id
  13451. }
  13452. // Find out whether a line ends or starts in a collapsed span. If
  13453. // so, return the marker for that span.
  13454. function collapsedSpanAtSide(line, start) {
  13455. var sps = sawCollapsedSpans && line.markedSpans, found;
  13456. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  13457. sp = sps[i];
  13458. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  13459. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  13460. { found = sp.marker; }
  13461. } }
  13462. return found
  13463. }
  13464. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  13465. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  13466. function collapsedSpanAround(line, ch) {
  13467. var sps = sawCollapsedSpans && line.markedSpans, found;
  13468. if (sps) { for (var i = 0; i < sps.length; ++i) {
  13469. var sp = sps[i];
  13470. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  13471. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  13472. } }
  13473. return found
  13474. }
  13475. // Test whether there exists a collapsed span that partially
  13476. // overlaps (covers the start or end, but not both) of a new span.
  13477. // Such overlap is not allowed.
  13478. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  13479. var line = getLine(doc, lineNo);
  13480. var sps = sawCollapsedSpans && line.markedSpans;
  13481. if (sps) { for (var i = 0; i < sps.length; ++i) {
  13482. var sp = sps[i];
  13483. if (!sp.marker.collapsed) { continue }
  13484. var found = sp.marker.find(0);
  13485. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  13486. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  13487. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  13488. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  13489. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  13490. { return true }
  13491. } }
  13492. }
  13493. // A visual line is a line as drawn on the screen. Folding, for
  13494. // example, can cause multiple logical lines to appear on the same
  13495. // visual line. This finds the start of the visual line that the
  13496. // given line is part of (usually that is the line itself).
  13497. function visualLine(line) {
  13498. var merged;
  13499. while (merged = collapsedSpanAtStart(line))
  13500. { line = merged.find(-1, true).line; }
  13501. return line
  13502. }
  13503. function visualLineEnd(line) {
  13504. var merged;
  13505. while (merged = collapsedSpanAtEnd(line))
  13506. { line = merged.find(1, true).line; }
  13507. return line
  13508. }
  13509. // Returns an array of logical lines that continue the visual line
  13510. // started by the argument, or undefined if there are no such lines.
  13511. function visualLineContinued(line) {
  13512. var merged, lines;
  13513. while (merged = collapsedSpanAtEnd(line)) {
  13514. line = merged.find(1, true).line
  13515. ;(lines || (lines = [])).push(line);
  13516. }
  13517. return lines
  13518. }
  13519. // Get the line number of the start of the visual line that the
  13520. // given line number is part of.
  13521. function visualLineNo(doc, lineN) {
  13522. var line = getLine(doc, lineN), vis = visualLine(line);
  13523. if (line == vis) { return lineN }
  13524. return lineNo(vis)
  13525. }
  13526. // Get the line number of the start of the next visual line after
  13527. // the given line.
  13528. function visualLineEndNo(doc, lineN) {
  13529. if (lineN > doc.lastLine()) { return lineN }
  13530. var line = getLine(doc, lineN), merged;
  13531. if (!lineIsHidden(doc, line)) { return lineN }
  13532. while (merged = collapsedSpanAtEnd(line))
  13533. { line = merged.find(1, true).line; }
  13534. return lineNo(line) + 1
  13535. }
  13536. // Compute whether a line is hidden. Lines count as hidden when they
  13537. // are part of a visual line that starts with another line, or when
  13538. // they are entirely covered by collapsed, non-widget span.
  13539. function lineIsHidden(doc, line) {
  13540. var sps = sawCollapsedSpans && line.markedSpans;
  13541. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  13542. sp = sps[i];
  13543. if (!sp.marker.collapsed) { continue }
  13544. if (sp.from == null) { return true }
  13545. if (sp.marker.widgetNode) { continue }
  13546. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  13547. { return true }
  13548. } }
  13549. }
  13550. function lineIsHiddenInner(doc, line, span) {
  13551. if (span.to == null) {
  13552. var end = span.marker.find(1, true);
  13553. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  13554. }
  13555. if (span.marker.inclusiveRight && span.to == line.text.length)
  13556. { return true }
  13557. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  13558. sp = line.markedSpans[i];
  13559. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  13560. (sp.to == null || sp.to != span.from) &&
  13561. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  13562. lineIsHiddenInner(doc, line, sp)) { return true }
  13563. }
  13564. }
  13565. // Find the height above the given line.
  13566. function heightAtLine(lineObj) {
  13567. lineObj = visualLine(lineObj);
  13568. var h = 0, chunk = lineObj.parent;
  13569. for (var i = 0; i < chunk.lines.length; ++i) {
  13570. var line = chunk.lines[i];
  13571. if (line == lineObj) { break }
  13572. else { h += line.height; }
  13573. }
  13574. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  13575. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  13576. var cur = p.children[i$1];
  13577. if (cur == chunk) { break }
  13578. else { h += cur.height; }
  13579. }
  13580. }
  13581. return h
  13582. }
  13583. // Compute the character length of a line, taking into account
  13584. // collapsed ranges (see markText) that might hide parts, and join
  13585. // other lines onto it.
  13586. function lineLength(line) {
  13587. if (line.height == 0) { return 0 }
  13588. var len = line.text.length, merged, cur = line;
  13589. while (merged = collapsedSpanAtStart(cur)) {
  13590. var found = merged.find(0, true);
  13591. cur = found.from.line;
  13592. len += found.from.ch - found.to.ch;
  13593. }
  13594. cur = line;
  13595. while (merged = collapsedSpanAtEnd(cur)) {
  13596. var found$1 = merged.find(0, true);
  13597. len -= cur.text.length - found$1.from.ch;
  13598. cur = found$1.to.line;
  13599. len += cur.text.length - found$1.to.ch;
  13600. }
  13601. return len
  13602. }
  13603. // Find the longest line in the document.
  13604. function findMaxLine(cm) {
  13605. var d = cm.display, doc = cm.doc;
  13606. d.maxLine = getLine(doc, doc.first);
  13607. d.maxLineLength = lineLength(d.maxLine);
  13608. d.maxLineChanged = true;
  13609. doc.iter(function (line) {
  13610. var len = lineLength(line);
  13611. if (len > d.maxLineLength) {
  13612. d.maxLineLength = len;
  13613. d.maxLine = line;
  13614. }
  13615. });
  13616. }
  13617. // LINE DATA STRUCTURE
  13618. // Line objects. These hold state related to a line, including
  13619. // highlighting info (the styles array).
  13620. var Line = function(text, markedSpans, estimateHeight) {
  13621. this.text = text;
  13622. attachMarkedSpans(this, markedSpans);
  13623. this.height = estimateHeight ? estimateHeight(this) : 1;
  13624. };
  13625. Line.prototype.lineNo = function () { return lineNo(this) };
  13626. eventMixin(Line);
  13627. // Change the content (text, markers) of a line. Automatically
  13628. // invalidates cached information and tries to re-estimate the
  13629. // line's height.
  13630. function updateLine(line, text, markedSpans, estimateHeight) {
  13631. line.text = text;
  13632. if (line.stateAfter) { line.stateAfter = null; }
  13633. if (line.styles) { line.styles = null; }
  13634. if (line.order != null) { line.order = null; }
  13635. detachMarkedSpans(line);
  13636. attachMarkedSpans(line, markedSpans);
  13637. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  13638. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  13639. }
  13640. // Detach a line from the document tree and its markers.
  13641. function cleanUpLine(line) {
  13642. line.parent = null;
  13643. detachMarkedSpans(line);
  13644. }
  13645. // Convert a style as returned by a mode (either null, or a string
  13646. // containing one or more styles) to a CSS style. This is cached,
  13647. // and also looks for line-wide styles.
  13648. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  13649. function interpretTokenStyle(style, options) {
  13650. if (!style || /^\s*$/.test(style)) { return null }
  13651. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  13652. return cache[style] ||
  13653. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  13654. }
  13655. // Render the DOM representation of the text of a line. Also builds
  13656. // up a 'line map', which points at the DOM nodes that represent
  13657. // specific stretches of text, and is used by the measuring code.
  13658. // The returned object contains the DOM node, this map, and
  13659. // information about line-wide styles that were set by the mode.
  13660. function buildLineContent(cm, lineView) {
  13661. // The padding-right forces the element to have a 'border', which
  13662. // is needed on Webkit to be able to get line-level bounding
  13663. // rectangles for it (in measureChar).
  13664. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  13665. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  13666. col: 0, pos: 0, cm: cm,
  13667. trailingSpace: false,
  13668. splitSpaces: cm.getOption("lineWrapping")};
  13669. lineView.measure = {};
  13670. // Iterate over the logical lines that make up this visual line.
  13671. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  13672. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  13673. builder.pos = 0;
  13674. builder.addToken = buildToken;
  13675. // Optionally wire in some hacks into the token-rendering
  13676. // algorithm, to deal with browser quirks.
  13677. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  13678. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  13679. builder.map = [];
  13680. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  13681. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  13682. if (line.styleClasses) {
  13683. if (line.styleClasses.bgClass)
  13684. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  13685. if (line.styleClasses.textClass)
  13686. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  13687. }
  13688. // Ensure at least a single node is present, for measuring.
  13689. if (builder.map.length == 0)
  13690. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  13691. // Store the map and a cache object for the current logical line
  13692. if (i == 0) {
  13693. lineView.measure.map = builder.map;
  13694. lineView.measure.cache = {};
  13695. } else {
  13696. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  13697. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  13698. }
  13699. }
  13700. // See issue #2901
  13701. if (webkit) {
  13702. var last = builder.content.lastChild;
  13703. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  13704. { builder.content.className = "cm-tab-wrap-hack"; }
  13705. }
  13706. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  13707. if (builder.pre.className)
  13708. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  13709. return builder
  13710. }
  13711. function defaultSpecialCharPlaceholder(ch) {
  13712. var token = elt("span", "\u2022", "cm-invalidchar");
  13713. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  13714. token.setAttribute("aria-label", token.title);
  13715. return token
  13716. }
  13717. // Build up the DOM representation for a single token, and add it to
  13718. // the line map. Takes care to render special characters separately.
  13719. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  13720. if (!text) { return }
  13721. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  13722. var special = builder.cm.state.specialChars, mustWrap = false;
  13723. var content;
  13724. if (!special.test(text)) {
  13725. builder.col += text.length;
  13726. content = document.createTextNode(displayText);
  13727. builder.map.push(builder.pos, builder.pos + text.length, content);
  13728. if (ie && ie_version < 9) { mustWrap = true; }
  13729. builder.pos += text.length;
  13730. } else {
  13731. content = document.createDocumentFragment();
  13732. var pos = 0;
  13733. while (true) {
  13734. special.lastIndex = pos;
  13735. var m = special.exec(text);
  13736. var skipped = m ? m.index - pos : text.length - pos;
  13737. if (skipped) {
  13738. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  13739. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  13740. else { content.appendChild(txt); }
  13741. builder.map.push(builder.pos, builder.pos + skipped, txt);
  13742. builder.col += skipped;
  13743. builder.pos += skipped;
  13744. }
  13745. if (!m) { break }
  13746. pos += skipped + 1;
  13747. var txt$1 = (void 0);
  13748. if (m[0] == "\t") {
  13749. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  13750. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  13751. txt$1.setAttribute("role", "presentation");
  13752. txt$1.setAttribute("cm-text", "\t");
  13753. builder.col += tabWidth;
  13754. } else if (m[0] == "\r" || m[0] == "\n") {
  13755. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  13756. txt$1.setAttribute("cm-text", m[0]);
  13757. builder.col += 1;
  13758. } else {
  13759. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  13760. txt$1.setAttribute("cm-text", m[0]);
  13761. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  13762. else { content.appendChild(txt$1); }
  13763. builder.col += 1;
  13764. }
  13765. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  13766. builder.pos++;
  13767. }
  13768. }
  13769. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  13770. if (style || startStyle || endStyle || mustWrap || css) {
  13771. var fullStyle = style || "";
  13772. if (startStyle) { fullStyle += startStyle; }
  13773. if (endStyle) { fullStyle += endStyle; }
  13774. var token = elt("span", [content], fullStyle, css);
  13775. if (attributes) {
  13776. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  13777. { token.setAttribute(attr, attributes[attr]); } }
  13778. }
  13779. return builder.content.appendChild(token)
  13780. }
  13781. builder.content.appendChild(content);
  13782. }
  13783. // Change some spaces to NBSP to prevent the browser from collapsing
  13784. // trailing spaces at the end of a line when rendering text (issue #1362).
  13785. function splitSpaces(text, trailingBefore) {
  13786. if (text.length > 1 && !/ /.test(text)) { return text }
  13787. var spaceBefore = trailingBefore, result = "";
  13788. for (var i = 0; i < text.length; i++) {
  13789. var ch = text.charAt(i);
  13790. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  13791. { ch = "\u00a0"; }
  13792. result += ch;
  13793. spaceBefore = ch == " ";
  13794. }
  13795. return result
  13796. }
  13797. // Work around nonsense dimensions being reported for stretches of
  13798. // right-to-left text.
  13799. function buildTokenBadBidi(inner, order) {
  13800. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  13801. style = style ? style + " cm-force-border" : "cm-force-border";
  13802. var start = builder.pos, end = start + text.length;
  13803. for (;;) {
  13804. // Find the part that overlaps with the start of this text
  13805. var part = (void 0);
  13806. for (var i = 0; i < order.length; i++) {
  13807. part = order[i];
  13808. if (part.to > start && part.from <= start) { break }
  13809. }
  13810. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  13811. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  13812. startStyle = null;
  13813. text = text.slice(part.to - start);
  13814. start = part.to;
  13815. }
  13816. }
  13817. }
  13818. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  13819. var widget = !ignoreWidget && marker.widgetNode;
  13820. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  13821. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  13822. if (!widget)
  13823. { widget = builder.content.appendChild(document.createElement("span")); }
  13824. widget.setAttribute("cm-marker", marker.id);
  13825. }
  13826. if (widget) {
  13827. builder.cm.display.input.setUneditable(widget);
  13828. builder.content.appendChild(widget);
  13829. }
  13830. builder.pos += size;
  13831. builder.trailingSpace = false;
  13832. }
  13833. // Outputs a number of spans to make up a line, taking highlighting
  13834. // and marked text into account.
  13835. function insertLineContent(line, builder, styles) {
  13836. var spans = line.markedSpans, allText = line.text, at = 0;
  13837. if (!spans) {
  13838. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  13839. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  13840. return
  13841. }
  13842. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  13843. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  13844. for (;;) {
  13845. if (nextChange == pos) { // Update current marker set
  13846. spanStyle = spanEndStyle = spanStartStyle = css = "";
  13847. attributes = null;
  13848. collapsed = null; nextChange = Infinity;
  13849. var foundBookmarks = [], endStyles = (void 0);
  13850. for (var j = 0; j < spans.length; ++j) {
  13851. var sp = spans[j], m = sp.marker;
  13852. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  13853. foundBookmarks.push(m);
  13854. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  13855. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  13856. nextChange = sp.to;
  13857. spanEndStyle = "";
  13858. }
  13859. if (m.className) { spanStyle += " " + m.className; }
  13860. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  13861. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  13862. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  13863. // support for the old title property
  13864. // https://github.com/codemirror/CodeMirror/pull/5673
  13865. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  13866. if (m.attributes) {
  13867. for (var attr in m.attributes)
  13868. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  13869. }
  13870. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  13871. { collapsed = sp; }
  13872. } else if (sp.from > pos && nextChange > sp.from) {
  13873. nextChange = sp.from;
  13874. }
  13875. }
  13876. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  13877. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  13878. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  13879. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  13880. if (collapsed && (collapsed.from || 0) == pos) {
  13881. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  13882. collapsed.marker, collapsed.from == null);
  13883. if (collapsed.to == null) { return }
  13884. if (collapsed.to == pos) { collapsed = false; }
  13885. }
  13886. }
  13887. if (pos >= len) { break }
  13888. var upto = Math.min(len, nextChange);
  13889. while (true) {
  13890. if (text) {
  13891. var end = pos + text.length;
  13892. if (!collapsed) {
  13893. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  13894. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  13895. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  13896. }
  13897. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  13898. pos = end;
  13899. spanStartStyle = "";
  13900. }
  13901. text = allText.slice(at, at = styles[i++]);
  13902. style = interpretTokenStyle(styles[i++], builder.cm.options);
  13903. }
  13904. }
  13905. }
  13906. // These objects are used to represent the visible (currently drawn)
  13907. // part of the document. A LineView may correspond to multiple
  13908. // logical lines, if those are connected by collapsed ranges.
  13909. function LineView(doc, line, lineN) {
  13910. // The starting line
  13911. this.line = line;
  13912. // Continuing lines, if any
  13913. this.rest = visualLineContinued(line);
  13914. // Number of logical lines in this visual line
  13915. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  13916. this.node = this.text = null;
  13917. this.hidden = lineIsHidden(doc, line);
  13918. }
  13919. // Create a range of LineView objects for the given lines.
  13920. function buildViewArray(cm, from, to) {
  13921. var array = [], nextPos;
  13922. for (var pos = from; pos < to; pos = nextPos) {
  13923. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  13924. nextPos = pos + view.size;
  13925. array.push(view);
  13926. }
  13927. return array
  13928. }
  13929. var operationGroup = null;
  13930. function pushOperation(op) {
  13931. if (operationGroup) {
  13932. operationGroup.ops.push(op);
  13933. } else {
  13934. op.ownsGroup = operationGroup = {
  13935. ops: [op],
  13936. delayedCallbacks: []
  13937. };
  13938. }
  13939. }
  13940. function fireCallbacksForOps(group) {
  13941. // Calls delayed callbacks and cursorActivity handlers until no
  13942. // new ones appear
  13943. var callbacks = group.delayedCallbacks, i = 0;
  13944. do {
  13945. for (; i < callbacks.length; i++)
  13946. { callbacks[i].call(null); }
  13947. for (var j = 0; j < group.ops.length; j++) {
  13948. var op = group.ops[j];
  13949. if (op.cursorActivityHandlers)
  13950. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  13951. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  13952. }
  13953. } while (i < callbacks.length)
  13954. }
  13955. function finishOperation(op, endCb) {
  13956. var group = op.ownsGroup;
  13957. if (!group) { return }
  13958. try { fireCallbacksForOps(group); }
  13959. finally {
  13960. operationGroup = null;
  13961. endCb(group);
  13962. }
  13963. }
  13964. var orphanDelayedCallbacks = null;
  13965. // Often, we want to signal events at a point where we are in the
  13966. // middle of some work, but don't want the handler to start calling
  13967. // other methods on the editor, which might be in an inconsistent
  13968. // state or simply not expect any other events to happen.
  13969. // signalLater looks whether there are any handlers, and schedules
  13970. // them to be executed when the last operation ends, or, if no
  13971. // operation is active, when a timeout fires.
  13972. function signalLater(emitter, type /*, values...*/) {
  13973. var arr = getHandlers(emitter, type);
  13974. if (!arr.length) { return }
  13975. var args = Array.prototype.slice.call(arguments, 2), list;
  13976. if (operationGroup) {
  13977. list = operationGroup.delayedCallbacks;
  13978. } else if (orphanDelayedCallbacks) {
  13979. list = orphanDelayedCallbacks;
  13980. } else {
  13981. list = orphanDelayedCallbacks = [];
  13982. setTimeout(fireOrphanDelayed, 0);
  13983. }
  13984. var loop = function ( i ) {
  13985. list.push(function () { return arr[i].apply(null, args); });
  13986. };
  13987. for (var i = 0; i < arr.length; ++i)
  13988. loop( i );
  13989. }
  13990. function fireOrphanDelayed() {
  13991. var delayed = orphanDelayedCallbacks;
  13992. orphanDelayedCallbacks = null;
  13993. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  13994. }
  13995. // When an aspect of a line changes, a string is added to
  13996. // lineView.changes. This updates the relevant part of the line's
  13997. // DOM structure.
  13998. function updateLineForChanges(cm, lineView, lineN, dims) {
  13999. for (var j = 0; j < lineView.changes.length; j++) {
  14000. var type = lineView.changes[j];
  14001. if (type == "text") { updateLineText(cm, lineView); }
  14002. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  14003. else if (type == "class") { updateLineClasses(cm, lineView); }
  14004. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  14005. }
  14006. lineView.changes = null;
  14007. }
  14008. // Lines with gutter elements, widgets or a background class need to
  14009. // be wrapped, and have the extra elements added to the wrapper div
  14010. function ensureLineWrapped(lineView) {
  14011. if (lineView.node == lineView.text) {
  14012. lineView.node = elt("div", null, null, "position: relative");
  14013. if (lineView.text.parentNode)
  14014. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  14015. lineView.node.appendChild(lineView.text);
  14016. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  14017. }
  14018. return lineView.node
  14019. }
  14020. function updateLineBackground(cm, lineView) {
  14021. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  14022. if (cls) { cls += " CodeMirror-linebackground"; }
  14023. if (lineView.background) {
  14024. if (cls) { lineView.background.className = cls; }
  14025. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  14026. } else if (cls) {
  14027. var wrap = ensureLineWrapped(lineView);
  14028. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  14029. cm.display.input.setUneditable(lineView.background);
  14030. }
  14031. }
  14032. // Wrapper around buildLineContent which will reuse the structure
  14033. // in display.externalMeasured when possible.
  14034. function getLineContent(cm, lineView) {
  14035. var ext = cm.display.externalMeasured;
  14036. if (ext && ext.line == lineView.line) {
  14037. cm.display.externalMeasured = null;
  14038. lineView.measure = ext.measure;
  14039. return ext.built
  14040. }
  14041. return buildLineContent(cm, lineView)
  14042. }
  14043. // Redraw the line's text. Interacts with the background and text
  14044. // classes because the mode may output tokens that influence these
  14045. // classes.
  14046. function updateLineText(cm, lineView) {
  14047. var cls = lineView.text.className;
  14048. var built = getLineContent(cm, lineView);
  14049. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  14050. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  14051. lineView.text = built.pre;
  14052. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  14053. lineView.bgClass = built.bgClass;
  14054. lineView.textClass = built.textClass;
  14055. updateLineClasses(cm, lineView);
  14056. } else if (cls) {
  14057. lineView.text.className = cls;
  14058. }
  14059. }
  14060. function updateLineClasses(cm, lineView) {
  14061. updateLineBackground(cm, lineView);
  14062. if (lineView.line.wrapClass)
  14063. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  14064. else if (lineView.node != lineView.text)
  14065. { lineView.node.className = ""; }
  14066. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  14067. lineView.text.className = textClass || "";
  14068. }
  14069. function updateLineGutter(cm, lineView, lineN, dims) {
  14070. if (lineView.gutter) {
  14071. lineView.node.removeChild(lineView.gutter);
  14072. lineView.gutter = null;
  14073. }
  14074. if (lineView.gutterBackground) {
  14075. lineView.node.removeChild(lineView.gutterBackground);
  14076. lineView.gutterBackground = null;
  14077. }
  14078. if (lineView.line.gutterClass) {
  14079. var wrap = ensureLineWrapped(lineView);
  14080. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  14081. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  14082. cm.display.input.setUneditable(lineView.gutterBackground);
  14083. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  14084. }
  14085. var markers = lineView.line.gutterMarkers;
  14086. if (cm.options.lineNumbers || markers) {
  14087. var wrap$1 = ensureLineWrapped(lineView);
  14088. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  14089. cm.display.input.setUneditable(gutterWrap);
  14090. wrap$1.insertBefore(gutterWrap, lineView.text);
  14091. if (lineView.line.gutterClass)
  14092. { gutterWrap.className += " " + lineView.line.gutterClass; }
  14093. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  14094. { lineView.lineNumber = gutterWrap.appendChild(
  14095. elt("div", lineNumberFor(cm.options, lineN),
  14096. "CodeMirror-linenumber CodeMirror-gutter-elt",
  14097. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  14098. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  14099. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  14100. if (found)
  14101. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  14102. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  14103. } }
  14104. }
  14105. }
  14106. function updateLineWidgets(cm, lineView, dims) {
  14107. if (lineView.alignable) { lineView.alignable = null; }
  14108. var isWidget = classTest("CodeMirror-linewidget");
  14109. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  14110. next = node.nextSibling;
  14111. if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  14112. }
  14113. insertLineWidgets(cm, lineView, dims);
  14114. }
  14115. // Build a line's DOM representation from scratch
  14116. function buildLineElement(cm, lineView, lineN, dims) {
  14117. var built = getLineContent(cm, lineView);
  14118. lineView.text = lineView.node = built.pre;
  14119. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  14120. if (built.textClass) { lineView.textClass = built.textClass; }
  14121. updateLineClasses(cm, lineView);
  14122. updateLineGutter(cm, lineView, lineN, dims);
  14123. insertLineWidgets(cm, lineView, dims);
  14124. return lineView.node
  14125. }
  14126. // A lineView may contain multiple logical lines (when merged by
  14127. // collapsed spans). The widgets for all of them need to be drawn.
  14128. function insertLineWidgets(cm, lineView, dims) {
  14129. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  14130. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  14131. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  14132. }
  14133. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  14134. if (!line.widgets) { return }
  14135. var wrap = ensureLineWrapped(lineView);
  14136. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  14137. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  14138. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  14139. positionLineWidget(widget, node, lineView, dims);
  14140. cm.display.input.setUneditable(node);
  14141. if (allowAbove && widget.above)
  14142. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  14143. else
  14144. { wrap.appendChild(node); }
  14145. signalLater(widget, "redraw");
  14146. }
  14147. }
  14148. function positionLineWidget(widget, node, lineView, dims) {
  14149. if (widget.noHScroll) {
  14150. (lineView.alignable || (lineView.alignable = [])).push(node);
  14151. var width = dims.wrapperWidth;
  14152. node.style.left = dims.fixedPos + "px";
  14153. if (!widget.coverGutter) {
  14154. width -= dims.gutterTotalWidth;
  14155. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  14156. }
  14157. node.style.width = width + "px";
  14158. }
  14159. if (widget.coverGutter) {
  14160. node.style.zIndex = 5;
  14161. node.style.position = "relative";
  14162. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  14163. }
  14164. }
  14165. function widgetHeight(widget) {
  14166. if (widget.height != null) { return widget.height }
  14167. var cm = widget.doc.cm;
  14168. if (!cm) { return 0 }
  14169. if (!contains(document.body, widget.node)) {
  14170. var parentStyle = "position: relative;";
  14171. if (widget.coverGutter)
  14172. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  14173. if (widget.noHScroll)
  14174. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  14175. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  14176. }
  14177. return widget.height = widget.node.parentNode.offsetHeight
  14178. }
  14179. // Return true when the given mouse event happened in a widget
  14180. function eventInWidget(display, e) {
  14181. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  14182. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  14183. (n.parentNode == display.sizer && n != display.mover))
  14184. { return true }
  14185. }
  14186. }
  14187. // POSITION MEASUREMENT
  14188. function paddingTop(display) {return display.lineSpace.offsetTop}
  14189. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  14190. function paddingH(display) {
  14191. if (display.cachedPaddingH) { return display.cachedPaddingH }
  14192. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  14193. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  14194. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  14195. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  14196. return data
  14197. }
  14198. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  14199. function displayWidth(cm) {
  14200. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  14201. }
  14202. function displayHeight(cm) {
  14203. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  14204. }
  14205. // Ensure the lineView.wrapping.heights array is populated. This is
  14206. // an array of bottom offsets for the lines that make up a drawn
  14207. // line. When lineWrapping is on, there might be more than one
  14208. // height.
  14209. function ensureLineHeights(cm, lineView, rect) {
  14210. var wrapping = cm.options.lineWrapping;
  14211. var curWidth = wrapping && displayWidth(cm);
  14212. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  14213. var heights = lineView.measure.heights = [];
  14214. if (wrapping) {
  14215. lineView.measure.width = curWidth;
  14216. var rects = lineView.text.firstChild.getClientRects();
  14217. for (var i = 0; i < rects.length - 1; i++) {
  14218. var cur = rects[i], next = rects[i + 1];
  14219. if (Math.abs(cur.bottom - next.bottom) > 2)
  14220. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  14221. }
  14222. }
  14223. heights.push(rect.bottom - rect.top);
  14224. }
  14225. }
  14226. // Find a line map (mapping character offsets to text nodes) and a
  14227. // measurement cache for the given line number. (A line view might
  14228. // contain multiple lines when collapsed ranges are present.)
  14229. function mapFromLineView(lineView, line, lineN) {
  14230. if (lineView.line == line)
  14231. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  14232. for (var i = 0; i < lineView.rest.length; i++)
  14233. { if (lineView.rest[i] == line)
  14234. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  14235. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  14236. { if (lineNo(lineView.rest[i$1]) > lineN)
  14237. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  14238. }
  14239. // Render a line into the hidden node display.externalMeasured. Used
  14240. // when measurement is needed for a line that's not in the viewport.
  14241. function updateExternalMeasurement(cm, line) {
  14242. line = visualLine(line);
  14243. var lineN = lineNo(line);
  14244. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  14245. view.lineN = lineN;
  14246. var built = view.built = buildLineContent(cm, view);
  14247. view.text = built.pre;
  14248. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  14249. return view
  14250. }
  14251. // Get a {top, bottom, left, right} box (in line-local coordinates)
  14252. // for a given character.
  14253. function measureChar(cm, line, ch, bias) {
  14254. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  14255. }
  14256. // Find a line view that corresponds to the given line number.
  14257. function findViewForLine(cm, lineN) {
  14258. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  14259. { return cm.display.view[findViewIndex(cm, lineN)] }
  14260. var ext = cm.display.externalMeasured;
  14261. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  14262. { return ext }
  14263. }
  14264. // Measurement can be split in two steps, the set-up work that
  14265. // applies to the whole line, and the measurement of the actual
  14266. // character. Functions like coordsChar, that need to do a lot of
  14267. // measurements in a row, can thus ensure that the set-up work is
  14268. // only done once.
  14269. function prepareMeasureForLine(cm, line) {
  14270. var lineN = lineNo(line);
  14271. var view = findViewForLine(cm, lineN);
  14272. if (view && !view.text) {
  14273. view = null;
  14274. } else if (view && view.changes) {
  14275. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  14276. cm.curOp.forceUpdate = true;
  14277. }
  14278. if (!view)
  14279. { view = updateExternalMeasurement(cm, line); }
  14280. var info = mapFromLineView(view, line, lineN);
  14281. return {
  14282. line: line, view: view, rect: null,
  14283. map: info.map, cache: info.cache, before: info.before,
  14284. hasHeights: false
  14285. }
  14286. }
  14287. // Given a prepared measurement object, measures the position of an
  14288. // actual character (or fetches it from the cache).
  14289. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  14290. if (prepared.before) { ch = -1; }
  14291. var key = ch + (bias || ""), found;
  14292. if (prepared.cache.hasOwnProperty(key)) {
  14293. found = prepared.cache[key];
  14294. } else {
  14295. if (!prepared.rect)
  14296. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  14297. if (!prepared.hasHeights) {
  14298. ensureLineHeights(cm, prepared.view, prepared.rect);
  14299. prepared.hasHeights = true;
  14300. }
  14301. found = measureCharInner(cm, prepared, ch, bias);
  14302. if (!found.bogus) { prepared.cache[key] = found; }
  14303. }
  14304. return {left: found.left, right: found.right,
  14305. top: varHeight ? found.rtop : found.top,
  14306. bottom: varHeight ? found.rbottom : found.bottom}
  14307. }
  14308. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  14309. function nodeAndOffsetInLineMap(map, ch, bias) {
  14310. var node, start, end, collapse, mStart, mEnd;
  14311. // First, search the line map for the text node corresponding to,
  14312. // or closest to, the target character.
  14313. for (var i = 0; i < map.length; i += 3) {
  14314. mStart = map[i];
  14315. mEnd = map[i + 1];
  14316. if (ch < mStart) {
  14317. start = 0; end = 1;
  14318. collapse = "left";
  14319. } else if (ch < mEnd) {
  14320. start = ch - mStart;
  14321. end = start + 1;
  14322. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  14323. end = mEnd - mStart;
  14324. start = end - 1;
  14325. if (ch >= mEnd) { collapse = "right"; }
  14326. }
  14327. if (start != null) {
  14328. node = map[i + 2];
  14329. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  14330. { collapse = bias; }
  14331. if (bias == "left" && start == 0)
  14332. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  14333. node = map[(i -= 3) + 2];
  14334. collapse = "left";
  14335. } }
  14336. if (bias == "right" && start == mEnd - mStart)
  14337. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  14338. node = map[(i += 3) + 2];
  14339. collapse = "right";
  14340. } }
  14341. break
  14342. }
  14343. }
  14344. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  14345. }
  14346. function getUsefulRect(rects, bias) {
  14347. var rect = nullRect;
  14348. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  14349. if ((rect = rects[i]).left != rect.right) { break }
  14350. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  14351. if ((rect = rects[i$1]).left != rect.right) { break }
  14352. } }
  14353. return rect
  14354. }
  14355. function measureCharInner(cm, prepared, ch, bias) {
  14356. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  14357. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  14358. var rect;
  14359. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  14360. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  14361. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  14362. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  14363. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  14364. { rect = node.parentNode.getBoundingClientRect(); }
  14365. else
  14366. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  14367. if (rect.left || rect.right || start == 0) { break }
  14368. end = start;
  14369. start = start - 1;
  14370. collapse = "right";
  14371. }
  14372. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  14373. } else { // If it is a widget, simply get the box for the whole widget.
  14374. if (start > 0) { collapse = bias = "right"; }
  14375. var rects;
  14376. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  14377. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  14378. else
  14379. { rect = node.getBoundingClientRect(); }
  14380. }
  14381. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  14382. var rSpan = node.parentNode.getClientRects()[0];
  14383. if (rSpan)
  14384. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  14385. else
  14386. { rect = nullRect; }
  14387. }
  14388. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  14389. var mid = (rtop + rbot) / 2;
  14390. var heights = prepared.view.measure.heights;
  14391. var i = 0;
  14392. for (; i < heights.length - 1; i++)
  14393. { if (mid < heights[i]) { break } }
  14394. var top = i ? heights[i - 1] : 0, bot = heights[i];
  14395. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  14396. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  14397. top: top, bottom: bot};
  14398. if (!rect.left && !rect.right) { result.bogus = true; }
  14399. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  14400. return result
  14401. }
  14402. // Work around problem with bounding client rects on ranges being
  14403. // returned incorrectly when zoomed on IE10 and below.
  14404. function maybeUpdateRectForZooming(measure, rect) {
  14405. if (!window.screen || screen.logicalXDPI == null ||
  14406. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  14407. { return rect }
  14408. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  14409. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  14410. return {left: rect.left * scaleX, right: rect.right * scaleX,
  14411. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  14412. }
  14413. function clearLineMeasurementCacheFor(lineView) {
  14414. if (lineView.measure) {
  14415. lineView.measure.cache = {};
  14416. lineView.measure.heights = null;
  14417. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  14418. { lineView.measure.caches[i] = {}; } }
  14419. }
  14420. }
  14421. function clearLineMeasurementCache(cm) {
  14422. cm.display.externalMeasure = null;
  14423. removeChildren(cm.display.lineMeasure);
  14424. for (var i = 0; i < cm.display.view.length; i++)
  14425. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  14426. }
  14427. function clearCaches(cm) {
  14428. clearLineMeasurementCache(cm);
  14429. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  14430. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  14431. cm.display.lineNumChars = null;
  14432. }
  14433. function pageScrollX() {
  14434. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  14435. // which causes page_Offset and bounding client rects to use
  14436. // different reference viewports and invalidate our calculations.
  14437. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  14438. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  14439. }
  14440. function pageScrollY() {
  14441. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  14442. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  14443. }
  14444. function widgetTopHeight(lineObj) {
  14445. var height = 0;
  14446. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  14447. { height += widgetHeight(lineObj.widgets[i]); } } }
  14448. return height
  14449. }
  14450. // Converts a {top, bottom, left, right} box from line-local
  14451. // coordinates into another coordinate system. Context may be one of
  14452. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  14453. // or "page".
  14454. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  14455. if (!includeWidgets) {
  14456. var height = widgetTopHeight(lineObj);
  14457. rect.top += height; rect.bottom += height;
  14458. }
  14459. if (context == "line") { return rect }
  14460. if (!context) { context = "local"; }
  14461. var yOff = heightAtLine(lineObj);
  14462. if (context == "local") { yOff += paddingTop(cm.display); }
  14463. else { yOff -= cm.display.viewOffset; }
  14464. if (context == "page" || context == "window") {
  14465. var lOff = cm.display.lineSpace.getBoundingClientRect();
  14466. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  14467. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  14468. rect.left += xOff; rect.right += xOff;
  14469. }
  14470. rect.top += yOff; rect.bottom += yOff;
  14471. return rect
  14472. }
  14473. // Coverts a box from "div" coords to another coordinate system.
  14474. // Context may be "window", "page", "div", or "local"./null.
  14475. function fromCoordSystem(cm, coords, context) {
  14476. if (context == "div") { return coords }
  14477. var left = coords.left, top = coords.top;
  14478. // First move into "page" coordinate system
  14479. if (context == "page") {
  14480. left -= pageScrollX();
  14481. top -= pageScrollY();
  14482. } else if (context == "local" || !context) {
  14483. var localBox = cm.display.sizer.getBoundingClientRect();
  14484. left += localBox.left;
  14485. top += localBox.top;
  14486. }
  14487. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  14488. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  14489. }
  14490. function charCoords(cm, pos, context, lineObj, bias) {
  14491. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  14492. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  14493. }
  14494. // Returns a box for a given cursor position, which may have an
  14495. // 'other' property containing the position of the secondary cursor
  14496. // on a bidi boundary.
  14497. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  14498. // and after `char - 1` in writing order of `char - 1`
  14499. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  14500. // and before `char` in writing order of `char`
  14501. // Examples (upper-case letters are RTL, lower-case are LTR):
  14502. // Pos(0, 1, ...)
  14503. // before after
  14504. // ab a|b a|b
  14505. // aB a|B aB|
  14506. // Ab |Ab A|b
  14507. // AB B|A B|A
  14508. // Every position after the last character on a line is considered to stick
  14509. // to the last character on the line.
  14510. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  14511. lineObj = lineObj || getLine(cm.doc, pos.line);
  14512. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  14513. function get(ch, right) {
  14514. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  14515. if (right) { m.left = m.right; } else { m.right = m.left; }
  14516. return intoCoordSystem(cm, lineObj, m, context)
  14517. }
  14518. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  14519. if (ch >= lineObj.text.length) {
  14520. ch = lineObj.text.length;
  14521. sticky = "before";
  14522. } else if (ch <= 0) {
  14523. ch = 0;
  14524. sticky = "after";
  14525. }
  14526. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  14527. function getBidi(ch, partPos, invert) {
  14528. var part = order[partPos], right = part.level == 1;
  14529. return get(invert ? ch - 1 : ch, right != invert)
  14530. }
  14531. var partPos = getBidiPartAt(order, ch, sticky);
  14532. var other = bidiOther;
  14533. var val = getBidi(ch, partPos, sticky == "before");
  14534. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  14535. return val
  14536. }
  14537. // Used to cheaply estimate the coordinates for a position. Used for
  14538. // intermediate scroll updates.
  14539. function estimateCoords(cm, pos) {
  14540. var left = 0;
  14541. pos = clipPos(cm.doc, pos);
  14542. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  14543. var lineObj = getLine(cm.doc, pos.line);
  14544. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  14545. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  14546. }
  14547. // Positions returned by coordsChar contain some extra information.
  14548. // xRel is the relative x position of the input coordinates compared
  14549. // to the found position (so xRel > 0 means the coordinates are to
  14550. // the right of the character position, for example). When outside
  14551. // is true, that means the coordinates lie outside the line's
  14552. // vertical range.
  14553. function PosWithInfo(line, ch, sticky, outside, xRel) {
  14554. var pos = Pos(line, ch, sticky);
  14555. pos.xRel = xRel;
  14556. if (outside) { pos.outside = outside; }
  14557. return pos
  14558. }
  14559. // Compute the character position closest to the given coordinates.
  14560. // Input must be lineSpace-local ("div" coordinate system).
  14561. function coordsChar(cm, x, y) {
  14562. var doc = cm.doc;
  14563. y += cm.display.viewOffset;
  14564. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  14565. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  14566. if (lineN > last)
  14567. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  14568. if (x < 0) { x = 0; }
  14569. var lineObj = getLine(doc, lineN);
  14570. for (;;) {
  14571. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  14572. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  14573. if (!collapsed) { return found }
  14574. var rangeEnd = collapsed.find(1);
  14575. if (rangeEnd.line == lineN) { return rangeEnd }
  14576. lineObj = getLine(doc, lineN = rangeEnd.line);
  14577. }
  14578. }
  14579. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  14580. y -= widgetTopHeight(lineObj);
  14581. var end = lineObj.text.length;
  14582. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  14583. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  14584. return {begin: begin, end: end}
  14585. }
  14586. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  14587. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  14588. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  14589. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  14590. }
  14591. // Returns true if the given side of a box is after the given
  14592. // coordinates, in top-to-bottom, left-to-right order.
  14593. function boxIsAfter(box, x, y, left) {
  14594. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  14595. }
  14596. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  14597. // Move y into line-local coordinate space
  14598. y -= heightAtLine(lineObj);
  14599. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  14600. // When directly calling `measureCharPrepared`, we have to adjust
  14601. // for the widgets at this line.
  14602. var widgetHeight = widgetTopHeight(lineObj);
  14603. var begin = 0, end = lineObj.text.length, ltr = true;
  14604. var order = getOrder(lineObj, cm.doc.direction);
  14605. // If the line isn't plain left-to-right text, first figure out
  14606. // which bidi section the coordinates fall into.
  14607. if (order) {
  14608. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  14609. (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  14610. ltr = part.level != 1;
  14611. // The awkward -1 offsets are needed because findFirst (called
  14612. // on these below) will treat its first bound as inclusive,
  14613. // second as exclusive, but we want to actually address the
  14614. // characters in the part's range
  14615. begin = ltr ? part.from : part.to - 1;
  14616. end = ltr ? part.to : part.from - 1;
  14617. }
  14618. // A binary search to find the first character whose bounding box
  14619. // starts after the coordinates. If we run across any whose box wrap
  14620. // the coordinates, store that.
  14621. var chAround = null, boxAround = null;
  14622. var ch = findFirst(function (ch) {
  14623. var box = measureCharPrepared(cm, preparedMeasure, ch);
  14624. box.top += widgetHeight; box.bottom += widgetHeight;
  14625. if (!boxIsAfter(box, x, y, false)) { return false }
  14626. if (box.top <= y && box.left <= x) {
  14627. chAround = ch;
  14628. boxAround = box;
  14629. }
  14630. return true
  14631. }, begin, end);
  14632. var baseX, sticky, outside = false;
  14633. // If a box around the coordinates was found, use that
  14634. if (boxAround) {
  14635. // Distinguish coordinates nearer to the left or right side of the box
  14636. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  14637. ch = chAround + (atStart ? 0 : 1);
  14638. sticky = atStart ? "after" : "before";
  14639. baseX = atLeft ? boxAround.left : boxAround.right;
  14640. } else {
  14641. // (Adjust for extended bound, if necessary.)
  14642. if (!ltr && (ch == end || ch == begin)) { ch++; }
  14643. // To determine which side to associate with, get the box to the
  14644. // left of the character and compare it's vertical position to the
  14645. // coordinates
  14646. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  14647. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  14648. "after" : "before";
  14649. // Now get accurate coordinates for this place, in order to get a
  14650. // base X position
  14651. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  14652. baseX = coords.left;
  14653. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  14654. }
  14655. ch = skipExtendingChars(lineObj.text, ch, 1);
  14656. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  14657. }
  14658. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  14659. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  14660. // situation, we can take this ordering to correspond to the visual
  14661. // ordering. This finds the first part whose end is after the given
  14662. // coordinates.
  14663. var index = findFirst(function (i) {
  14664. var part = order[i], ltr = part.level != 1;
  14665. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  14666. "line", lineObj, preparedMeasure), x, y, true)
  14667. }, 0, order.length - 1);
  14668. var part = order[index];
  14669. // If this isn't the first part, the part's start is also after
  14670. // the coordinates, and the coordinates aren't on the same line as
  14671. // that start, move one part back.
  14672. if (index > 0) {
  14673. var ltr = part.level != 1;
  14674. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  14675. "line", lineObj, preparedMeasure);
  14676. if (boxIsAfter(start, x, y, true) && start.top > y)
  14677. { part = order[index - 1]; }
  14678. }
  14679. return part
  14680. }
  14681. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  14682. // In a wrapped line, rtl text on wrapping boundaries can do things
  14683. // that don't correspond to the ordering in our `order` array at
  14684. // all, so a binary search doesn't work, and we want to return a
  14685. // part that only spans one line so that the binary search in
  14686. // coordsCharInner is safe. As such, we first find the extent of the
  14687. // wrapped line, and then do a flat search in which we discard any
  14688. // spans that aren't on the line.
  14689. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  14690. var begin = ref.begin;
  14691. var end = ref.end;
  14692. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  14693. var part = null, closestDist = null;
  14694. for (var i = 0; i < order.length; i++) {
  14695. var p = order[i];
  14696. if (p.from >= end || p.to <= begin) { continue }
  14697. var ltr = p.level != 1;
  14698. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  14699. // Weigh against spans ending before this, so that they are only
  14700. // picked if nothing ends after
  14701. var dist = endX < x ? x - endX + 1e9 : endX - x;
  14702. if (!part || closestDist > dist) {
  14703. part = p;
  14704. closestDist = dist;
  14705. }
  14706. }
  14707. if (!part) { part = order[order.length - 1]; }
  14708. // Clip the part to the wrapped line.
  14709. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  14710. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  14711. return part
  14712. }
  14713. var measureText;
  14714. // Compute the default text height.
  14715. function textHeight(display) {
  14716. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  14717. if (measureText == null) {
  14718. measureText = elt("pre", null, "CodeMirror-line-like");
  14719. // Measure a bunch of lines, for browsers that compute
  14720. // fractional heights.
  14721. for (var i = 0; i < 49; ++i) {
  14722. measureText.appendChild(document.createTextNode("x"));
  14723. measureText.appendChild(elt("br"));
  14724. }
  14725. measureText.appendChild(document.createTextNode("x"));
  14726. }
  14727. removeChildrenAndAdd(display.measure, measureText);
  14728. var height = measureText.offsetHeight / 50;
  14729. if (height > 3) { display.cachedTextHeight = height; }
  14730. removeChildren(display.measure);
  14731. return height || 1
  14732. }
  14733. // Compute the default character width.
  14734. function charWidth(display) {
  14735. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  14736. var anchor = elt("span", "xxxxxxxxxx");
  14737. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  14738. removeChildrenAndAdd(display.measure, pre);
  14739. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  14740. if (width > 2) { display.cachedCharWidth = width; }
  14741. return width || 10
  14742. }
  14743. // Do a bulk-read of the DOM positions and sizes needed to draw the
  14744. // view, so that we don't interleave reading and writing to the DOM.
  14745. function getDimensions(cm) {
  14746. var d = cm.display, left = {}, width = {};
  14747. var gutterLeft = d.gutters.clientLeft;
  14748. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  14749. var id = cm.display.gutterSpecs[i].className;
  14750. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  14751. width[id] = n.clientWidth;
  14752. }
  14753. return {fixedPos: compensateForHScroll(d),
  14754. gutterTotalWidth: d.gutters.offsetWidth,
  14755. gutterLeft: left,
  14756. gutterWidth: width,
  14757. wrapperWidth: d.wrapper.clientWidth}
  14758. }
  14759. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  14760. // but using getBoundingClientRect to get a sub-pixel-accurate
  14761. // result.
  14762. function compensateForHScroll(display) {
  14763. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  14764. }
  14765. // Returns a function that estimates the height of a line, to use as
  14766. // first approximation until the line becomes visible (and is thus
  14767. // properly measurable).
  14768. function estimateHeight(cm) {
  14769. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  14770. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  14771. return function (line) {
  14772. if (lineIsHidden(cm.doc, line)) { return 0 }
  14773. var widgetsHeight = 0;
  14774. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  14775. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  14776. } }
  14777. if (wrapping)
  14778. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  14779. else
  14780. { return widgetsHeight + th }
  14781. }
  14782. }
  14783. function estimateLineHeights(cm) {
  14784. var doc = cm.doc, est = estimateHeight(cm);
  14785. doc.iter(function (line) {
  14786. var estHeight = est(line);
  14787. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  14788. });
  14789. }
  14790. // Given a mouse event, find the corresponding position. If liberal
  14791. // is false, it checks whether a gutter or scrollbar was clicked,
  14792. // and returns null if it was. forRect is used by rectangular
  14793. // selections, and tries to estimate a character position even for
  14794. // coordinates beyond the right of the text.
  14795. function posFromMouse(cm, e, liberal, forRect) {
  14796. var display = cm.display;
  14797. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  14798. var x, y, space = display.lineSpace.getBoundingClientRect();
  14799. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  14800. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  14801. catch (e) { return null }
  14802. var coords = coordsChar(cm, x, y), line;
  14803. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  14804. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  14805. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  14806. }
  14807. return coords
  14808. }
  14809. // Find the view element corresponding to a given line. Return null
  14810. // when the line isn't visible.
  14811. function findViewIndex(cm, n) {
  14812. if (n >= cm.display.viewTo) { return null }
  14813. n -= cm.display.viewFrom;
  14814. if (n < 0) { return null }
  14815. var view = cm.display.view;
  14816. for (var i = 0; i < view.length; i++) {
  14817. n -= view[i].size;
  14818. if (n < 0) { return i }
  14819. }
  14820. }
  14821. // Updates the display.view data structure for a given change to the
  14822. // document. From and to are in pre-change coordinates. Lendiff is
  14823. // the amount of lines added or subtracted by the change. This is
  14824. // used for changes that span multiple lines, or change the way
  14825. // lines are divided into visual lines. regLineChange (below)
  14826. // registers single-line changes.
  14827. function regChange(cm, from, to, lendiff) {
  14828. if (from == null) { from = cm.doc.first; }
  14829. if (to == null) { to = cm.doc.first + cm.doc.size; }
  14830. if (!lendiff) { lendiff = 0; }
  14831. var display = cm.display;
  14832. if (lendiff && to < display.viewTo &&
  14833. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  14834. { display.updateLineNumbers = from; }
  14835. cm.curOp.viewChanged = true;
  14836. if (from >= display.viewTo) { // Change after
  14837. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  14838. { resetView(cm); }
  14839. } else if (to <= display.viewFrom) { // Change before
  14840. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  14841. resetView(cm);
  14842. } else {
  14843. display.viewFrom += lendiff;
  14844. display.viewTo += lendiff;
  14845. }
  14846. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  14847. resetView(cm);
  14848. } else if (from <= display.viewFrom) { // Top overlap
  14849. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  14850. if (cut) {
  14851. display.view = display.view.slice(cut.index);
  14852. display.viewFrom = cut.lineN;
  14853. display.viewTo += lendiff;
  14854. } else {
  14855. resetView(cm);
  14856. }
  14857. } else if (to >= display.viewTo) { // Bottom overlap
  14858. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  14859. if (cut$1) {
  14860. display.view = display.view.slice(0, cut$1.index);
  14861. display.viewTo = cut$1.lineN;
  14862. } else {
  14863. resetView(cm);
  14864. }
  14865. } else { // Gap in the middle
  14866. var cutTop = viewCuttingPoint(cm, from, from, -1);
  14867. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  14868. if (cutTop && cutBot) {
  14869. display.view = display.view.slice(0, cutTop.index)
  14870. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  14871. .concat(display.view.slice(cutBot.index));
  14872. display.viewTo += lendiff;
  14873. } else {
  14874. resetView(cm);
  14875. }
  14876. }
  14877. var ext = display.externalMeasured;
  14878. if (ext) {
  14879. if (to < ext.lineN)
  14880. { ext.lineN += lendiff; }
  14881. else if (from < ext.lineN + ext.size)
  14882. { display.externalMeasured = null; }
  14883. }
  14884. }
  14885. // Register a change to a single line. Type must be one of "text",
  14886. // "gutter", "class", "widget"
  14887. function regLineChange(cm, line, type) {
  14888. cm.curOp.viewChanged = true;
  14889. var display = cm.display, ext = cm.display.externalMeasured;
  14890. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  14891. { display.externalMeasured = null; }
  14892. if (line < display.viewFrom || line >= display.viewTo) { return }
  14893. var lineView = display.view[findViewIndex(cm, line)];
  14894. if (lineView.node == null) { return }
  14895. var arr = lineView.changes || (lineView.changes = []);
  14896. if (indexOf(arr, type) == -1) { arr.push(type); }
  14897. }
  14898. // Clear the view.
  14899. function resetView(cm) {
  14900. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  14901. cm.display.view = [];
  14902. cm.display.viewOffset = 0;
  14903. }
  14904. function viewCuttingPoint(cm, oldN, newN, dir) {
  14905. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  14906. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  14907. { return {index: index, lineN: newN} }
  14908. var n = cm.display.viewFrom;
  14909. for (var i = 0; i < index; i++)
  14910. { n += view[i].size; }
  14911. if (n != oldN) {
  14912. if (dir > 0) {
  14913. if (index == view.length - 1) { return null }
  14914. diff = (n + view[index].size) - oldN;
  14915. index++;
  14916. } else {
  14917. diff = n - oldN;
  14918. }
  14919. oldN += diff; newN += diff;
  14920. }
  14921. while (visualLineNo(cm.doc, newN) != newN) {
  14922. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  14923. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  14924. index += dir;
  14925. }
  14926. return {index: index, lineN: newN}
  14927. }
  14928. // Force the view to cover a given range, adding empty view element
  14929. // or clipping off existing ones as needed.
  14930. function adjustView(cm, from, to) {
  14931. var display = cm.display, view = display.view;
  14932. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  14933. display.view = buildViewArray(cm, from, to);
  14934. display.viewFrom = from;
  14935. } else {
  14936. if (display.viewFrom > from)
  14937. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  14938. else if (display.viewFrom < from)
  14939. { display.view = display.view.slice(findViewIndex(cm, from)); }
  14940. display.viewFrom = from;
  14941. if (display.viewTo < to)
  14942. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  14943. else if (display.viewTo > to)
  14944. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  14945. }
  14946. display.viewTo = to;
  14947. }
  14948. // Count the number of lines in the view whose DOM representation is
  14949. // out of date (or nonexistent).
  14950. function countDirtyView(cm) {
  14951. var view = cm.display.view, dirty = 0;
  14952. for (var i = 0; i < view.length; i++) {
  14953. var lineView = view[i];
  14954. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  14955. }
  14956. return dirty
  14957. }
  14958. function updateSelection(cm) {
  14959. cm.display.input.showSelection(cm.display.input.prepareSelection());
  14960. }
  14961. function prepareSelection(cm, primary) {
  14962. if ( primary === void 0 ) primary = true;
  14963. var doc = cm.doc, result = {};
  14964. var curFragment = result.cursors = document.createDocumentFragment();
  14965. var selFragment = result.selection = document.createDocumentFragment();
  14966. for (var i = 0; i < doc.sel.ranges.length; i++) {
  14967. if (!primary && i == doc.sel.primIndex) { continue }
  14968. var range = doc.sel.ranges[i];
  14969. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  14970. var collapsed = range.empty();
  14971. if (collapsed || cm.options.showCursorWhenSelecting)
  14972. { drawSelectionCursor(cm, range.head, curFragment); }
  14973. if (!collapsed)
  14974. { drawSelectionRange(cm, range, selFragment); }
  14975. }
  14976. return result
  14977. }
  14978. // Draws a cursor for the given range
  14979. function drawSelectionCursor(cm, head, output) {
  14980. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  14981. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  14982. cursor.style.left = pos.left + "px";
  14983. cursor.style.top = pos.top + "px";
  14984. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  14985. if (pos.other) {
  14986. // Secondary cursor, shown when on a 'jump' in bi-directional text
  14987. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  14988. otherCursor.style.display = "";
  14989. otherCursor.style.left = pos.other.left + "px";
  14990. otherCursor.style.top = pos.other.top + "px";
  14991. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  14992. }
  14993. }
  14994. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  14995. // Draws the given range as a highlighted selection
  14996. function drawSelectionRange(cm, range, output) {
  14997. var display = cm.display, doc = cm.doc;
  14998. var fragment = document.createDocumentFragment();
  14999. var padding = paddingH(cm.display), leftSide = padding.left;
  15000. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  15001. var docLTR = doc.direction == "ltr";
  15002. function add(left, top, width, bottom) {
  15003. if (top < 0) { top = 0; }
  15004. top = Math.round(top);
  15005. bottom = Math.round(bottom);
  15006. 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")));
  15007. }
  15008. function drawForLine(line, fromArg, toArg) {
  15009. var lineObj = getLine(doc, line);
  15010. var lineLen = lineObj.text.length;
  15011. var start, end;
  15012. function coords(ch, bias) {
  15013. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  15014. }
  15015. function wrapX(pos, dir, side) {
  15016. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  15017. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  15018. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  15019. return coords(ch, prop)[prop]
  15020. }
  15021. var order = getOrder(lineObj, doc.direction);
  15022. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  15023. var ltr = dir == "ltr";
  15024. var fromPos = coords(from, ltr ? "left" : "right");
  15025. var toPos = coords(to - 1, ltr ? "right" : "left");
  15026. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  15027. var first = i == 0, last = !order || i == order.length - 1;
  15028. if (toPos.top - fromPos.top <= 3) { // Single line
  15029. var openLeft = (docLTR ? openStart : openEnd) && first;
  15030. var openRight = (docLTR ? openEnd : openStart) && last;
  15031. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  15032. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  15033. add(left, fromPos.top, right - left, fromPos.bottom);
  15034. } else { // Multiple lines
  15035. var topLeft, topRight, botLeft, botRight;
  15036. if (ltr) {
  15037. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  15038. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  15039. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  15040. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  15041. } else {
  15042. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  15043. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  15044. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  15045. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  15046. }
  15047. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  15048. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  15049. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  15050. }
  15051. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  15052. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  15053. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  15054. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  15055. });
  15056. return {start: start, end: end}
  15057. }
  15058. var sFrom = range.from(), sTo = range.to();
  15059. if (sFrom.line == sTo.line) {
  15060. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  15061. } else {
  15062. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  15063. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  15064. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  15065. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  15066. if (singleVLine) {
  15067. if (leftEnd.top < rightStart.top - 2) {
  15068. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  15069. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  15070. } else {
  15071. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  15072. }
  15073. }
  15074. if (leftEnd.bottom < rightStart.top)
  15075. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  15076. }
  15077. output.appendChild(fragment);
  15078. }
  15079. // Cursor-blinking
  15080. function restartBlink(cm) {
  15081. if (!cm.state.focused) { return }
  15082. var display = cm.display;
  15083. clearInterval(display.blinker);
  15084. var on = true;
  15085. display.cursorDiv.style.visibility = "";
  15086. if (cm.options.cursorBlinkRate > 0)
  15087. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  15088. cm.options.cursorBlinkRate); }
  15089. else if (cm.options.cursorBlinkRate < 0)
  15090. { display.cursorDiv.style.visibility = "hidden"; }
  15091. }
  15092. function ensureFocus(cm) {
  15093. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  15094. }
  15095. function delayBlurEvent(cm) {
  15096. cm.state.delayingBlurEvent = true;
  15097. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  15098. cm.state.delayingBlurEvent = false;
  15099. onBlur(cm);
  15100. } }, 100);
  15101. }
  15102. function onFocus(cm, e) {
  15103. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  15104. if (cm.options.readOnly == "nocursor") { return }
  15105. if (!cm.state.focused) {
  15106. signal(cm, "focus", cm, e);
  15107. cm.state.focused = true;
  15108. addClass(cm.display.wrapper, "CodeMirror-focused");
  15109. // This test prevents this from firing when a context
  15110. // menu is closed (since the input reset would kill the
  15111. // select-all detection hack)
  15112. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  15113. cm.display.input.reset();
  15114. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  15115. }
  15116. cm.display.input.receivedFocus();
  15117. }
  15118. restartBlink(cm);
  15119. }
  15120. function onBlur(cm, e) {
  15121. if (cm.state.delayingBlurEvent) { return }
  15122. if (cm.state.focused) {
  15123. signal(cm, "blur", cm, e);
  15124. cm.state.focused = false;
  15125. rmClass(cm.display.wrapper, "CodeMirror-focused");
  15126. }
  15127. clearInterval(cm.display.blinker);
  15128. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  15129. }
  15130. // Read the actual heights of the rendered lines, and update their
  15131. // stored heights to match.
  15132. function updateHeightsInViewport(cm) {
  15133. var display = cm.display;
  15134. var prevBottom = display.lineDiv.offsetTop;
  15135. for (var i = 0; i < display.view.length; i++) {
  15136. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  15137. var height = (void 0), width = 0;
  15138. if (cur.hidden) { continue }
  15139. if (ie && ie_version < 8) {
  15140. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  15141. height = bot - prevBottom;
  15142. prevBottom = bot;
  15143. } else {
  15144. var box = cur.node.getBoundingClientRect();
  15145. height = box.bottom - box.top;
  15146. // Check that lines don't extend past the right of the current
  15147. // editor width
  15148. if (!wrapping && cur.text.firstChild)
  15149. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  15150. }
  15151. var diff = cur.line.height - height;
  15152. if (diff > .005 || diff < -.005) {
  15153. updateLineHeight(cur.line, height);
  15154. updateWidgetHeight(cur.line);
  15155. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  15156. { updateWidgetHeight(cur.rest[j]); } }
  15157. }
  15158. if (width > cm.display.sizerWidth) {
  15159. var chWidth = Math.ceil(width / charWidth(cm.display));
  15160. if (chWidth > cm.display.maxLineLength) {
  15161. cm.display.maxLineLength = chWidth;
  15162. cm.display.maxLine = cur.line;
  15163. cm.display.maxLineChanged = true;
  15164. }
  15165. }
  15166. }
  15167. }
  15168. // Read and store the height of line widgets associated with the
  15169. // given line.
  15170. function updateWidgetHeight(line) {
  15171. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  15172. var w = line.widgets[i], parent = w.node.parentNode;
  15173. if (parent) { w.height = parent.offsetHeight; }
  15174. } }
  15175. }
  15176. // Compute the lines that are visible in a given viewport (defaults
  15177. // the the current scroll position). viewport may contain top,
  15178. // height, and ensure (see op.scrollToPos) properties.
  15179. function visibleLines(display, doc, viewport) {
  15180. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  15181. top = Math.floor(top - paddingTop(display));
  15182. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  15183. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  15184. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  15185. // forces those lines into the viewport (if possible).
  15186. if (viewport && viewport.ensure) {
  15187. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  15188. if (ensureFrom < from) {
  15189. from = ensureFrom;
  15190. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  15191. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  15192. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  15193. to = ensureTo;
  15194. }
  15195. }
  15196. return {from: from, to: Math.max(to, from + 1)}
  15197. }
  15198. // SCROLLING THINGS INTO VIEW
  15199. // If an editor sits on the top or bottom of the window, partially
  15200. // scrolled out of view, this ensures that the cursor is visible.
  15201. function maybeScrollWindow(cm, rect) {
  15202. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  15203. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  15204. if (rect.top + box.top < 0) { doScroll = true; }
  15205. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  15206. if (doScroll != null && !phantom) {
  15207. 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;"));
  15208. cm.display.lineSpace.appendChild(scrollNode);
  15209. scrollNode.scrollIntoView(doScroll);
  15210. cm.display.lineSpace.removeChild(scrollNode);
  15211. }
  15212. }
  15213. // Scroll a given position into view (immediately), verifying that
  15214. // it actually became visible (as line heights are accurately
  15215. // measured, the position of something may 'drift' during drawing).
  15216. function scrollPosIntoView(cm, pos, end, margin) {
  15217. if (margin == null) { margin = 0; }
  15218. var rect;
  15219. if (!cm.options.lineWrapping && pos == end) {
  15220. // Set pos and end to the cursor positions around the character pos sticks to
  15221. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  15222. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  15223. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  15224. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  15225. }
  15226. for (var limit = 0; limit < 5; limit++) {
  15227. var changed = false;
  15228. var coords = cursorCoords(cm, pos);
  15229. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  15230. rect = {left: Math.min(coords.left, endCoords.left),
  15231. top: Math.min(coords.top, endCoords.top) - margin,
  15232. right: Math.max(coords.left, endCoords.left),
  15233. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  15234. var scrollPos = calculateScrollPos(cm, rect);
  15235. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  15236. if (scrollPos.scrollTop != null) {
  15237. updateScrollTop(cm, scrollPos.scrollTop);
  15238. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  15239. }
  15240. if (scrollPos.scrollLeft != null) {
  15241. setScrollLeft(cm, scrollPos.scrollLeft);
  15242. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  15243. }
  15244. if (!changed) { break }
  15245. }
  15246. return rect
  15247. }
  15248. // Scroll a given set of coordinates into view (immediately).
  15249. function scrollIntoView(cm, rect) {
  15250. var scrollPos = calculateScrollPos(cm, rect);
  15251. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  15252. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  15253. }
  15254. // Calculate a new scroll position needed to scroll the given
  15255. // rectangle into view. Returns an object with scrollTop and
  15256. // scrollLeft properties. When these are undefined, the
  15257. // vertical/horizontal position does not need to be adjusted.
  15258. function calculateScrollPos(cm, rect) {
  15259. var display = cm.display, snapMargin = textHeight(cm.display);
  15260. if (rect.top < 0) { rect.top = 0; }
  15261. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  15262. var screen = displayHeight(cm), result = {};
  15263. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  15264. var docBottom = cm.doc.height + paddingVert(display);
  15265. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  15266. if (rect.top < screentop) {
  15267. result.scrollTop = atTop ? 0 : rect.top;
  15268. } else if (rect.bottom > screentop + screen) {
  15269. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  15270. if (newTop != screentop) { result.scrollTop = newTop; }
  15271. }
  15272. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  15273. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  15274. var tooWide = rect.right - rect.left > screenw;
  15275. if (tooWide) { rect.right = rect.left + screenw; }
  15276. if (rect.left < 10)
  15277. { result.scrollLeft = 0; }
  15278. else if (rect.left < screenleft)
  15279. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  15280. else if (rect.right > screenw + screenleft - 3)
  15281. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  15282. return result
  15283. }
  15284. // Store a relative adjustment to the scroll position in the current
  15285. // operation (to be applied when the operation finishes).
  15286. function addToScrollTop(cm, top) {
  15287. if (top == null) { return }
  15288. resolveScrollToPos(cm);
  15289. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  15290. }
  15291. // Make sure that at the end of the operation the current cursor is
  15292. // shown.
  15293. function ensureCursorVisible(cm) {
  15294. resolveScrollToPos(cm);
  15295. var cur = cm.getCursor();
  15296. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  15297. }
  15298. function scrollToCoords(cm, x, y) {
  15299. if (x != null || y != null) { resolveScrollToPos(cm); }
  15300. if (x != null) { cm.curOp.scrollLeft = x; }
  15301. if (y != null) { cm.curOp.scrollTop = y; }
  15302. }
  15303. function scrollToRange(cm, range) {
  15304. resolveScrollToPos(cm);
  15305. cm.curOp.scrollToPos = range;
  15306. }
  15307. // When an operation has its scrollToPos property set, and another
  15308. // scroll action is applied before the end of the operation, this
  15309. // 'simulates' scrolling that position into view in a cheap way, so
  15310. // that the effect of intermediate scroll commands is not ignored.
  15311. function resolveScrollToPos(cm) {
  15312. var range = cm.curOp.scrollToPos;
  15313. if (range) {
  15314. cm.curOp.scrollToPos = null;
  15315. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  15316. scrollToCoordsRange(cm, from, to, range.margin);
  15317. }
  15318. }
  15319. function scrollToCoordsRange(cm, from, to, margin) {
  15320. var sPos = calculateScrollPos(cm, {
  15321. left: Math.min(from.left, to.left),
  15322. top: Math.min(from.top, to.top) - margin,
  15323. right: Math.max(from.right, to.right),
  15324. bottom: Math.max(from.bottom, to.bottom) + margin
  15325. });
  15326. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  15327. }
  15328. // Sync the scrollable area and scrollbars, ensure the viewport
  15329. // covers the visible area.
  15330. function updateScrollTop(cm, val) {
  15331. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  15332. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  15333. setScrollTop(cm, val, true);
  15334. if (gecko) { updateDisplaySimple(cm); }
  15335. startWorker(cm, 100);
  15336. }
  15337. function setScrollTop(cm, val, forceScroll) {
  15338. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  15339. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  15340. cm.doc.scrollTop = val;
  15341. cm.display.scrollbars.setScrollTop(val);
  15342. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  15343. }
  15344. // Sync scroller and scrollbar, ensure the gutter elements are
  15345. // aligned.
  15346. function setScrollLeft(cm, val, isScroller, forceScroll) {
  15347. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  15348. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  15349. cm.doc.scrollLeft = val;
  15350. alignHorizontally(cm);
  15351. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  15352. cm.display.scrollbars.setScrollLeft(val);
  15353. }
  15354. // SCROLLBARS
  15355. // Prepare DOM reads needed to update the scrollbars. Done in one
  15356. // shot to minimize update/measure roundtrips.
  15357. function measureForScrollbars(cm) {
  15358. var d = cm.display, gutterW = d.gutters.offsetWidth;
  15359. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  15360. return {
  15361. clientHeight: d.scroller.clientHeight,
  15362. viewHeight: d.wrapper.clientHeight,
  15363. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  15364. viewWidth: d.wrapper.clientWidth,
  15365. barLeft: cm.options.fixedGutter ? gutterW : 0,
  15366. docHeight: docH,
  15367. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  15368. nativeBarWidth: d.nativeBarWidth,
  15369. gutterWidth: gutterW
  15370. }
  15371. }
  15372. var NativeScrollbars = function(place, scroll, cm) {
  15373. this.cm = cm;
  15374. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  15375. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  15376. vert.tabIndex = horiz.tabIndex = -1;
  15377. place(vert); place(horiz);
  15378. on(vert, "scroll", function () {
  15379. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  15380. });
  15381. on(horiz, "scroll", function () {
  15382. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  15383. });
  15384. this.checkedZeroWidth = false;
  15385. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  15386. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  15387. };
  15388. NativeScrollbars.prototype.update = function (measure) {
  15389. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  15390. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  15391. var sWidth = measure.nativeBarWidth;
  15392. if (needsV) {
  15393. this.vert.style.display = "block";
  15394. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  15395. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  15396. // A bug in IE8 can cause this value to be negative, so guard it.
  15397. this.vert.firstChild.style.height =
  15398. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  15399. } else {
  15400. this.vert.style.display = "";
  15401. this.vert.firstChild.style.height = "0";
  15402. }
  15403. if (needsH) {
  15404. this.horiz.style.display = "block";
  15405. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  15406. this.horiz.style.left = measure.barLeft + "px";
  15407. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  15408. this.horiz.firstChild.style.width =
  15409. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  15410. } else {
  15411. this.horiz.style.display = "";
  15412. this.horiz.firstChild.style.width = "0";
  15413. }
  15414. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  15415. if (sWidth == 0) { this.zeroWidthHack(); }
  15416. this.checkedZeroWidth = true;
  15417. }
  15418. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  15419. };
  15420. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  15421. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  15422. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  15423. };
  15424. NativeScrollbars.prototype.setScrollTop = function (pos) {
  15425. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  15426. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  15427. };
  15428. NativeScrollbars.prototype.zeroWidthHack = function () {
  15429. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  15430. this.horiz.style.height = this.vert.style.width = w;
  15431. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  15432. this.disableHoriz = new Delayed;
  15433. this.disableVert = new Delayed;
  15434. };
  15435. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  15436. bar.style.pointerEvents = "auto";
  15437. function maybeDisable() {
  15438. // To find out whether the scrollbar is still visible, we
  15439. // check whether the element under the pixel in the bottom
  15440. // right corner of the scrollbar box is the scrollbar box
  15441. // itself (when the bar is still visible) or its filler child
  15442. // (when the bar is hidden). If it is still visible, we keep
  15443. // it enabled, if it's hidden, we disable pointer events.
  15444. var box = bar.getBoundingClientRect();
  15445. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  15446. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  15447. if (elt != bar) { bar.style.pointerEvents = "none"; }
  15448. else { delay.set(1000, maybeDisable); }
  15449. }
  15450. delay.set(1000, maybeDisable);
  15451. };
  15452. NativeScrollbars.prototype.clear = function () {
  15453. var parent = this.horiz.parentNode;
  15454. parent.removeChild(this.horiz);
  15455. parent.removeChild(this.vert);
  15456. };
  15457. var NullScrollbars = function () {};
  15458. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  15459. NullScrollbars.prototype.setScrollLeft = function () {};
  15460. NullScrollbars.prototype.setScrollTop = function () {};
  15461. NullScrollbars.prototype.clear = function () {};
  15462. function updateScrollbars(cm, measure) {
  15463. if (!measure) { measure = measureForScrollbars(cm); }
  15464. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  15465. updateScrollbarsInner(cm, measure);
  15466. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  15467. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  15468. { updateHeightsInViewport(cm); }
  15469. updateScrollbarsInner(cm, measureForScrollbars(cm));
  15470. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  15471. }
  15472. }
  15473. // Re-synchronize the fake scrollbars with the actual size of the
  15474. // content.
  15475. function updateScrollbarsInner(cm, measure) {
  15476. var d = cm.display;
  15477. var sizes = d.scrollbars.update(measure);
  15478. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  15479. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  15480. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  15481. if (sizes.right && sizes.bottom) {
  15482. d.scrollbarFiller.style.display = "block";
  15483. d.scrollbarFiller.style.height = sizes.bottom + "px";
  15484. d.scrollbarFiller.style.width = sizes.right + "px";
  15485. } else { d.scrollbarFiller.style.display = ""; }
  15486. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  15487. d.gutterFiller.style.display = "block";
  15488. d.gutterFiller.style.height = sizes.bottom + "px";
  15489. d.gutterFiller.style.width = measure.gutterWidth + "px";
  15490. } else { d.gutterFiller.style.display = ""; }
  15491. }
  15492. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  15493. function initScrollbars(cm) {
  15494. if (cm.display.scrollbars) {
  15495. cm.display.scrollbars.clear();
  15496. if (cm.display.scrollbars.addClass)
  15497. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  15498. }
  15499. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  15500. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  15501. // Prevent clicks in the scrollbars from killing focus
  15502. on(node, "mousedown", function () {
  15503. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  15504. });
  15505. node.setAttribute("cm-not-content", "true");
  15506. }, function (pos, axis) {
  15507. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  15508. else { updateScrollTop(cm, pos); }
  15509. }, cm);
  15510. if (cm.display.scrollbars.addClass)
  15511. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  15512. }
  15513. // Operations are used to wrap a series of changes to the editor
  15514. // state in such a way that each change won't have to update the
  15515. // cursor and display (which would be awkward, slow, and
  15516. // error-prone). Instead, display updates are batched and then all
  15517. // combined and executed at once.
  15518. var nextOpId = 0;
  15519. // Start a new operation.
  15520. function startOperation(cm) {
  15521. cm.curOp = {
  15522. cm: cm,
  15523. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  15524. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  15525. forceUpdate: false, // Used to force a redraw
  15526. updateInput: 0, // Whether to reset the input textarea
  15527. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  15528. changeObjs: null, // Accumulated changes, for firing change events
  15529. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  15530. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  15531. selectionChanged: false, // Whether the selection needs to be redrawn
  15532. updateMaxLine: false, // Set when the widest line needs to be determined anew
  15533. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  15534. scrollToPos: null, // Used to scroll to a specific position
  15535. focus: false,
  15536. id: ++nextOpId // Unique ID
  15537. };
  15538. pushOperation(cm.curOp);
  15539. }
  15540. // Finish an operation, updating the display and signalling delayed events
  15541. function endOperation(cm) {
  15542. var op = cm.curOp;
  15543. if (op) { finishOperation(op, function (group) {
  15544. for (var i = 0; i < group.ops.length; i++)
  15545. { group.ops[i].cm.curOp = null; }
  15546. endOperations(group);
  15547. }); }
  15548. }
  15549. // The DOM updates done when an operation finishes are batched so
  15550. // that the minimum number of relayouts are required.
  15551. function endOperations(group) {
  15552. var ops = group.ops;
  15553. for (var i = 0; i < ops.length; i++) // Read DOM
  15554. { endOperation_R1(ops[i]); }
  15555. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  15556. { endOperation_W1(ops[i$1]); }
  15557. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  15558. { endOperation_R2(ops[i$2]); }
  15559. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  15560. { endOperation_W2(ops[i$3]); }
  15561. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  15562. { endOperation_finish(ops[i$4]); }
  15563. }
  15564. function endOperation_R1(op) {
  15565. var cm = op.cm, display = cm.display;
  15566. maybeClipScrollbars(cm);
  15567. if (op.updateMaxLine) { findMaxLine(cm); }
  15568. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  15569. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  15570. op.scrollToPos.to.line >= display.viewTo) ||
  15571. display.maxLineChanged && cm.options.lineWrapping;
  15572. op.update = op.mustUpdate &&
  15573. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  15574. }
  15575. function endOperation_W1(op) {
  15576. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  15577. }
  15578. function endOperation_R2(op) {
  15579. var cm = op.cm, display = cm.display;
  15580. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  15581. op.barMeasure = measureForScrollbars(cm);
  15582. // If the max line changed since it was last measured, measure it,
  15583. // and ensure the document's width matches it.
  15584. // updateDisplay_W2 will use these properties to do the actual resizing
  15585. if (display.maxLineChanged && !cm.options.lineWrapping) {
  15586. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  15587. cm.display.sizerWidth = op.adjustWidthTo;
  15588. op.barMeasure.scrollWidth =
  15589. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  15590. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  15591. }
  15592. if (op.updatedDisplay || op.selectionChanged)
  15593. { op.preparedSelection = display.input.prepareSelection(); }
  15594. }
  15595. function endOperation_W2(op) {
  15596. var cm = op.cm;
  15597. if (op.adjustWidthTo != null) {
  15598. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  15599. if (op.maxScrollLeft < cm.doc.scrollLeft)
  15600. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  15601. cm.display.maxLineChanged = false;
  15602. }
  15603. var takeFocus = op.focus && op.focus == activeElt();
  15604. if (op.preparedSelection)
  15605. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  15606. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  15607. { updateScrollbars(cm, op.barMeasure); }
  15608. if (op.updatedDisplay)
  15609. { setDocumentHeight(cm, op.barMeasure); }
  15610. if (op.selectionChanged) { restartBlink(cm); }
  15611. if (cm.state.focused && op.updateInput)
  15612. { cm.display.input.reset(op.typing); }
  15613. if (takeFocus) { ensureFocus(op.cm); }
  15614. }
  15615. function endOperation_finish(op) {
  15616. var cm = op.cm, display = cm.display, doc = cm.doc;
  15617. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  15618. // Abort mouse wheel delta measurement, when scrolling explicitly
  15619. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  15620. { display.wheelStartX = display.wheelStartY = null; }
  15621. // Propagate the scroll position to the actual DOM scroller
  15622. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  15623. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  15624. // If we need to scroll a specific position into view, do so.
  15625. if (op.scrollToPos) {
  15626. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  15627. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  15628. maybeScrollWindow(cm, rect);
  15629. }
  15630. // Fire events for markers that are hidden/unidden by editing or
  15631. // undoing
  15632. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  15633. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  15634. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  15635. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  15636. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  15637. if (display.wrapper.offsetHeight)
  15638. { doc.scrollTop = cm.display.scroller.scrollTop; }
  15639. // Fire change events, and delayed event handlers
  15640. if (op.changeObjs)
  15641. { signal(cm, "changes", cm, op.changeObjs); }
  15642. if (op.update)
  15643. { op.update.finish(); }
  15644. }
  15645. // Run the given function in an operation
  15646. function runInOp(cm, f) {
  15647. if (cm.curOp) { return f() }
  15648. startOperation(cm);
  15649. try { return f() }
  15650. finally { endOperation(cm); }
  15651. }
  15652. // Wraps a function in an operation. Returns the wrapped function.
  15653. function operation(cm, f) {
  15654. return function() {
  15655. if (cm.curOp) { return f.apply(cm, arguments) }
  15656. startOperation(cm);
  15657. try { return f.apply(cm, arguments) }
  15658. finally { endOperation(cm); }
  15659. }
  15660. }
  15661. // Used to add methods to editor and doc instances, wrapping them in
  15662. // operations.
  15663. function methodOp(f) {
  15664. return function() {
  15665. if (this.curOp) { return f.apply(this, arguments) }
  15666. startOperation(this);
  15667. try { return f.apply(this, arguments) }
  15668. finally { endOperation(this); }
  15669. }
  15670. }
  15671. function docMethodOp(f) {
  15672. return function() {
  15673. var cm = this.cm;
  15674. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  15675. startOperation(cm);
  15676. try { return f.apply(this, arguments) }
  15677. finally { endOperation(cm); }
  15678. }
  15679. }
  15680. // HIGHLIGHT WORKER
  15681. function startWorker(cm, time) {
  15682. if (cm.doc.highlightFrontier < cm.display.viewTo)
  15683. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  15684. }
  15685. function highlightWorker(cm) {
  15686. var doc = cm.doc;
  15687. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  15688. var end = +new Date + cm.options.workTime;
  15689. var context = getContextBefore(cm, doc.highlightFrontier);
  15690. var changedLines = [];
  15691. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  15692. if (context.line >= cm.display.viewFrom) { // Visible
  15693. var oldStyles = line.styles;
  15694. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  15695. var highlighted = highlightLine(cm, line, context, true);
  15696. if (resetState) { context.state = resetState; }
  15697. line.styles = highlighted.styles;
  15698. var oldCls = line.styleClasses, newCls = highlighted.classes;
  15699. if (newCls) { line.styleClasses = newCls; }
  15700. else if (oldCls) { line.styleClasses = null; }
  15701. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  15702. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  15703. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  15704. if (ischange) { changedLines.push(context.line); }
  15705. line.stateAfter = context.save();
  15706. context.nextLine();
  15707. } else {
  15708. if (line.text.length <= cm.options.maxHighlightLength)
  15709. { processLine(cm, line.text, context); }
  15710. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  15711. context.nextLine();
  15712. }
  15713. if (+new Date > end) {
  15714. startWorker(cm, cm.options.workDelay);
  15715. return true
  15716. }
  15717. });
  15718. doc.highlightFrontier = context.line;
  15719. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  15720. if (changedLines.length) { runInOp(cm, function () {
  15721. for (var i = 0; i < changedLines.length; i++)
  15722. { regLineChange(cm, changedLines[i], "text"); }
  15723. }); }
  15724. }
  15725. // DISPLAY DRAWING
  15726. var DisplayUpdate = function(cm, viewport, force) {
  15727. var display = cm.display;
  15728. this.viewport = viewport;
  15729. // Store some values that we'll need later (but don't want to force a relayout for)
  15730. this.visible = visibleLines(display, cm.doc, viewport);
  15731. this.editorIsHidden = !display.wrapper.offsetWidth;
  15732. this.wrapperHeight = display.wrapper.clientHeight;
  15733. this.wrapperWidth = display.wrapper.clientWidth;
  15734. this.oldDisplayWidth = displayWidth(cm);
  15735. this.force = force;
  15736. this.dims = getDimensions(cm);
  15737. this.events = [];
  15738. };
  15739. DisplayUpdate.prototype.signal = function (emitter, type) {
  15740. if (hasHandler(emitter, type))
  15741. { this.events.push(arguments); }
  15742. };
  15743. DisplayUpdate.prototype.finish = function () {
  15744. for (var i = 0; i < this.events.length; i++)
  15745. { signal.apply(null, this.events[i]); }
  15746. };
  15747. function maybeClipScrollbars(cm) {
  15748. var display = cm.display;
  15749. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  15750. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  15751. display.heightForcer.style.height = scrollGap(cm) + "px";
  15752. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  15753. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  15754. display.scrollbarsClipped = true;
  15755. }
  15756. }
  15757. function selectionSnapshot(cm) {
  15758. if (cm.hasFocus()) { return null }
  15759. var active = activeElt();
  15760. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  15761. var result = {activeElt: active};
  15762. if (window.getSelection) {
  15763. var sel = window.getSelection();
  15764. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  15765. result.anchorNode = sel.anchorNode;
  15766. result.anchorOffset = sel.anchorOffset;
  15767. result.focusNode = sel.focusNode;
  15768. result.focusOffset = sel.focusOffset;
  15769. }
  15770. }
  15771. return result
  15772. }
  15773. function restoreSelection(snapshot) {
  15774. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  15775. snapshot.activeElt.focus();
  15776. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  15777. snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  15778. var sel = window.getSelection(), range = document.createRange();
  15779. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  15780. range.collapse(false);
  15781. sel.removeAllRanges();
  15782. sel.addRange(range);
  15783. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  15784. }
  15785. }
  15786. // Does the actual updating of the line display. Bails out
  15787. // (returning false) when there is nothing to be done and forced is
  15788. // false.
  15789. function updateDisplayIfNeeded(cm, update) {
  15790. var display = cm.display, doc = cm.doc;
  15791. if (update.editorIsHidden) {
  15792. resetView(cm);
  15793. return false
  15794. }
  15795. // Bail out if the visible area is already rendered and nothing changed.
  15796. if (!update.force &&
  15797. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  15798. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  15799. display.renderedView == display.view && countDirtyView(cm) == 0)
  15800. { return false }
  15801. if (maybeUpdateLineNumberWidth(cm)) {
  15802. resetView(cm);
  15803. update.dims = getDimensions(cm);
  15804. }
  15805. // Compute a suitable new viewport (from & to)
  15806. var end = doc.first + doc.size;
  15807. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  15808. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  15809. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  15810. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  15811. if (sawCollapsedSpans) {
  15812. from = visualLineNo(cm.doc, from);
  15813. to = visualLineEndNo(cm.doc, to);
  15814. }
  15815. var different = from != display.viewFrom || to != display.viewTo ||
  15816. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  15817. adjustView(cm, from, to);
  15818. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  15819. // Position the mover div to align with the current scroll position
  15820. cm.display.mover.style.top = display.viewOffset + "px";
  15821. var toUpdate = countDirtyView(cm);
  15822. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  15823. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  15824. { return false }
  15825. // For big changes, we hide the enclosing element during the
  15826. // update, since that speeds up the operations on most browsers.
  15827. var selSnapshot = selectionSnapshot(cm);
  15828. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  15829. patchDisplay(cm, display.updateLineNumbers, update.dims);
  15830. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  15831. display.renderedView = display.view;
  15832. // There might have been a widget with a focused element that got
  15833. // hidden or updated, if so re-focus it.
  15834. restoreSelection(selSnapshot);
  15835. // Prevent selection and cursors from interfering with the scroll
  15836. // width and height.
  15837. removeChildren(display.cursorDiv);
  15838. removeChildren(display.selectionDiv);
  15839. display.gutters.style.height = display.sizer.style.minHeight = 0;
  15840. if (different) {
  15841. display.lastWrapHeight = update.wrapperHeight;
  15842. display.lastWrapWidth = update.wrapperWidth;
  15843. startWorker(cm, 400);
  15844. }
  15845. display.updateLineNumbers = null;
  15846. return true
  15847. }
  15848. function postUpdateDisplay(cm, update) {
  15849. var viewport = update.viewport;
  15850. for (var first = true;; first = false) {
  15851. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  15852. // Clip forced viewport to actual scrollable area.
  15853. if (viewport && viewport.top != null)
  15854. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  15855. // Updated line heights might result in the drawn area not
  15856. // actually covering the viewport. Keep looping until it does.
  15857. update.visible = visibleLines(cm.display, cm.doc, viewport);
  15858. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  15859. { break }
  15860. } else if (first) {
  15861. update.visible = visibleLines(cm.display, cm.doc, viewport);
  15862. }
  15863. if (!updateDisplayIfNeeded(cm, update)) { break }
  15864. updateHeightsInViewport(cm);
  15865. var barMeasure = measureForScrollbars(cm);
  15866. updateSelection(cm);
  15867. updateScrollbars(cm, barMeasure);
  15868. setDocumentHeight(cm, barMeasure);
  15869. update.force = false;
  15870. }
  15871. update.signal(cm, "update", cm);
  15872. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  15873. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  15874. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  15875. }
  15876. }
  15877. function updateDisplaySimple(cm, viewport) {
  15878. var update = new DisplayUpdate(cm, viewport);
  15879. if (updateDisplayIfNeeded(cm, update)) {
  15880. updateHeightsInViewport(cm);
  15881. postUpdateDisplay(cm, update);
  15882. var barMeasure = measureForScrollbars(cm);
  15883. updateSelection(cm);
  15884. updateScrollbars(cm, barMeasure);
  15885. setDocumentHeight(cm, barMeasure);
  15886. update.finish();
  15887. }
  15888. }
  15889. // Sync the actual display DOM structure with display.view, removing
  15890. // nodes for lines that are no longer in view, and creating the ones
  15891. // that are not there yet, and updating the ones that are out of
  15892. // date.
  15893. function patchDisplay(cm, updateNumbersFrom, dims) {
  15894. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  15895. var container = display.lineDiv, cur = container.firstChild;
  15896. function rm(node) {
  15897. var next = node.nextSibling;
  15898. // Works around a throw-scroll bug in OS X Webkit
  15899. if (webkit && mac && cm.display.currentWheelTarget == node)
  15900. { node.style.display = "none"; }
  15901. else
  15902. { node.parentNode.removeChild(node); }
  15903. return next
  15904. }
  15905. var view = display.view, lineN = display.viewFrom;
  15906. // Loop over the elements in the view, syncing cur (the DOM nodes
  15907. // in display.lineDiv) with the view as we go.
  15908. for (var i = 0; i < view.length; i++) {
  15909. var lineView = view[i];
  15910. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  15911. var node = buildLineElement(cm, lineView, lineN, dims);
  15912. container.insertBefore(node, cur);
  15913. } else { // Already drawn
  15914. while (cur != lineView.node) { cur = rm(cur); }
  15915. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  15916. updateNumbersFrom <= lineN && lineView.lineNumber;
  15917. if (lineView.changes) {
  15918. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  15919. updateLineForChanges(cm, lineView, lineN, dims);
  15920. }
  15921. if (updateNumber) {
  15922. removeChildren(lineView.lineNumber);
  15923. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  15924. }
  15925. cur = lineView.node.nextSibling;
  15926. }
  15927. lineN += lineView.size;
  15928. }
  15929. while (cur) { cur = rm(cur); }
  15930. }
  15931. function updateGutterSpace(display) {
  15932. var width = display.gutters.offsetWidth;
  15933. display.sizer.style.marginLeft = width + "px";
  15934. }
  15935. function setDocumentHeight(cm, measure) {
  15936. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  15937. cm.display.heightForcer.style.top = measure.docHeight + "px";
  15938. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  15939. }
  15940. // Re-align line numbers and gutter marks to compensate for
  15941. // horizontal scrolling.
  15942. function alignHorizontally(cm) {
  15943. var display = cm.display, view = display.view;
  15944. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  15945. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  15946. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  15947. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  15948. if (cm.options.fixedGutter) {
  15949. if (view[i].gutter)
  15950. { view[i].gutter.style.left = left; }
  15951. if (view[i].gutterBackground)
  15952. { view[i].gutterBackground.style.left = left; }
  15953. }
  15954. var align = view[i].alignable;
  15955. if (align) { for (var j = 0; j < align.length; j++)
  15956. { align[j].style.left = left; } }
  15957. } }
  15958. if (cm.options.fixedGutter)
  15959. { display.gutters.style.left = (comp + gutterW) + "px"; }
  15960. }
  15961. // Used to ensure that the line number gutter is still the right
  15962. // size for the current document size. Returns true when an update
  15963. // is needed.
  15964. function maybeUpdateLineNumberWidth(cm) {
  15965. if (!cm.options.lineNumbers) { return false }
  15966. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  15967. if (last.length != display.lineNumChars) {
  15968. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  15969. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  15970. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  15971. display.lineGutter.style.width = "";
  15972. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  15973. display.lineNumWidth = display.lineNumInnerWidth + padding;
  15974. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  15975. display.lineGutter.style.width = display.lineNumWidth + "px";
  15976. updateGutterSpace(cm.display);
  15977. return true
  15978. }
  15979. return false
  15980. }
  15981. function getGutters(gutters, lineNumbers) {
  15982. var result = [], sawLineNumbers = false;
  15983. for (var i = 0; i < gutters.length; i++) {
  15984. var name = gutters[i], style = null;
  15985. if (typeof name != "string") { style = name.style; name = name.className; }
  15986. if (name == "CodeMirror-linenumbers") {
  15987. if (!lineNumbers) { continue }
  15988. else { sawLineNumbers = true; }
  15989. }
  15990. result.push({className: name, style: style});
  15991. }
  15992. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  15993. return result
  15994. }
  15995. // Rebuild the gutter elements, ensure the margin to the left of the
  15996. // code matches their width.
  15997. function renderGutters(display) {
  15998. var gutters = display.gutters, specs = display.gutterSpecs;
  15999. removeChildren(gutters);
  16000. display.lineGutter = null;
  16001. for (var i = 0; i < specs.length; ++i) {
  16002. var ref = specs[i];
  16003. var className = ref.className;
  16004. var style = ref.style;
  16005. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  16006. if (style) { gElt.style.cssText = style; }
  16007. if (className == "CodeMirror-linenumbers") {
  16008. display.lineGutter = gElt;
  16009. gElt.style.width = (display.lineNumWidth || 1) + "px";
  16010. }
  16011. }
  16012. gutters.style.display = specs.length ? "" : "none";
  16013. updateGutterSpace(display);
  16014. }
  16015. function updateGutters(cm) {
  16016. renderGutters(cm.display);
  16017. regChange(cm);
  16018. alignHorizontally(cm);
  16019. }
  16020. // The display handles the DOM integration, both for input reading
  16021. // and content drawing. It holds references to DOM nodes and
  16022. // display-related state.
  16023. function Display(place, doc, input, options) {
  16024. var d = this;
  16025. this.input = input;
  16026. // Covers bottom-right square when both scrollbars are present.
  16027. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  16028. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  16029. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  16030. // and h scrollbar is present.
  16031. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  16032. d.gutterFiller.setAttribute("cm-not-content", "true");
  16033. // Will contain the actual code, positioned to cover the viewport.
  16034. d.lineDiv = eltP("div", null, "CodeMirror-code");
  16035. // Elements are added to these to represent selection and cursors.
  16036. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  16037. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  16038. // A visibility: hidden element used to find the size of things.
  16039. d.measure = elt("div", null, "CodeMirror-measure");
  16040. // When lines outside of the viewport are measured, they are drawn in this.
  16041. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  16042. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  16043. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  16044. null, "position: relative; outline: none");
  16045. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  16046. // Moved around its parent to cover visible view.
  16047. d.mover = elt("div", [lines], null, "position: relative");
  16048. // Set to the height of the document, allowing scrolling.
  16049. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  16050. d.sizerWidth = null;
  16051. // Behavior of elts with overflow: auto and padding is
  16052. // inconsistent across browsers. This is used to ensure the
  16053. // scrollable area is big enough.
  16054. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  16055. // Will contain the gutters, if any.
  16056. d.gutters = elt("div", null, "CodeMirror-gutters");
  16057. d.lineGutter = null;
  16058. // Actual scrollable element.
  16059. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  16060. d.scroller.setAttribute("tabIndex", "-1");
  16061. // The element in which the editor lives.
  16062. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  16063. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  16064. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  16065. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  16066. if (place) {
  16067. if (place.appendChild) { place.appendChild(d.wrapper); }
  16068. else { place(d.wrapper); }
  16069. }
  16070. // Current rendered range (may be bigger than the view window).
  16071. d.viewFrom = d.viewTo = doc.first;
  16072. d.reportedViewFrom = d.reportedViewTo = doc.first;
  16073. // Information about the rendered lines.
  16074. d.view = [];
  16075. d.renderedView = null;
  16076. // Holds info about a single rendered line when it was rendered
  16077. // for measurement, while not in view.
  16078. d.externalMeasured = null;
  16079. // Empty space (in pixels) above the view
  16080. d.viewOffset = 0;
  16081. d.lastWrapHeight = d.lastWrapWidth = 0;
  16082. d.updateLineNumbers = null;
  16083. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  16084. d.scrollbarsClipped = false;
  16085. // Used to only resize the line number gutter when necessary (when
  16086. // the amount of lines crosses a boundary that makes its width change)
  16087. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  16088. // Set to true when a non-horizontal-scrolling line widget is
  16089. // added. As an optimization, line widget aligning is skipped when
  16090. // this is false.
  16091. d.alignWidgets = false;
  16092. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  16093. // Tracks the maximum line length so that the horizontal scrollbar
  16094. // can be kept static when scrolling.
  16095. d.maxLine = null;
  16096. d.maxLineLength = 0;
  16097. d.maxLineChanged = false;
  16098. // Used for measuring wheel scrolling granularity
  16099. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  16100. // True when shift is held down.
  16101. d.shift = false;
  16102. // Used to track whether anything happened since the context menu
  16103. // was opened.
  16104. d.selForContextMenu = null;
  16105. d.activeTouch = null;
  16106. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  16107. renderGutters(d);
  16108. input.init(d);
  16109. }
  16110. // Since the delta values reported on mouse wheel events are
  16111. // unstandardized between browsers and even browser versions, and
  16112. // generally horribly unpredictable, this code starts by measuring
  16113. // the scroll effect that the first few mouse wheel events have,
  16114. // and, from that, detects the way it can convert deltas to pixel
  16115. // offsets afterwards.
  16116. //
  16117. // The reason we want to know the amount a wheel event will scroll
  16118. // is that it gives us a chance to update the display before the
  16119. // actual scrolling happens, reducing flickering.
  16120. var wheelSamples = 0, wheelPixelsPerUnit = null;
  16121. // Fill in a browser-detected starting value on browsers where we
  16122. // know one. These don't have to be accurate -- the result of them
  16123. // being wrong would just be a slight flicker on the first wheel
  16124. // scroll (if it is large enough).
  16125. if (ie) { wheelPixelsPerUnit = -.53; }
  16126. else if (gecko) { wheelPixelsPerUnit = 15; }
  16127. else if (chrome) { wheelPixelsPerUnit = -.7; }
  16128. else if (safari) { wheelPixelsPerUnit = -1/3; }
  16129. function wheelEventDelta(e) {
  16130. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  16131. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  16132. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  16133. else if (dy == null) { dy = e.wheelDelta; }
  16134. return {x: dx, y: dy}
  16135. }
  16136. function wheelEventPixels(e) {
  16137. var delta = wheelEventDelta(e);
  16138. delta.x *= wheelPixelsPerUnit;
  16139. delta.y *= wheelPixelsPerUnit;
  16140. return delta
  16141. }
  16142. function onScrollWheel(cm, e) {
  16143. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  16144. var display = cm.display, scroll = display.scroller;
  16145. // Quit if there's nothing to scroll here
  16146. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  16147. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  16148. if (!(dx && canScrollX || dy && canScrollY)) { return }
  16149. // Webkit browsers on OS X abort momentum scrolls when the target
  16150. // of the scroll event is removed from the scrollable element.
  16151. // This hack (see related code in patchDisplay) makes sure the
  16152. // element is kept around.
  16153. if (dy && mac && webkit) {
  16154. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  16155. for (var i = 0; i < view.length; i++) {
  16156. if (view[i].node == cur) {
  16157. cm.display.currentWheelTarget = cur;
  16158. break outer
  16159. }
  16160. }
  16161. }
  16162. }
  16163. // On some browsers, horizontal scrolling will cause redraws to
  16164. // happen before the gutter has been realigned, causing it to
  16165. // wriggle around in a most unseemly way. When we have an
  16166. // estimated pixels/delta value, we just handle horizontal
  16167. // scrolling entirely here. It'll be slightly off from native, but
  16168. // better than glitching out.
  16169. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  16170. if (dy && canScrollY)
  16171. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  16172. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  16173. // Only prevent default scrolling if vertical scrolling is
  16174. // actually possible. Otherwise, it causes vertical scroll
  16175. // jitter on OSX trackpads when deltaX is small and deltaY
  16176. // is large (issue #3579)
  16177. if (!dy || (dy && canScrollY))
  16178. { e_preventDefault(e); }
  16179. display.wheelStartX = null; // Abort measurement, if in progress
  16180. return
  16181. }
  16182. // 'Project' the visible viewport to cover the area that is being
  16183. // scrolled into view (if we know enough to estimate it).
  16184. if (dy && wheelPixelsPerUnit != null) {
  16185. var pixels = dy * wheelPixelsPerUnit;
  16186. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  16187. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  16188. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  16189. updateDisplaySimple(cm, {top: top, bottom: bot});
  16190. }
  16191. if (wheelSamples < 20) {
  16192. if (display.wheelStartX == null) {
  16193. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  16194. display.wheelDX = dx; display.wheelDY = dy;
  16195. setTimeout(function () {
  16196. if (display.wheelStartX == null) { return }
  16197. var movedX = scroll.scrollLeft - display.wheelStartX;
  16198. var movedY = scroll.scrollTop - display.wheelStartY;
  16199. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  16200. (movedX && display.wheelDX && movedX / display.wheelDX);
  16201. display.wheelStartX = display.wheelStartY = null;
  16202. if (!sample) { return }
  16203. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  16204. ++wheelSamples;
  16205. }, 200);
  16206. } else {
  16207. display.wheelDX += dx; display.wheelDY += dy;
  16208. }
  16209. }
  16210. }
  16211. // Selection objects are immutable. A new one is created every time
  16212. // the selection changes. A selection is one or more non-overlapping
  16213. // (and non-touching) ranges, sorted, and an integer that indicates
  16214. // which one is the primary selection (the one that's scrolled into
  16215. // view, that getCursor returns, etc).
  16216. var Selection = function(ranges, primIndex) {
  16217. this.ranges = ranges;
  16218. this.primIndex = primIndex;
  16219. };
  16220. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  16221. Selection.prototype.equals = function (other) {
  16222. if (other == this) { return true }
  16223. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  16224. for (var i = 0; i < this.ranges.length; i++) {
  16225. var here = this.ranges[i], there = other.ranges[i];
  16226. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  16227. }
  16228. return true
  16229. };
  16230. Selection.prototype.deepCopy = function () {
  16231. var out = [];
  16232. for (var i = 0; i < this.ranges.length; i++)
  16233. { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  16234. return new Selection(out, this.primIndex)
  16235. };
  16236. Selection.prototype.somethingSelected = function () {
  16237. for (var i = 0; i < this.ranges.length; i++)
  16238. { if (!this.ranges[i].empty()) { return true } }
  16239. return false
  16240. };
  16241. Selection.prototype.contains = function (pos, end) {
  16242. if (!end) { end = pos; }
  16243. for (var i = 0; i < this.ranges.length; i++) {
  16244. var range = this.ranges[i];
  16245. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  16246. { return i }
  16247. }
  16248. return -1
  16249. };
  16250. var Range = function(anchor, head) {
  16251. this.anchor = anchor; this.head = head;
  16252. };
  16253. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  16254. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  16255. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  16256. // Take an unsorted, potentially overlapping set of ranges, and
  16257. // build a selection out of it. 'Consumes' ranges array (modifying
  16258. // it).
  16259. function normalizeSelection(cm, ranges, primIndex) {
  16260. var mayTouch = cm && cm.options.selectionsMayTouch;
  16261. var prim = ranges[primIndex];
  16262. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  16263. primIndex = indexOf(ranges, prim);
  16264. for (var i = 1; i < ranges.length; i++) {
  16265. var cur = ranges[i], prev = ranges[i - 1];
  16266. var diff = cmp(prev.to(), cur.from());
  16267. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  16268. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  16269. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  16270. if (i <= primIndex) { --primIndex; }
  16271. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  16272. }
  16273. }
  16274. return new Selection(ranges, primIndex)
  16275. }
  16276. function simpleSelection(anchor, head) {
  16277. return new Selection([new Range(anchor, head || anchor)], 0)
  16278. }
  16279. // Compute the position of the end of a change (its 'to' property
  16280. // refers to the pre-change end).
  16281. function changeEnd(change) {
  16282. if (!change.text) { return change.to }
  16283. return Pos(change.from.line + change.text.length - 1,
  16284. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  16285. }
  16286. // Adjust a position to refer to the post-change position of the
  16287. // same text, or the end of the change if the change covers it.
  16288. function adjustForChange(pos, change) {
  16289. if (cmp(pos, change.from) < 0) { return pos }
  16290. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  16291. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  16292. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  16293. return Pos(line, ch)
  16294. }
  16295. function computeSelAfterChange(doc, change) {
  16296. var out = [];
  16297. for (var i = 0; i < doc.sel.ranges.length; i++) {
  16298. var range = doc.sel.ranges[i];
  16299. out.push(new Range(adjustForChange(range.anchor, change),
  16300. adjustForChange(range.head, change)));
  16301. }
  16302. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  16303. }
  16304. function offsetPos(pos, old, nw) {
  16305. if (pos.line == old.line)
  16306. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  16307. else
  16308. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  16309. }
  16310. // Used by replaceSelections to allow moving the selection to the
  16311. // start or around the replaced test. Hint may be "start" or "around".
  16312. function computeReplacedSel(doc, changes, hint) {
  16313. var out = [];
  16314. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  16315. for (var i = 0; i < changes.length; i++) {
  16316. var change = changes[i];
  16317. var from = offsetPos(change.from, oldPrev, newPrev);
  16318. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  16319. oldPrev = change.to;
  16320. newPrev = to;
  16321. if (hint == "around") {
  16322. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  16323. out[i] = new Range(inv ? to : from, inv ? from : to);
  16324. } else {
  16325. out[i] = new Range(from, from);
  16326. }
  16327. }
  16328. return new Selection(out, doc.sel.primIndex)
  16329. }
  16330. // Used to get the editor into a consistent state again when options change.
  16331. function loadMode(cm) {
  16332. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  16333. resetModeState(cm);
  16334. }
  16335. function resetModeState(cm) {
  16336. cm.doc.iter(function (line) {
  16337. if (line.stateAfter) { line.stateAfter = null; }
  16338. if (line.styles) { line.styles = null; }
  16339. });
  16340. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  16341. startWorker(cm, 100);
  16342. cm.state.modeGen++;
  16343. if (cm.curOp) { regChange(cm); }
  16344. }
  16345. // DOCUMENT DATA STRUCTURE
  16346. // By default, updates that start and end at the beginning of a line
  16347. // are treated specially, in order to make the association of line
  16348. // widgets and marker elements with the text behave more intuitive.
  16349. function isWholeLineUpdate(doc, change) {
  16350. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  16351. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  16352. }
  16353. // Perform a change on the document data structure.
  16354. function updateDoc(doc, change, markedSpans, estimateHeight) {
  16355. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  16356. function update(line, text, spans) {
  16357. updateLine(line, text, spans, estimateHeight);
  16358. signalLater(line, "change", line, change);
  16359. }
  16360. function linesFor(start, end) {
  16361. var result = [];
  16362. for (var i = start; i < end; ++i)
  16363. { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  16364. return result
  16365. }
  16366. var from = change.from, to = change.to, text = change.text;
  16367. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  16368. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  16369. // Adjust the line structure
  16370. if (change.full) {
  16371. doc.insert(0, linesFor(0, text.length));
  16372. doc.remove(text.length, doc.size - text.length);
  16373. } else if (isWholeLineUpdate(doc, change)) {
  16374. // This is a whole-line replace. Treated specially to make
  16375. // sure line objects move the way they are supposed to.
  16376. var added = linesFor(0, text.length - 1);
  16377. update(lastLine, lastLine.text, lastSpans);
  16378. if (nlines) { doc.remove(from.line, nlines); }
  16379. if (added.length) { doc.insert(from.line, added); }
  16380. } else if (firstLine == lastLine) {
  16381. if (text.length == 1) {
  16382. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  16383. } else {
  16384. var added$1 = linesFor(1, text.length - 1);
  16385. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  16386. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  16387. doc.insert(from.line + 1, added$1);
  16388. }
  16389. } else if (text.length == 1) {
  16390. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  16391. doc.remove(from.line + 1, nlines);
  16392. } else {
  16393. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  16394. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  16395. var added$2 = linesFor(1, text.length - 1);
  16396. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  16397. doc.insert(from.line + 1, added$2);
  16398. }
  16399. signalLater(doc, "change", doc, change);
  16400. }
  16401. // Call f for all linked documents.
  16402. function linkedDocs(doc, f, sharedHistOnly) {
  16403. function propagate(doc, skip, sharedHist) {
  16404. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  16405. var rel = doc.linked[i];
  16406. if (rel.doc == skip) { continue }
  16407. var shared = sharedHist && rel.sharedHist;
  16408. if (sharedHistOnly && !shared) { continue }
  16409. f(rel.doc, shared);
  16410. propagate(rel.doc, doc, shared);
  16411. } }
  16412. }
  16413. propagate(doc, null, true);
  16414. }
  16415. // Attach a document to an editor.
  16416. function attachDoc(cm, doc) {
  16417. if (doc.cm) { throw new Error("This document is already in use.") }
  16418. cm.doc = doc;
  16419. doc.cm = cm;
  16420. estimateLineHeights(cm);
  16421. loadMode(cm);
  16422. setDirectionClass(cm);
  16423. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  16424. cm.options.mode = doc.modeOption;
  16425. regChange(cm);
  16426. }
  16427. function setDirectionClass(cm) {
  16428. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  16429. }
  16430. function directionChanged(cm) {
  16431. runInOp(cm, function () {
  16432. setDirectionClass(cm);
  16433. regChange(cm);
  16434. });
  16435. }
  16436. function History(startGen) {
  16437. // Arrays of change events and selections. Doing something adds an
  16438. // event to done and clears undo. Undoing moves events from done
  16439. // to undone, redoing moves them in the other direction.
  16440. this.done = []; this.undone = [];
  16441. this.undoDepth = Infinity;
  16442. // Used to track when changes can be merged into a single undo
  16443. // event
  16444. this.lastModTime = this.lastSelTime = 0;
  16445. this.lastOp = this.lastSelOp = null;
  16446. this.lastOrigin = this.lastSelOrigin = null;
  16447. // Used by the isClean() method
  16448. this.generation = this.maxGeneration = startGen || 1;
  16449. }
  16450. // Create a history change event from an updateDoc-style change
  16451. // object.
  16452. function historyChangeFromChange(doc, change) {
  16453. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  16454. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  16455. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  16456. return histChange
  16457. }
  16458. // Pop all selection events off the end of a history array. Stop at
  16459. // a change event.
  16460. function clearSelectionEvents(array) {
  16461. while (array.length) {
  16462. var last = lst(array);
  16463. if (last.ranges) { array.pop(); }
  16464. else { break }
  16465. }
  16466. }
  16467. // Find the top change event in the history. Pop off selection
  16468. // events that are in the way.
  16469. function lastChangeEvent(hist, force) {
  16470. if (force) {
  16471. clearSelectionEvents(hist.done);
  16472. return lst(hist.done)
  16473. } else if (hist.done.length && !lst(hist.done).ranges) {
  16474. return lst(hist.done)
  16475. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  16476. hist.done.pop();
  16477. return lst(hist.done)
  16478. }
  16479. }
  16480. // Register a change in the history. Merges changes that are within
  16481. // a single operation, or are close together with an origin that
  16482. // allows merging (starting with "+") into a single event.
  16483. function addChangeToHistory(doc, change, selAfter, opId) {
  16484. var hist = doc.history;
  16485. hist.undone.length = 0;
  16486. var time = +new Date, cur;
  16487. var last;
  16488. if ((hist.lastOp == opId ||
  16489. hist.lastOrigin == change.origin && change.origin &&
  16490. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  16491. change.origin.charAt(0) == "*")) &&
  16492. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  16493. // Merge this change into the last event
  16494. last = lst(cur.changes);
  16495. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  16496. // Optimized case for simple insertion -- don't want to add
  16497. // new changesets for every character typed
  16498. last.to = changeEnd(change);
  16499. } else {
  16500. // Add new sub-event
  16501. cur.changes.push(historyChangeFromChange(doc, change));
  16502. }
  16503. } else {
  16504. // Can not be merged, start a new event.
  16505. var before = lst(hist.done);
  16506. if (!before || !before.ranges)
  16507. { pushSelectionToHistory(doc.sel, hist.done); }
  16508. cur = {changes: [historyChangeFromChange(doc, change)],
  16509. generation: hist.generation};
  16510. hist.done.push(cur);
  16511. while (hist.done.length > hist.undoDepth) {
  16512. hist.done.shift();
  16513. if (!hist.done[0].ranges) { hist.done.shift(); }
  16514. }
  16515. }
  16516. hist.done.push(selAfter);
  16517. hist.generation = ++hist.maxGeneration;
  16518. hist.lastModTime = hist.lastSelTime = time;
  16519. hist.lastOp = hist.lastSelOp = opId;
  16520. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  16521. if (!last) { signal(doc, "historyAdded"); }
  16522. }
  16523. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  16524. var ch = origin.charAt(0);
  16525. return ch == "*" ||
  16526. ch == "+" &&
  16527. prev.ranges.length == sel.ranges.length &&
  16528. prev.somethingSelected() == sel.somethingSelected() &&
  16529. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  16530. }
  16531. // Called whenever the selection changes, sets the new selection as
  16532. // the pending selection in the history, and pushes the old pending
  16533. // selection into the 'done' array when it was significantly
  16534. // different (in number of selected ranges, emptiness, or time).
  16535. function addSelectionToHistory(doc, sel, opId, options) {
  16536. var hist = doc.history, origin = options && options.origin;
  16537. // A new event is started when the previous origin does not match
  16538. // the current, or the origins don't allow matching. Origins
  16539. // starting with * are always merged, those starting with + are
  16540. // merged when similar and close together in time.
  16541. if (opId == hist.lastSelOp ||
  16542. (origin && hist.lastSelOrigin == origin &&
  16543. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  16544. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  16545. { hist.done[hist.done.length - 1] = sel; }
  16546. else
  16547. { pushSelectionToHistory(sel, hist.done); }
  16548. hist.lastSelTime = +new Date;
  16549. hist.lastSelOrigin = origin;
  16550. hist.lastSelOp = opId;
  16551. if (options && options.clearRedo !== false)
  16552. { clearSelectionEvents(hist.undone); }
  16553. }
  16554. function pushSelectionToHistory(sel, dest) {
  16555. var top = lst(dest);
  16556. if (!(top && top.ranges && top.equals(sel)))
  16557. { dest.push(sel); }
  16558. }
  16559. // Used to store marked span information in the history.
  16560. function attachLocalSpans(doc, change, from, to) {
  16561. var existing = change["spans_" + doc.id], n = 0;
  16562. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  16563. if (line.markedSpans)
  16564. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  16565. ++n;
  16566. });
  16567. }
  16568. // When un/re-doing restores text containing marked spans, those
  16569. // that have been explicitly cleared should not be restored.
  16570. function removeClearedSpans(spans) {
  16571. if (!spans) { return null }
  16572. var out;
  16573. for (var i = 0; i < spans.length; ++i) {
  16574. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  16575. else if (out) { out.push(spans[i]); }
  16576. }
  16577. return !out ? spans : out.length ? out : null
  16578. }
  16579. // Retrieve and filter the old marked spans stored in a change event.
  16580. function getOldSpans(doc, change) {
  16581. var found = change["spans_" + doc.id];
  16582. if (!found) { return null }
  16583. var nw = [];
  16584. for (var i = 0; i < change.text.length; ++i)
  16585. { nw.push(removeClearedSpans(found[i])); }
  16586. return nw
  16587. }
  16588. // Used for un/re-doing changes from the history. Combines the
  16589. // result of computing the existing spans with the set of spans that
  16590. // existed in the history (so that deleting around a span and then
  16591. // undoing brings back the span).
  16592. function mergeOldSpans(doc, change) {
  16593. var old = getOldSpans(doc, change);
  16594. var stretched = stretchSpansOverChange(doc, change);
  16595. if (!old) { return stretched }
  16596. if (!stretched) { return old }
  16597. for (var i = 0; i < old.length; ++i) {
  16598. var oldCur = old[i], stretchCur = stretched[i];
  16599. if (oldCur && stretchCur) {
  16600. spans: for (var j = 0; j < stretchCur.length; ++j) {
  16601. var span = stretchCur[j];
  16602. for (var k = 0; k < oldCur.length; ++k)
  16603. { if (oldCur[k].marker == span.marker) { continue spans } }
  16604. oldCur.push(span);
  16605. }
  16606. } else if (stretchCur) {
  16607. old[i] = stretchCur;
  16608. }
  16609. }
  16610. return old
  16611. }
  16612. // Used both to provide a JSON-safe object in .getHistory, and, when
  16613. // detaching a document, to split the history in two
  16614. function copyHistoryArray(events, newGroup, instantiateSel) {
  16615. var copy = [];
  16616. for (var i = 0; i < events.length; ++i) {
  16617. var event = events[i];
  16618. if (event.ranges) {
  16619. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  16620. continue
  16621. }
  16622. var changes = event.changes, newChanges = [];
  16623. copy.push({changes: newChanges});
  16624. for (var j = 0; j < changes.length; ++j) {
  16625. var change = changes[j], m = (void 0);
  16626. newChanges.push({from: change.from, to: change.to, text: change.text});
  16627. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  16628. if (indexOf(newGroup, Number(m[1])) > -1) {
  16629. lst(newChanges)[prop] = change[prop];
  16630. delete change[prop];
  16631. }
  16632. } } }
  16633. }
  16634. }
  16635. return copy
  16636. }
  16637. // The 'scroll' parameter given to many of these indicated whether
  16638. // the new cursor position should be scrolled into view after
  16639. // modifying the selection.
  16640. // If shift is held or the extend flag is set, extends a range to
  16641. // include a given position (and optionally a second position).
  16642. // Otherwise, simply returns the range between the given positions.
  16643. // Used for cursor motion and such.
  16644. function extendRange(range, head, other, extend) {
  16645. if (extend) {
  16646. var anchor = range.anchor;
  16647. if (other) {
  16648. var posBefore = cmp(head, anchor) < 0;
  16649. if (posBefore != (cmp(other, anchor) < 0)) {
  16650. anchor = head;
  16651. head = other;
  16652. } else if (posBefore != (cmp(head, other) < 0)) {
  16653. head = other;
  16654. }
  16655. }
  16656. return new Range(anchor, head)
  16657. } else {
  16658. return new Range(other || head, head)
  16659. }
  16660. }
  16661. // Extend the primary selection range, discard the rest.
  16662. function extendSelection(doc, head, other, options, extend) {
  16663. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  16664. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  16665. }
  16666. // Extend all selections (pos is an array of selections with length
  16667. // equal the number of selections)
  16668. function extendSelections(doc, heads, options) {
  16669. var out = [];
  16670. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  16671. for (var i = 0; i < doc.sel.ranges.length; i++)
  16672. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  16673. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  16674. setSelection(doc, newSel, options);
  16675. }
  16676. // Updates a single range in the selection.
  16677. function replaceOneSelection(doc, i, range, options) {
  16678. var ranges = doc.sel.ranges.slice(0);
  16679. ranges[i] = range;
  16680. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  16681. }
  16682. // Reset the selection to a single range.
  16683. function setSimpleSelection(doc, anchor, head, options) {
  16684. setSelection(doc, simpleSelection(anchor, head), options);
  16685. }
  16686. // Give beforeSelectionChange handlers a change to influence a
  16687. // selection update.
  16688. function filterSelectionChange(doc, sel, options) {
  16689. var obj = {
  16690. ranges: sel.ranges,
  16691. update: function(ranges) {
  16692. this.ranges = [];
  16693. for (var i = 0; i < ranges.length; i++)
  16694. { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  16695. clipPos(doc, ranges[i].head)); }
  16696. },
  16697. origin: options && options.origin
  16698. };
  16699. signal(doc, "beforeSelectionChange", doc, obj);
  16700. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  16701. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  16702. else { return sel }
  16703. }
  16704. function setSelectionReplaceHistory(doc, sel, options) {
  16705. var done = doc.history.done, last = lst(done);
  16706. if (last && last.ranges) {
  16707. done[done.length - 1] = sel;
  16708. setSelectionNoUndo(doc, sel, options);
  16709. } else {
  16710. setSelection(doc, sel, options);
  16711. }
  16712. }
  16713. // Set a new selection.
  16714. function setSelection(doc, sel, options) {
  16715. setSelectionNoUndo(doc, sel, options);
  16716. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  16717. }
  16718. function setSelectionNoUndo(doc, sel, options) {
  16719. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  16720. { sel = filterSelectionChange(doc, sel, options); }
  16721. var bias = options && options.bias ||
  16722. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  16723. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  16724. if (!(options && options.scroll === false) && doc.cm)
  16725. { ensureCursorVisible(doc.cm); }
  16726. }
  16727. function setSelectionInner(doc, sel) {
  16728. if (sel.equals(doc.sel)) { return }
  16729. doc.sel = sel;
  16730. if (doc.cm) {
  16731. doc.cm.curOp.updateInput = 1;
  16732. doc.cm.curOp.selectionChanged = true;
  16733. signalCursorActivity(doc.cm);
  16734. }
  16735. signalLater(doc, "cursorActivity", doc);
  16736. }
  16737. // Verify that the selection does not partially select any atomic
  16738. // marked ranges.
  16739. function reCheckSelection(doc) {
  16740. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  16741. }
  16742. // Return a selection that does not partially select any atomic
  16743. // ranges.
  16744. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  16745. var out;
  16746. for (var i = 0; i < sel.ranges.length; i++) {
  16747. var range = sel.ranges[i];
  16748. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  16749. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  16750. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  16751. if (out || newAnchor != range.anchor || newHead != range.head) {
  16752. if (!out) { out = sel.ranges.slice(0, i); }
  16753. out[i] = new Range(newAnchor, newHead);
  16754. }
  16755. }
  16756. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  16757. }
  16758. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  16759. var line = getLine(doc, pos.line);
  16760. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  16761. var sp = line.markedSpans[i], m = sp.marker;
  16762. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  16763. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  16764. // is with selectLeft/Right
  16765. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  16766. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  16767. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  16768. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  16769. if (mayClear) {
  16770. signal(m, "beforeCursorEnter");
  16771. if (m.explicitlyCleared) {
  16772. if (!line.markedSpans) { break }
  16773. else {--i; continue}
  16774. }
  16775. }
  16776. if (!m.atomic) { continue }
  16777. if (oldPos) {
  16778. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  16779. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  16780. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  16781. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  16782. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  16783. }
  16784. var far = m.find(dir < 0 ? -1 : 1);
  16785. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  16786. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  16787. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  16788. }
  16789. } }
  16790. return pos
  16791. }
  16792. // Ensure a given position is not inside an atomic range.
  16793. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  16794. var dir = bias || 1;
  16795. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  16796. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  16797. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  16798. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  16799. if (!found) {
  16800. doc.cantEdit = true;
  16801. return Pos(doc.first, 0)
  16802. }
  16803. return found
  16804. }
  16805. function movePos(doc, pos, dir, line) {
  16806. if (dir < 0 && pos.ch == 0) {
  16807. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  16808. else { return null }
  16809. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  16810. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  16811. else { return null }
  16812. } else {
  16813. return new Pos(pos.line, pos.ch + dir)
  16814. }
  16815. }
  16816. function selectAll(cm) {
  16817. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  16818. }
  16819. // UPDATING
  16820. // Allow "beforeChange" event handlers to influence a change
  16821. function filterChange(doc, change, update) {
  16822. var obj = {
  16823. canceled: false,
  16824. from: change.from,
  16825. to: change.to,
  16826. text: change.text,
  16827. origin: change.origin,
  16828. cancel: function () { return obj.canceled = true; }
  16829. };
  16830. if (update) { obj.update = function (from, to, text, origin) {
  16831. if (from) { obj.from = clipPos(doc, from); }
  16832. if (to) { obj.to = clipPos(doc, to); }
  16833. if (text) { obj.text = text; }
  16834. if (origin !== undefined) { obj.origin = origin; }
  16835. }; }
  16836. signal(doc, "beforeChange", doc, obj);
  16837. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  16838. if (obj.canceled) {
  16839. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  16840. return null
  16841. }
  16842. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  16843. }
  16844. // Apply a change to a document, and add it to the document's
  16845. // history, and propagating it to all linked documents.
  16846. function makeChange(doc, change, ignoreReadOnly) {
  16847. if (doc.cm) {
  16848. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  16849. if (doc.cm.state.suppressEdits) { return }
  16850. }
  16851. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  16852. change = filterChange(doc, change, true);
  16853. if (!change) { return }
  16854. }
  16855. // Possibly split or suppress the update based on the presence
  16856. // of read-only spans in its range.
  16857. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  16858. if (split) {
  16859. for (var i = split.length - 1; i >= 0; --i)
  16860. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  16861. } else {
  16862. makeChangeInner(doc, change);
  16863. }
  16864. }
  16865. function makeChangeInner(doc, change) {
  16866. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  16867. var selAfter = computeSelAfterChange(doc, change);
  16868. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  16869. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  16870. var rebased = [];
  16871. linkedDocs(doc, function (doc, sharedHist) {
  16872. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  16873. rebaseHist(doc.history, change);
  16874. rebased.push(doc.history);
  16875. }
  16876. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  16877. });
  16878. }
  16879. // Revert a change stored in a document's history.
  16880. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  16881. var suppress = doc.cm && doc.cm.state.suppressEdits;
  16882. if (suppress && !allowSelectionOnly) { return }
  16883. var hist = doc.history, event, selAfter = doc.sel;
  16884. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  16885. // Verify that there is a useable event (so that ctrl-z won't
  16886. // needlessly clear selection events)
  16887. var i = 0;
  16888. for (; i < source.length; i++) {
  16889. event = source[i];
  16890. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  16891. { break }
  16892. }
  16893. if (i == source.length) { return }
  16894. hist.lastOrigin = hist.lastSelOrigin = null;
  16895. for (;;) {
  16896. event = source.pop();
  16897. if (event.ranges) {
  16898. pushSelectionToHistory(event, dest);
  16899. if (allowSelectionOnly && !event.equals(doc.sel)) {
  16900. setSelection(doc, event, {clearRedo: false});
  16901. return
  16902. }
  16903. selAfter = event;
  16904. } else if (suppress) {
  16905. source.push(event);
  16906. return
  16907. } else { break }
  16908. }
  16909. // Build up a reverse change object to add to the opposite history
  16910. // stack (redo when undoing, and vice versa).
  16911. var antiChanges = [];
  16912. pushSelectionToHistory(selAfter, dest);
  16913. dest.push({changes: antiChanges, generation: hist.generation});
  16914. hist.generation = event.generation || ++hist.maxGeneration;
  16915. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  16916. var loop = function ( i ) {
  16917. var change = event.changes[i];
  16918. change.origin = type;
  16919. if (filter && !filterChange(doc, change, false)) {
  16920. source.length = 0;
  16921. return {}
  16922. }
  16923. antiChanges.push(historyChangeFromChange(doc, change));
  16924. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  16925. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  16926. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  16927. var rebased = [];
  16928. // Propagate to the linked documents
  16929. linkedDocs(doc, function (doc, sharedHist) {
  16930. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  16931. rebaseHist(doc.history, change);
  16932. rebased.push(doc.history);
  16933. }
  16934. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  16935. });
  16936. };
  16937. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  16938. var returned = loop( i$1 );
  16939. if ( returned ) return returned.v;
  16940. }
  16941. }
  16942. // Sub-views need their line numbers shifted when text is added
  16943. // above or below them in the parent document.
  16944. function shiftDoc(doc, distance) {
  16945. if (distance == 0) { return }
  16946. doc.first += distance;
  16947. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  16948. Pos(range.anchor.line + distance, range.anchor.ch),
  16949. Pos(range.head.line + distance, range.head.ch)
  16950. ); }), doc.sel.primIndex);
  16951. if (doc.cm) {
  16952. regChange(doc.cm, doc.first, doc.first - distance, distance);
  16953. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  16954. { regLineChange(doc.cm, l, "gutter"); }
  16955. }
  16956. }
  16957. // More lower-level change function, handling only a single document
  16958. // (not linked ones).
  16959. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  16960. if (doc.cm && !doc.cm.curOp)
  16961. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  16962. if (change.to.line < doc.first) {
  16963. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  16964. return
  16965. }
  16966. if (change.from.line > doc.lastLine()) { return }
  16967. // Clip the change to the size of this doc
  16968. if (change.from.line < doc.first) {
  16969. var shift = change.text.length - 1 - (doc.first - change.from.line);
  16970. shiftDoc(doc, shift);
  16971. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  16972. text: [lst(change.text)], origin: change.origin};
  16973. }
  16974. var last = doc.lastLine();
  16975. if (change.to.line > last) {
  16976. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  16977. text: [change.text[0]], origin: change.origin};
  16978. }
  16979. change.removed = getBetween(doc, change.from, change.to);
  16980. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  16981. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  16982. else { updateDoc(doc, change, spans); }
  16983. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  16984. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  16985. { doc.cantEdit = false; }
  16986. }
  16987. // Handle the interaction of a change to a document with the editor
  16988. // that this document is part of.
  16989. function makeChangeSingleDocInEditor(cm, change, spans) {
  16990. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  16991. var recomputeMaxLength = false, checkWidthStart = from.line;
  16992. if (!cm.options.lineWrapping) {
  16993. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  16994. doc.iter(checkWidthStart, to.line + 1, function (line) {
  16995. if (line == display.maxLine) {
  16996. recomputeMaxLength = true;
  16997. return true
  16998. }
  16999. });
  17000. }
  17001. if (doc.sel.contains(change.from, change.to) > -1)
  17002. { signalCursorActivity(cm); }
  17003. updateDoc(doc, change, spans, estimateHeight(cm));
  17004. if (!cm.options.lineWrapping) {
  17005. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  17006. var len = lineLength(line);
  17007. if (len > display.maxLineLength) {
  17008. display.maxLine = line;
  17009. display.maxLineLength = len;
  17010. display.maxLineChanged = true;
  17011. recomputeMaxLength = false;
  17012. }
  17013. });
  17014. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  17015. }
  17016. retreatFrontier(doc, from.line);
  17017. startWorker(cm, 400);
  17018. var lendiff = change.text.length - (to.line - from.line) - 1;
  17019. // Remember that these lines changed, for updating the display
  17020. if (change.full)
  17021. { regChange(cm); }
  17022. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  17023. { regLineChange(cm, from.line, "text"); }
  17024. else
  17025. { regChange(cm, from.line, to.line + 1, lendiff); }
  17026. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  17027. if (changeHandler || changesHandler) {
  17028. var obj = {
  17029. from: from, to: to,
  17030. text: change.text,
  17031. removed: change.removed,
  17032. origin: change.origin
  17033. };
  17034. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  17035. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  17036. }
  17037. cm.display.selForContextMenu = null;
  17038. }
  17039. function replaceRange(doc, code, from, to, origin) {
  17040. var assign;
  17041. if (!to) { to = from; }
  17042. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  17043. if (typeof code == "string") { code = doc.splitLines(code); }
  17044. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  17045. }
  17046. // Rebasing/resetting history to deal with externally-sourced changes
  17047. function rebaseHistSelSingle(pos, from, to, diff) {
  17048. if (to < pos.line) {
  17049. pos.line += diff;
  17050. } else if (from < pos.line) {
  17051. pos.line = from;
  17052. pos.ch = 0;
  17053. }
  17054. }
  17055. // Tries to rebase an array of history events given a change in the
  17056. // document. If the change touches the same lines as the event, the
  17057. // event, and everything 'behind' it, is discarded. If the change is
  17058. // before the event, the event's positions are updated. Uses a
  17059. // copy-on-write scheme for the positions, to avoid having to
  17060. // reallocate them all on every rebase, but also avoid problems with
  17061. // shared position objects being unsafely updated.
  17062. function rebaseHistArray(array, from, to, diff) {
  17063. for (var i = 0; i < array.length; ++i) {
  17064. var sub = array[i], ok = true;
  17065. if (sub.ranges) {
  17066. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  17067. for (var j = 0; j < sub.ranges.length; j++) {
  17068. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  17069. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  17070. }
  17071. continue
  17072. }
  17073. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  17074. var cur = sub.changes[j$1];
  17075. if (to < cur.from.line) {
  17076. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  17077. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  17078. } else if (from <= cur.to.line) {
  17079. ok = false;
  17080. break
  17081. }
  17082. }
  17083. if (!ok) {
  17084. array.splice(0, i + 1);
  17085. i = 0;
  17086. }
  17087. }
  17088. }
  17089. function rebaseHist(hist, change) {
  17090. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  17091. rebaseHistArray(hist.done, from, to, diff);
  17092. rebaseHistArray(hist.undone, from, to, diff);
  17093. }
  17094. // Utility for applying a change to a line by handle or number,
  17095. // returning the number and optionally registering the line as
  17096. // changed.
  17097. function changeLine(doc, handle, changeType, op) {
  17098. var no = handle, line = handle;
  17099. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  17100. else { no = lineNo(handle); }
  17101. if (no == null) { return null }
  17102. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  17103. return line
  17104. }
  17105. // The document is represented as a BTree consisting of leaves, with
  17106. // chunk of lines in them, and branches, with up to ten leaves or
  17107. // other branch nodes below them. The top node is always a branch
  17108. // node, and is the document object itself (meaning it has
  17109. // additional methods and properties).
  17110. //
  17111. // All nodes have parent links. The tree is used both to go from
  17112. // line numbers to line objects, and to go from objects to numbers.
  17113. // It also indexes by height, and is used to convert between height
  17114. // and line object, and to find the total height of the document.
  17115. //
  17116. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  17117. function LeafChunk(lines) {
  17118. this.lines = lines;
  17119. this.parent = null;
  17120. var height = 0;
  17121. for (var i = 0; i < lines.length; ++i) {
  17122. lines[i].parent = this;
  17123. height += lines[i].height;
  17124. }
  17125. this.height = height;
  17126. }
  17127. LeafChunk.prototype = {
  17128. chunkSize: function() { return this.lines.length },
  17129. // Remove the n lines at offset 'at'.
  17130. removeInner: function(at, n) {
  17131. for (var i = at, e = at + n; i < e; ++i) {
  17132. var line = this.lines[i];
  17133. this.height -= line.height;
  17134. cleanUpLine(line);
  17135. signalLater(line, "delete");
  17136. }
  17137. this.lines.splice(at, n);
  17138. },
  17139. // Helper used to collapse a small branch into a single leaf.
  17140. collapse: function(lines) {
  17141. lines.push.apply(lines, this.lines);
  17142. },
  17143. // Insert the given array of lines at offset 'at', count them as
  17144. // having the given height.
  17145. insertInner: function(at, lines, height) {
  17146. this.height += height;
  17147. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  17148. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  17149. },
  17150. // Used to iterate over a part of the tree.
  17151. iterN: function(at, n, op) {
  17152. for (var e = at + n; at < e; ++at)
  17153. { if (op(this.lines[at])) { return true } }
  17154. }
  17155. };
  17156. function BranchChunk(children) {
  17157. this.children = children;
  17158. var size = 0, height = 0;
  17159. for (var i = 0; i < children.length; ++i) {
  17160. var ch = children[i];
  17161. size += ch.chunkSize(); height += ch.height;
  17162. ch.parent = this;
  17163. }
  17164. this.size = size;
  17165. this.height = height;
  17166. this.parent = null;
  17167. }
  17168. BranchChunk.prototype = {
  17169. chunkSize: function() { return this.size },
  17170. removeInner: function(at, n) {
  17171. this.size -= n;
  17172. for (var i = 0; i < this.children.length; ++i) {
  17173. var child = this.children[i], sz = child.chunkSize();
  17174. if (at < sz) {
  17175. var rm = Math.min(n, sz - at), oldHeight = child.height;
  17176. child.removeInner(at, rm);
  17177. this.height -= oldHeight - child.height;
  17178. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  17179. if ((n -= rm) == 0) { break }
  17180. at = 0;
  17181. } else { at -= sz; }
  17182. }
  17183. // If the result is smaller than 25 lines, ensure that it is a
  17184. // single leaf node.
  17185. if (this.size - n < 25 &&
  17186. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  17187. var lines = [];
  17188. this.collapse(lines);
  17189. this.children = [new LeafChunk(lines)];
  17190. this.children[0].parent = this;
  17191. }
  17192. },
  17193. collapse: function(lines) {
  17194. for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  17195. },
  17196. insertInner: function(at, lines, height) {
  17197. this.size += lines.length;
  17198. this.height += height;
  17199. for (var i = 0; i < this.children.length; ++i) {
  17200. var child = this.children[i], sz = child.chunkSize();
  17201. if (at <= sz) {
  17202. child.insertInner(at, lines, height);
  17203. if (child.lines && child.lines.length > 50) {
  17204. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  17205. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  17206. var remaining = child.lines.length % 25 + 25;
  17207. for (var pos = remaining; pos < child.lines.length;) {
  17208. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  17209. child.height -= leaf.height;
  17210. this.children.splice(++i, 0, leaf);
  17211. leaf.parent = this;
  17212. }
  17213. child.lines = child.lines.slice(0, remaining);
  17214. this.maybeSpill();
  17215. }
  17216. break
  17217. }
  17218. at -= sz;
  17219. }
  17220. },
  17221. // When a node has grown, check whether it should be split.
  17222. maybeSpill: function() {
  17223. if (this.children.length <= 10) { return }
  17224. var me = this;
  17225. do {
  17226. var spilled = me.children.splice(me.children.length - 5, 5);
  17227. var sibling = new BranchChunk(spilled);
  17228. if (!me.parent) { // Become the parent node
  17229. var copy = new BranchChunk(me.children);
  17230. copy.parent = me;
  17231. me.children = [copy, sibling];
  17232. me = copy;
  17233. } else {
  17234. me.size -= sibling.size;
  17235. me.height -= sibling.height;
  17236. var myIndex = indexOf(me.parent.children, me);
  17237. me.parent.children.splice(myIndex + 1, 0, sibling);
  17238. }
  17239. sibling.parent = me.parent;
  17240. } while (me.children.length > 10)
  17241. me.parent.maybeSpill();
  17242. },
  17243. iterN: function(at, n, op) {
  17244. for (var i = 0; i < this.children.length; ++i) {
  17245. var child = this.children[i], sz = child.chunkSize();
  17246. if (at < sz) {
  17247. var used = Math.min(n, sz - at);
  17248. if (child.iterN(at, used, op)) { return true }
  17249. if ((n -= used) == 0) { break }
  17250. at = 0;
  17251. } else { at -= sz; }
  17252. }
  17253. }
  17254. };
  17255. // Line widgets are block elements displayed above or below a line.
  17256. var LineWidget = function(doc, node, options) {
  17257. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  17258. { this[opt] = options[opt]; } } }
  17259. this.doc = doc;
  17260. this.node = node;
  17261. };
  17262. LineWidget.prototype.clear = function () {
  17263. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  17264. if (no == null || !ws) { return }
  17265. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  17266. if (!ws.length) { line.widgets = null; }
  17267. var height = widgetHeight(this);
  17268. updateLineHeight(line, Math.max(0, line.height - height));
  17269. if (cm) {
  17270. runInOp(cm, function () {
  17271. adjustScrollWhenAboveVisible(cm, line, -height);
  17272. regLineChange(cm, no, "widget");
  17273. });
  17274. signalLater(cm, "lineWidgetCleared", cm, this, no);
  17275. }
  17276. };
  17277. LineWidget.prototype.changed = function () {
  17278. var this$1 = this;
  17279. var oldH = this.height, cm = this.doc.cm, line = this.line;
  17280. this.height = null;
  17281. var diff = widgetHeight(this) - oldH;
  17282. if (!diff) { return }
  17283. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  17284. if (cm) {
  17285. runInOp(cm, function () {
  17286. cm.curOp.forceUpdate = true;
  17287. adjustScrollWhenAboveVisible(cm, line, diff);
  17288. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  17289. });
  17290. }
  17291. };
  17292. eventMixin(LineWidget);
  17293. function adjustScrollWhenAboveVisible(cm, line, diff) {
  17294. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  17295. { addToScrollTop(cm, diff); }
  17296. }
  17297. function addLineWidget(doc, handle, node, options) {
  17298. var widget = new LineWidget(doc, node, options);
  17299. var cm = doc.cm;
  17300. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  17301. changeLine(doc, handle, "widget", function (line) {
  17302. var widgets = line.widgets || (line.widgets = []);
  17303. if (widget.insertAt == null) { widgets.push(widget); }
  17304. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  17305. widget.line = line;
  17306. if (cm && !lineIsHidden(doc, line)) {
  17307. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  17308. updateLineHeight(line, line.height + widgetHeight(widget));
  17309. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  17310. cm.curOp.forceUpdate = true;
  17311. }
  17312. return true
  17313. });
  17314. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  17315. return widget
  17316. }
  17317. // TEXTMARKERS
  17318. // Created with markText and setBookmark methods. A TextMarker is a
  17319. // handle that can be used to clear or find a marked position in the
  17320. // document. Line objects hold arrays (markedSpans) containing
  17321. // {from, to, marker} object pointing to such marker objects, and
  17322. // indicating that such a marker is present on that line. Multiple
  17323. // lines may point to the same marker when it spans across lines.
  17324. // The spans will have null for their from/to properties when the
  17325. // marker continues beyond the start/end of the line. Markers have
  17326. // links back to the lines they currently touch.
  17327. // Collapsed markers have unique ids, in order to be able to order
  17328. // them, which is needed for uniquely determining an outer marker
  17329. // when they overlap (they may nest, but not partially overlap).
  17330. var nextMarkerId = 0;
  17331. var TextMarker = function(doc, type) {
  17332. this.lines = [];
  17333. this.type = type;
  17334. this.doc = doc;
  17335. this.id = ++nextMarkerId;
  17336. };
  17337. // Clear the marker.
  17338. TextMarker.prototype.clear = function () {
  17339. if (this.explicitlyCleared) { return }
  17340. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  17341. if (withOp) { startOperation(cm); }
  17342. if (hasHandler(this, "clear")) {
  17343. var found = this.find();
  17344. if (found) { signalLater(this, "clear", found.from, found.to); }
  17345. }
  17346. var min = null, max = null;
  17347. for (var i = 0; i < this.lines.length; ++i) {
  17348. var line = this.lines[i];
  17349. var span = getMarkedSpanFor(line.markedSpans, this);
  17350. if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  17351. else if (cm) {
  17352. if (span.to != null) { max = lineNo(line); }
  17353. if (span.from != null) { min = lineNo(line); }
  17354. }
  17355. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  17356. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  17357. { updateLineHeight(line, textHeight(cm.display)); }
  17358. }
  17359. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  17360. var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  17361. if (len > cm.display.maxLineLength) {
  17362. cm.display.maxLine = visual;
  17363. cm.display.maxLineLength = len;
  17364. cm.display.maxLineChanged = true;
  17365. }
  17366. } }
  17367. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  17368. this.lines.length = 0;
  17369. this.explicitlyCleared = true;
  17370. if (this.atomic && this.doc.cantEdit) {
  17371. this.doc.cantEdit = false;
  17372. if (cm) { reCheckSelection(cm.doc); }
  17373. }
  17374. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  17375. if (withOp) { endOperation(cm); }
  17376. if (this.parent) { this.parent.clear(); }
  17377. };
  17378. // Find the position of the marker in the document. Returns a {from,
  17379. // to} object by default. Side can be passed to get a specific side
  17380. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  17381. // Pos objects returned contain a line object, rather than a line
  17382. // number (used to prevent looking up the same line twice).
  17383. TextMarker.prototype.find = function (side, lineObj) {
  17384. if (side == null && this.type == "bookmark") { side = 1; }
  17385. var from, to;
  17386. for (var i = 0; i < this.lines.length; ++i) {
  17387. var line = this.lines[i];
  17388. var span = getMarkedSpanFor(line.markedSpans, this);
  17389. if (span.from != null) {
  17390. from = Pos(lineObj ? line : lineNo(line), span.from);
  17391. if (side == -1) { return from }
  17392. }
  17393. if (span.to != null) {
  17394. to = Pos(lineObj ? line : lineNo(line), span.to);
  17395. if (side == 1) { return to }
  17396. }
  17397. }
  17398. return from && {from: from, to: to}
  17399. };
  17400. // Signals that the marker's widget changed, and surrounding layout
  17401. // should be recomputed.
  17402. TextMarker.prototype.changed = function () {
  17403. var this$1 = this;
  17404. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  17405. if (!pos || !cm) { return }
  17406. runInOp(cm, function () {
  17407. var line = pos.line, lineN = lineNo(pos.line);
  17408. var view = findViewForLine(cm, lineN);
  17409. if (view) {
  17410. clearLineMeasurementCacheFor(view);
  17411. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  17412. }
  17413. cm.curOp.updateMaxLine = true;
  17414. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  17415. var oldHeight = widget.height;
  17416. widget.height = null;
  17417. var dHeight = widgetHeight(widget) - oldHeight;
  17418. if (dHeight)
  17419. { updateLineHeight(line, line.height + dHeight); }
  17420. }
  17421. signalLater(cm, "markerChanged", cm, this$1);
  17422. });
  17423. };
  17424. TextMarker.prototype.attachLine = function (line) {
  17425. if (!this.lines.length && this.doc.cm) {
  17426. var op = this.doc.cm.curOp;
  17427. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  17428. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  17429. }
  17430. this.lines.push(line);
  17431. };
  17432. TextMarker.prototype.detachLine = function (line) {
  17433. this.lines.splice(indexOf(this.lines, line), 1);
  17434. if (!this.lines.length && this.doc.cm) {
  17435. var op = this.doc.cm.curOp
  17436. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  17437. }
  17438. };
  17439. eventMixin(TextMarker);
  17440. // Create a marker, wire it up to the right lines, and
  17441. function markText(doc, from, to, options, type) {
  17442. // Shared markers (across linked documents) are handled separately
  17443. // (markTextShared will call out to this again, once per
  17444. // document).
  17445. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  17446. // Ensure we are in an operation.
  17447. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  17448. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  17449. if (options) { copyObj(options, marker, false); }
  17450. // Don't connect empty markers unless clearWhenEmpty is false
  17451. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  17452. { return marker }
  17453. if (marker.replacedWith) {
  17454. // Showing up as a widget implies collapsed (widget replaces text)
  17455. marker.collapsed = true;
  17456. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  17457. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  17458. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  17459. }
  17460. if (marker.collapsed) {
  17461. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  17462. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  17463. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  17464. seeCollapsedSpans();
  17465. }
  17466. if (marker.addToHistory)
  17467. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  17468. var curLine = from.line, cm = doc.cm, updateMaxLine;
  17469. doc.iter(curLine, to.line + 1, function (line) {
  17470. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  17471. { updateMaxLine = true; }
  17472. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  17473. addMarkedSpan(line, new MarkedSpan(marker,
  17474. curLine == from.line ? from.ch : null,
  17475. curLine == to.line ? to.ch : null));
  17476. ++curLine;
  17477. });
  17478. // lineIsHidden depends on the presence of the spans, so needs a second pass
  17479. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  17480. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  17481. }); }
  17482. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  17483. if (marker.readOnly) {
  17484. seeReadOnlySpans();
  17485. if (doc.history.done.length || doc.history.undone.length)
  17486. { doc.clearHistory(); }
  17487. }
  17488. if (marker.collapsed) {
  17489. marker.id = ++nextMarkerId;
  17490. marker.atomic = true;
  17491. }
  17492. if (cm) {
  17493. // Sync editor state
  17494. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  17495. if (marker.collapsed)
  17496. { regChange(cm, from.line, to.line + 1); }
  17497. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  17498. marker.attributes || marker.title)
  17499. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  17500. if (marker.atomic) { reCheckSelection(cm.doc); }
  17501. signalLater(cm, "markerAdded", cm, marker);
  17502. }
  17503. return marker
  17504. }
  17505. // SHARED TEXTMARKERS
  17506. // A shared marker spans multiple linked documents. It is
  17507. // implemented as a meta-marker-object controlling multiple normal
  17508. // markers.
  17509. var SharedTextMarker = function(markers, primary) {
  17510. this.markers = markers;
  17511. this.primary = primary;
  17512. for (var i = 0; i < markers.length; ++i)
  17513. { markers[i].parent = this; }
  17514. };
  17515. SharedTextMarker.prototype.clear = function () {
  17516. if (this.explicitlyCleared) { return }
  17517. this.explicitlyCleared = true;
  17518. for (var i = 0; i < this.markers.length; ++i)
  17519. { this.markers[i].clear(); }
  17520. signalLater(this, "clear");
  17521. };
  17522. SharedTextMarker.prototype.find = function (side, lineObj) {
  17523. return this.primary.find(side, lineObj)
  17524. };
  17525. eventMixin(SharedTextMarker);
  17526. function markTextShared(doc, from, to, options, type) {
  17527. options = copyObj(options);
  17528. options.shared = false;
  17529. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  17530. var widget = options.widgetNode;
  17531. linkedDocs(doc, function (doc) {
  17532. if (widget) { options.widgetNode = widget.cloneNode(true); }
  17533. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  17534. for (var i = 0; i < doc.linked.length; ++i)
  17535. { if (doc.linked[i].isParent) { return } }
  17536. primary = lst(markers);
  17537. });
  17538. return new SharedTextMarker(markers, primary)
  17539. }
  17540. function findSharedMarkers(doc) {
  17541. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  17542. }
  17543. function copySharedMarkers(doc, markers) {
  17544. for (var i = 0; i < markers.length; i++) {
  17545. var marker = markers[i], pos = marker.find();
  17546. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  17547. if (cmp(mFrom, mTo)) {
  17548. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  17549. marker.markers.push(subMark);
  17550. subMark.parent = marker;
  17551. }
  17552. }
  17553. }
  17554. function detachSharedMarkers(markers) {
  17555. var loop = function ( i ) {
  17556. var marker = markers[i], linked = [marker.primary.doc];
  17557. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  17558. for (var j = 0; j < marker.markers.length; j++) {
  17559. var subMarker = marker.markers[j];
  17560. if (indexOf(linked, subMarker.doc) == -1) {
  17561. subMarker.parent = null;
  17562. marker.markers.splice(j--, 1);
  17563. }
  17564. }
  17565. };
  17566. for (var i = 0; i < markers.length; i++) loop( i );
  17567. }
  17568. var nextDocId = 0;
  17569. var Doc = function(text, mode, firstLine, lineSep, direction) {
  17570. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  17571. if (firstLine == null) { firstLine = 0; }
  17572. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  17573. this.first = firstLine;
  17574. this.scrollTop = this.scrollLeft = 0;
  17575. this.cantEdit = false;
  17576. this.cleanGeneration = 1;
  17577. this.modeFrontier = this.highlightFrontier = firstLine;
  17578. var start = Pos(firstLine, 0);
  17579. this.sel = simpleSelection(start);
  17580. this.history = new History(null);
  17581. this.id = ++nextDocId;
  17582. this.modeOption = mode;
  17583. this.lineSep = lineSep;
  17584. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  17585. this.extend = false;
  17586. if (typeof text == "string") { text = this.splitLines(text); }
  17587. updateDoc(this, {from: start, to: start, text: text});
  17588. setSelection(this, simpleSelection(start), sel_dontScroll);
  17589. };
  17590. Doc.prototype = createObj(BranchChunk.prototype, {
  17591. constructor: Doc,
  17592. // Iterate over the document. Supports two forms -- with only one
  17593. // argument, it calls that for each line in the document. With
  17594. // three, it iterates over the range given by the first two (with
  17595. // the second being non-inclusive).
  17596. iter: function(from, to, op) {
  17597. if (op) { this.iterN(from - this.first, to - from, op); }
  17598. else { this.iterN(this.first, this.first + this.size, from); }
  17599. },
  17600. // Non-public interface for adding and removing lines.
  17601. insert: function(at, lines) {
  17602. var height = 0;
  17603. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  17604. this.insertInner(at - this.first, lines, height);
  17605. },
  17606. remove: function(at, n) { this.removeInner(at - this.first, n); },
  17607. // From here, the methods are part of the public interface. Most
  17608. // are also available from CodeMirror (editor) instances.
  17609. getValue: function(lineSep) {
  17610. var lines = getLines(this, this.first, this.first + this.size);
  17611. if (lineSep === false) { return lines }
  17612. return lines.join(lineSep || this.lineSeparator())
  17613. },
  17614. setValue: docMethodOp(function(code) {
  17615. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  17616. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  17617. text: this.splitLines(code), origin: "setValue", full: true}, true);
  17618. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  17619. setSelection(this, simpleSelection(top), sel_dontScroll);
  17620. }),
  17621. replaceRange: function(code, from, to, origin) {
  17622. from = clipPos(this, from);
  17623. to = to ? clipPos(this, to) : from;
  17624. replaceRange(this, code, from, to, origin);
  17625. },
  17626. getRange: function(from, to, lineSep) {
  17627. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  17628. if (lineSep === false) { return lines }
  17629. return lines.join(lineSep || this.lineSeparator())
  17630. },
  17631. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  17632. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  17633. getLineNumber: function(line) {return lineNo(line)},
  17634. getLineHandleVisualStart: function(line) {
  17635. if (typeof line == "number") { line = getLine(this, line); }
  17636. return visualLine(line)
  17637. },
  17638. lineCount: function() {return this.size},
  17639. firstLine: function() {return this.first},
  17640. lastLine: function() {return this.first + this.size - 1},
  17641. clipPos: function(pos) {return clipPos(this, pos)},
  17642. getCursor: function(start) {
  17643. var range = this.sel.primary(), pos;
  17644. if (start == null || start == "head") { pos = range.head; }
  17645. else if (start == "anchor") { pos = range.anchor; }
  17646. else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  17647. else { pos = range.from(); }
  17648. return pos
  17649. },
  17650. listSelections: function() { return this.sel.ranges },
  17651. somethingSelected: function() {return this.sel.somethingSelected()},
  17652. setCursor: docMethodOp(function(line, ch, options) {
  17653. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  17654. }),
  17655. setSelection: docMethodOp(function(anchor, head, options) {
  17656. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  17657. }),
  17658. extendSelection: docMethodOp(function(head, other, options) {
  17659. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  17660. }),
  17661. extendSelections: docMethodOp(function(heads, options) {
  17662. extendSelections(this, clipPosArray(this, heads), options);
  17663. }),
  17664. extendSelectionsBy: docMethodOp(function(f, options) {
  17665. var heads = map(this.sel.ranges, f);
  17666. extendSelections(this, clipPosArray(this, heads), options);
  17667. }),
  17668. setSelections: docMethodOp(function(ranges, primary, options) {
  17669. if (!ranges.length) { return }
  17670. var out = [];
  17671. for (var i = 0; i < ranges.length; i++)
  17672. { out[i] = new Range(clipPos(this, ranges[i].anchor),
  17673. clipPos(this, ranges[i].head)); }
  17674. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  17675. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  17676. }),
  17677. addSelection: docMethodOp(function(anchor, head, options) {
  17678. var ranges = this.sel.ranges.slice(0);
  17679. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  17680. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  17681. }),
  17682. getSelection: function(lineSep) {
  17683. var ranges = this.sel.ranges, lines;
  17684. for (var i = 0; i < ranges.length; i++) {
  17685. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  17686. lines = lines ? lines.concat(sel) : sel;
  17687. }
  17688. if (lineSep === false) { return lines }
  17689. else { return lines.join(lineSep || this.lineSeparator()) }
  17690. },
  17691. getSelections: function(lineSep) {
  17692. var parts = [], ranges = this.sel.ranges;
  17693. for (var i = 0; i < ranges.length; i++) {
  17694. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  17695. if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  17696. parts[i] = sel;
  17697. }
  17698. return parts
  17699. },
  17700. replaceSelection: function(code, collapse, origin) {
  17701. var dup = [];
  17702. for (var i = 0; i < this.sel.ranges.length; i++)
  17703. { dup[i] = code; }
  17704. this.replaceSelections(dup, collapse, origin || "+input");
  17705. },
  17706. replaceSelections: docMethodOp(function(code, collapse, origin) {
  17707. var changes = [], sel = this.sel;
  17708. for (var i = 0; i < sel.ranges.length; i++) {
  17709. var range = sel.ranges[i];
  17710. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  17711. }
  17712. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  17713. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  17714. { makeChange(this, changes[i$1]); }
  17715. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  17716. else if (this.cm) { ensureCursorVisible(this.cm); }
  17717. }),
  17718. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  17719. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  17720. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  17721. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  17722. setExtending: function(val) {this.extend = val;},
  17723. getExtending: function() {return this.extend},
  17724. historySize: function() {
  17725. var hist = this.history, done = 0, undone = 0;
  17726. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  17727. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  17728. return {undo: done, redo: undone}
  17729. },
  17730. clearHistory: function() {
  17731. var this$1 = this;
  17732. this.history = new History(this.history.maxGeneration);
  17733. linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  17734. },
  17735. markClean: function() {
  17736. this.cleanGeneration = this.changeGeneration(true);
  17737. },
  17738. changeGeneration: function(forceSplit) {
  17739. if (forceSplit)
  17740. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  17741. return this.history.generation
  17742. },
  17743. isClean: function (gen) {
  17744. return this.history.generation == (gen || this.cleanGeneration)
  17745. },
  17746. getHistory: function() {
  17747. return {done: copyHistoryArray(this.history.done),
  17748. undone: copyHistoryArray(this.history.undone)}
  17749. },
  17750. setHistory: function(histData) {
  17751. var hist = this.history = new History(this.history.maxGeneration);
  17752. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  17753. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  17754. },
  17755. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  17756. return changeLine(this, line, "gutter", function (line) {
  17757. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  17758. markers[gutterID] = value;
  17759. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  17760. return true
  17761. })
  17762. }),
  17763. clearGutter: docMethodOp(function(gutterID) {
  17764. var this$1 = this;
  17765. this.iter(function (line) {
  17766. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  17767. changeLine(this$1, line, "gutter", function () {
  17768. line.gutterMarkers[gutterID] = null;
  17769. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  17770. return true
  17771. });
  17772. }
  17773. });
  17774. }),
  17775. lineInfo: function(line) {
  17776. var n;
  17777. if (typeof line == "number") {
  17778. if (!isLine(this, line)) { return null }
  17779. n = line;
  17780. line = getLine(this, line);
  17781. if (!line) { return null }
  17782. } else {
  17783. n = lineNo(line);
  17784. if (n == null) { return null }
  17785. }
  17786. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  17787. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  17788. widgets: line.widgets}
  17789. },
  17790. addLineClass: docMethodOp(function(handle, where, cls) {
  17791. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  17792. var prop = where == "text" ? "textClass"
  17793. : where == "background" ? "bgClass"
  17794. : where == "gutter" ? "gutterClass" : "wrapClass";
  17795. if (!line[prop]) { line[prop] = cls; }
  17796. else if (classTest(cls).test(line[prop])) { return false }
  17797. else { line[prop] += " " + cls; }
  17798. return true
  17799. })
  17800. }),
  17801. removeLineClass: docMethodOp(function(handle, where, cls) {
  17802. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  17803. var prop = where == "text" ? "textClass"
  17804. : where == "background" ? "bgClass"
  17805. : where == "gutter" ? "gutterClass" : "wrapClass";
  17806. var cur = line[prop];
  17807. if (!cur) { return false }
  17808. else if (cls == null) { line[prop] = null; }
  17809. else {
  17810. var found = cur.match(classTest(cls));
  17811. if (!found) { return false }
  17812. var end = found.index + found[0].length;
  17813. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  17814. }
  17815. return true
  17816. })
  17817. }),
  17818. addLineWidget: docMethodOp(function(handle, node, options) {
  17819. return addLineWidget(this, handle, node, options)
  17820. }),
  17821. removeLineWidget: function(widget) { widget.clear(); },
  17822. markText: function(from, to, options) {
  17823. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  17824. },
  17825. setBookmark: function(pos, options) {
  17826. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  17827. insertLeft: options && options.insertLeft,
  17828. clearWhenEmpty: false, shared: options && options.shared,
  17829. handleMouseEvents: options && options.handleMouseEvents};
  17830. pos = clipPos(this, pos);
  17831. return markText(this, pos, pos, realOpts, "bookmark")
  17832. },
  17833. findMarksAt: function(pos) {
  17834. pos = clipPos(this, pos);
  17835. var markers = [], spans = getLine(this, pos.line).markedSpans;
  17836. if (spans) { for (var i = 0; i < spans.length; ++i) {
  17837. var span = spans[i];
  17838. if ((span.from == null || span.from <= pos.ch) &&
  17839. (span.to == null || span.to >= pos.ch))
  17840. { markers.push(span.marker.parent || span.marker); }
  17841. } }
  17842. return markers
  17843. },
  17844. findMarks: function(from, to, filter) {
  17845. from = clipPos(this, from); to = clipPos(this, to);
  17846. var found = [], lineNo = from.line;
  17847. this.iter(from.line, to.line + 1, function (line) {
  17848. var spans = line.markedSpans;
  17849. if (spans) { for (var i = 0; i < spans.length; i++) {
  17850. var span = spans[i];
  17851. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  17852. span.from == null && lineNo != from.line ||
  17853. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  17854. (!filter || filter(span.marker)))
  17855. { found.push(span.marker.parent || span.marker); }
  17856. } }
  17857. ++lineNo;
  17858. });
  17859. return found
  17860. },
  17861. getAllMarks: function() {
  17862. var markers = [];
  17863. this.iter(function (line) {
  17864. var sps = line.markedSpans;
  17865. if (sps) { for (var i = 0; i < sps.length; ++i)
  17866. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  17867. });
  17868. return markers
  17869. },
  17870. posFromIndex: function(off) {
  17871. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  17872. this.iter(function (line) {
  17873. var sz = line.text.length + sepSize;
  17874. if (sz > off) { ch = off; return true }
  17875. off -= sz;
  17876. ++lineNo;
  17877. });
  17878. return clipPos(this, Pos(lineNo, ch))
  17879. },
  17880. indexFromPos: function (coords) {
  17881. coords = clipPos(this, coords);
  17882. var index = coords.ch;
  17883. if (coords.line < this.first || coords.ch < 0) { return 0 }
  17884. var sepSize = this.lineSeparator().length;
  17885. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  17886. index += line.text.length + sepSize;
  17887. });
  17888. return index
  17889. },
  17890. copy: function(copyHistory) {
  17891. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  17892. this.modeOption, this.first, this.lineSep, this.direction);
  17893. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  17894. doc.sel = this.sel;
  17895. doc.extend = false;
  17896. if (copyHistory) {
  17897. doc.history.undoDepth = this.history.undoDepth;
  17898. doc.setHistory(this.getHistory());
  17899. }
  17900. return doc
  17901. },
  17902. linkedDoc: function(options) {
  17903. if (!options) { options = {}; }
  17904. var from = this.first, to = this.first + this.size;
  17905. if (options.from != null && options.from > from) { from = options.from; }
  17906. if (options.to != null && options.to < to) { to = options.to; }
  17907. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  17908. if (options.sharedHist) { copy.history = this.history
  17909. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  17910. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  17911. copySharedMarkers(copy, findSharedMarkers(this));
  17912. return copy
  17913. },
  17914. unlinkDoc: function(other) {
  17915. if (other instanceof CodeMirror) { other = other.doc; }
  17916. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  17917. var link = this.linked[i];
  17918. if (link.doc != other) { continue }
  17919. this.linked.splice(i, 1);
  17920. other.unlinkDoc(this);
  17921. detachSharedMarkers(findSharedMarkers(this));
  17922. break
  17923. } }
  17924. // If the histories were shared, split them again
  17925. if (other.history == this.history) {
  17926. var splitIds = [other.id];
  17927. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  17928. other.history = new History(null);
  17929. other.history.done = copyHistoryArray(this.history.done, splitIds);
  17930. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  17931. }
  17932. },
  17933. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  17934. getMode: function() {return this.mode},
  17935. getEditor: function() {return this.cm},
  17936. splitLines: function(str) {
  17937. if (this.lineSep) { return str.split(this.lineSep) }
  17938. return splitLinesAuto(str)
  17939. },
  17940. lineSeparator: function() { return this.lineSep || "\n" },
  17941. setDirection: docMethodOp(function (dir) {
  17942. if (dir != "rtl") { dir = "ltr"; }
  17943. if (dir == this.direction) { return }
  17944. this.direction = dir;
  17945. this.iter(function (line) { return line.order = null; });
  17946. if (this.cm) { directionChanged(this.cm); }
  17947. })
  17948. });
  17949. // Public alias.
  17950. Doc.prototype.eachLine = Doc.prototype.iter;
  17951. // Kludge to work around strange IE behavior where it'll sometimes
  17952. // re-fire a series of drag-related events right after the drop (#1551)
  17953. var lastDrop = 0;
  17954. function onDrop(e) {
  17955. var cm = this;
  17956. clearDragCursor(cm);
  17957. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  17958. { return }
  17959. e_preventDefault(e);
  17960. if (ie) { lastDrop = +new Date; }
  17961. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  17962. if (!pos || cm.isReadOnly()) { return }
  17963. // Might be a file drop, in which case we simply extract the text
  17964. // and insert it.
  17965. if (files && files.length && window.FileReader && window.File) {
  17966. var n = files.length, text = Array(n), read = 0;
  17967. var markAsReadAndPasteIfAllFilesAreRead = function () {
  17968. if (++read == n) {
  17969. operation(cm, function () {
  17970. pos = clipPos(cm.doc, pos);
  17971. var change = {from: pos, to: pos,
  17972. text: cm.doc.splitLines(
  17973. text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  17974. origin: "paste"};
  17975. makeChange(cm.doc, change);
  17976. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  17977. })();
  17978. }
  17979. };
  17980. var readTextFromFile = function (file, i) {
  17981. if (cm.options.allowDropFileTypes &&
  17982. indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  17983. markAsReadAndPasteIfAllFilesAreRead();
  17984. return
  17985. }
  17986. var reader = new FileReader;
  17987. reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  17988. reader.onload = function () {
  17989. var content = reader.result;
  17990. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  17991. markAsReadAndPasteIfAllFilesAreRead();
  17992. return
  17993. }
  17994. text[i] = content;
  17995. markAsReadAndPasteIfAllFilesAreRead();
  17996. };
  17997. reader.readAsText(file);
  17998. };
  17999. for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  18000. } else { // Normal drop
  18001. // Don't do a replace if the drop happened inside of the selected text.
  18002. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  18003. cm.state.draggingText(e);
  18004. // Ensure the editor is re-focused
  18005. setTimeout(function () { return cm.display.input.focus(); }, 20);
  18006. return
  18007. }
  18008. try {
  18009. var text$1 = e.dataTransfer.getData("Text");
  18010. if (text$1) {
  18011. var selected;
  18012. if (cm.state.draggingText && !cm.state.draggingText.copy)
  18013. { selected = cm.listSelections(); }
  18014. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  18015. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  18016. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  18017. cm.replaceSelection(text$1, "around", "paste");
  18018. cm.display.input.focus();
  18019. }
  18020. }
  18021. catch(e){}
  18022. }
  18023. }
  18024. function onDragStart(cm, e) {
  18025. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  18026. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  18027. e.dataTransfer.setData("Text", cm.getSelection());
  18028. e.dataTransfer.effectAllowed = "copyMove";
  18029. // Use dummy image instead of default browsers image.
  18030. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  18031. if (e.dataTransfer.setDragImage && !safari) {
  18032. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  18033. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  18034. if (presto) {
  18035. img.width = img.height = 1;
  18036. cm.display.wrapper.appendChild(img);
  18037. // Force a relayout, or Opera won't use our image for some obscure reason
  18038. img._top = img.offsetTop;
  18039. }
  18040. e.dataTransfer.setDragImage(img, 0, 0);
  18041. if (presto) { img.parentNode.removeChild(img); }
  18042. }
  18043. }
  18044. function onDragOver(cm, e) {
  18045. var pos = posFromMouse(cm, e);
  18046. if (!pos) { return }
  18047. var frag = document.createDocumentFragment();
  18048. drawSelectionCursor(cm, pos, frag);
  18049. if (!cm.display.dragCursor) {
  18050. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  18051. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  18052. }
  18053. removeChildrenAndAdd(cm.display.dragCursor, frag);
  18054. }
  18055. function clearDragCursor(cm) {
  18056. if (cm.display.dragCursor) {
  18057. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  18058. cm.display.dragCursor = null;
  18059. }
  18060. }
  18061. // These must be handled carefully, because naively registering a
  18062. // handler for each editor will cause the editors to never be
  18063. // garbage collected.
  18064. function forEachCodeMirror(f) {
  18065. if (!document.getElementsByClassName) { return }
  18066. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  18067. for (var i = 0; i < byClass.length; i++) {
  18068. var cm = byClass[i].CodeMirror;
  18069. if (cm) { editors.push(cm); }
  18070. }
  18071. if (editors.length) { editors[0].operation(function () {
  18072. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  18073. }); }
  18074. }
  18075. var globalsRegistered = false;
  18076. function ensureGlobalHandlers() {
  18077. if (globalsRegistered) { return }
  18078. registerGlobalHandlers();
  18079. globalsRegistered = true;
  18080. }
  18081. function registerGlobalHandlers() {
  18082. // When the window resizes, we need to refresh active editors.
  18083. var resizeTimer;
  18084. on(window, "resize", function () {
  18085. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  18086. resizeTimer = null;
  18087. forEachCodeMirror(onResize);
  18088. }, 100); }
  18089. });
  18090. // When the window loses focus, we want to show the editor as blurred
  18091. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  18092. }
  18093. // Called when the window resizes
  18094. function onResize(cm) {
  18095. var d = cm.display;
  18096. // Might be a text scaling operation, clear size caches.
  18097. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  18098. d.scrollbarsClipped = false;
  18099. cm.setSize();
  18100. }
  18101. var keyNames = {
  18102. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  18103. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  18104. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  18105. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  18106. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  18107. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  18108. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  18109. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  18110. };
  18111. // Number keys
  18112. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  18113. // Alphabetic keys
  18114. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  18115. // Function keys
  18116. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  18117. var keyMap = {};
  18118. keyMap.basic = {
  18119. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  18120. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  18121. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  18122. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  18123. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  18124. "Esc": "singleSelection"
  18125. };
  18126. // Note that the save and find-related commands aren't defined by
  18127. // default. User code or addons can define them. Unknown commands
  18128. // are simply ignored.
  18129. keyMap.pcDefault = {
  18130. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  18131. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  18132. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  18133. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  18134. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  18135. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  18136. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  18137. "fallthrough": "basic"
  18138. };
  18139. // Very basic readline/emacs-style bindings, which are standard on Mac.
  18140. keyMap.emacsy = {
  18141. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  18142. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  18143. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  18144. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  18145. "Ctrl-O": "openLine"
  18146. };
  18147. keyMap.macDefault = {
  18148. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  18149. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  18150. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  18151. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  18152. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  18153. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  18154. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  18155. "fallthrough": ["basic", "emacsy"]
  18156. };
  18157. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  18158. // KEYMAP DISPATCH
  18159. function normalizeKeyName(name) {
  18160. var parts = name.split(/-(?!$)/);
  18161. name = parts[parts.length - 1];
  18162. var alt, ctrl, shift, cmd;
  18163. for (var i = 0; i < parts.length - 1; i++) {
  18164. var mod = parts[i];
  18165. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  18166. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  18167. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  18168. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  18169. else { throw new Error("Unrecognized modifier name: " + mod) }
  18170. }
  18171. if (alt) { name = "Alt-" + name; }
  18172. if (ctrl) { name = "Ctrl-" + name; }
  18173. if (cmd) { name = "Cmd-" + name; }
  18174. if (shift) { name = "Shift-" + name; }
  18175. return name
  18176. }
  18177. // This is a kludge to keep keymaps mostly working as raw objects
  18178. // (backwards compatibility) while at the same time support features
  18179. // like normalization and multi-stroke key bindings. It compiles a
  18180. // new normalized keymap, and then updates the old object to reflect
  18181. // this.
  18182. function normalizeKeyMap(keymap) {
  18183. var copy = {};
  18184. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  18185. var value = keymap[keyname];
  18186. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  18187. if (value == "...") { delete keymap[keyname]; continue }
  18188. var keys = map(keyname.split(" "), normalizeKeyName);
  18189. for (var i = 0; i < keys.length; i++) {
  18190. var val = (void 0), name = (void 0);
  18191. if (i == keys.length - 1) {
  18192. name = keys.join(" ");
  18193. val = value;
  18194. } else {
  18195. name = keys.slice(0, i + 1).join(" ");
  18196. val = "...";
  18197. }
  18198. var prev = copy[name];
  18199. if (!prev) { copy[name] = val; }
  18200. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  18201. }
  18202. delete keymap[keyname];
  18203. } }
  18204. for (var prop in copy) { keymap[prop] = copy[prop]; }
  18205. return keymap
  18206. }
  18207. function lookupKey(key, map, handle, context) {
  18208. map = getKeyMap(map);
  18209. var found = map.call ? map.call(key, context) : map[key];
  18210. if (found === false) { return "nothing" }
  18211. if (found === "...") { return "multi" }
  18212. if (found != null && handle(found)) { return "handled" }
  18213. if (map.fallthrough) {
  18214. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  18215. { return lookupKey(key, map.fallthrough, handle, context) }
  18216. for (var i = 0; i < map.fallthrough.length; i++) {
  18217. var result = lookupKey(key, map.fallthrough[i], handle, context);
  18218. if (result) { return result }
  18219. }
  18220. }
  18221. }
  18222. // Modifier key presses don't count as 'real' key presses for the
  18223. // purpose of keymap fallthrough.
  18224. function isModifierKey(value) {
  18225. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  18226. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  18227. }
  18228. function addModifierNames(name, event, noShift) {
  18229. var base = name;
  18230. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  18231. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  18232. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  18233. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  18234. return name
  18235. }
  18236. // Look up the name of a key as indicated by an event object.
  18237. function keyName(event, noShift) {
  18238. if (presto && event.keyCode == 34 && event["char"]) { return false }
  18239. var name = keyNames[event.keyCode];
  18240. if (name == null || event.altGraphKey) { return false }
  18241. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  18242. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  18243. if (event.keyCode == 3 && event.code) { name = event.code; }
  18244. return addModifierNames(name, event, noShift)
  18245. }
  18246. function getKeyMap(val) {
  18247. return typeof val == "string" ? keyMap[val] : val
  18248. }
  18249. // Helper for deleting text near the selection(s), used to implement
  18250. // backspace, delete, and similar functionality.
  18251. function deleteNearSelection(cm, compute) {
  18252. var ranges = cm.doc.sel.ranges, kill = [];
  18253. // Build up a set of ranges to kill first, merging overlapping
  18254. // ranges.
  18255. for (var i = 0; i < ranges.length; i++) {
  18256. var toKill = compute(ranges[i]);
  18257. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  18258. var replaced = kill.pop();
  18259. if (cmp(replaced.from, toKill.from) < 0) {
  18260. toKill.from = replaced.from;
  18261. break
  18262. }
  18263. }
  18264. kill.push(toKill);
  18265. }
  18266. // Next, remove those actual ranges.
  18267. runInOp(cm, function () {
  18268. for (var i = kill.length - 1; i >= 0; i--)
  18269. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  18270. ensureCursorVisible(cm);
  18271. });
  18272. }
  18273. function moveCharLogically(line, ch, dir) {
  18274. var target = skipExtendingChars(line.text, ch + dir, dir);
  18275. return target < 0 || target > line.text.length ? null : target
  18276. }
  18277. function moveLogically(line, start, dir) {
  18278. var ch = moveCharLogically(line, start.ch, dir);
  18279. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  18280. }
  18281. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  18282. if (visually) {
  18283. if (cm.doc.direction == "rtl") { dir = -dir; }
  18284. var order = getOrder(lineObj, cm.doc.direction);
  18285. if (order) {
  18286. var part = dir < 0 ? lst(order) : order[0];
  18287. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  18288. var sticky = moveInStorageOrder ? "after" : "before";
  18289. var ch;
  18290. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  18291. // it could be that the last bidi part is not on the last visual line,
  18292. // since visual lines contain content order-consecutive chunks.
  18293. // Thus, in rtl, we are looking for the first (content-order) character
  18294. // in the rtl chunk that is on the last line (that is, the same line
  18295. // as the last (content-order) character).
  18296. if (part.level > 0 || cm.doc.direction == "rtl") {
  18297. var prep = prepareMeasureForLine(cm, lineObj);
  18298. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  18299. var targetTop = measureCharPrepared(cm, prep, ch).top;
  18300. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  18301. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  18302. } else { ch = dir < 0 ? part.to : part.from; }
  18303. return new Pos(lineNo, ch, sticky)
  18304. }
  18305. }
  18306. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  18307. }
  18308. function moveVisually(cm, line, start, dir) {
  18309. var bidi = getOrder(line, cm.doc.direction);
  18310. if (!bidi) { return moveLogically(line, start, dir) }
  18311. if (start.ch >= line.text.length) {
  18312. start.ch = line.text.length;
  18313. start.sticky = "before";
  18314. } else if (start.ch <= 0) {
  18315. start.ch = 0;
  18316. start.sticky = "after";
  18317. }
  18318. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  18319. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  18320. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  18321. // nothing interesting happens.
  18322. return moveLogically(line, start, dir)
  18323. }
  18324. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  18325. var prep;
  18326. var getWrappedLineExtent = function (ch) {
  18327. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  18328. prep = prep || prepareMeasureForLine(cm, line);
  18329. return wrappedLineExtentChar(cm, line, prep, ch)
  18330. };
  18331. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  18332. if (cm.doc.direction == "rtl" || part.level == 1) {
  18333. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  18334. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  18335. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  18336. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  18337. var sticky = moveInStorageOrder ? "before" : "after";
  18338. return new Pos(start.line, ch, sticky)
  18339. }
  18340. }
  18341. // Case 3: Could not move within this bidi part in this visual line, so leave
  18342. // the current bidi part
  18343. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  18344. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  18345. ? new Pos(start.line, mv(ch, 1), "before")
  18346. : new Pos(start.line, ch, "after"); };
  18347. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  18348. var part = bidi[partPos];
  18349. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  18350. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  18351. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  18352. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  18353. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  18354. }
  18355. };
  18356. // Case 3a: Look for other bidi parts on the same visual line
  18357. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  18358. if (res) { return res }
  18359. // Case 3b: Look for other bidi parts on the next visual line
  18360. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  18361. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  18362. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  18363. if (res) { return res }
  18364. }
  18365. // Case 4: Nowhere to move
  18366. return null
  18367. }
  18368. // Commands are parameter-less actions that can be performed on an
  18369. // editor, mostly used for keybindings.
  18370. var commands = {
  18371. selectAll: selectAll,
  18372. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  18373. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  18374. if (range.empty()) {
  18375. var len = getLine(cm.doc, range.head.line).text.length;
  18376. if (range.head.ch == len && range.head.line < cm.lastLine())
  18377. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  18378. else
  18379. { return {from: range.head, to: Pos(range.head.line, len)} }
  18380. } else {
  18381. return {from: range.from(), to: range.to()}
  18382. }
  18383. }); },
  18384. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  18385. from: Pos(range.from().line, 0),
  18386. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  18387. }); }); },
  18388. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  18389. from: Pos(range.from().line, 0), to: range.from()
  18390. }); }); },
  18391. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  18392. var top = cm.charCoords(range.head, "div").top + 5;
  18393. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  18394. return {from: leftPos, to: range.from()}
  18395. }); },
  18396. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  18397. var top = cm.charCoords(range.head, "div").top + 5;
  18398. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  18399. return {from: range.from(), to: rightPos }
  18400. }); },
  18401. undo: function (cm) { return cm.undo(); },
  18402. redo: function (cm) { return cm.redo(); },
  18403. undoSelection: function (cm) { return cm.undoSelection(); },
  18404. redoSelection: function (cm) { return cm.redoSelection(); },
  18405. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  18406. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  18407. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  18408. {origin: "+move", bias: 1}
  18409. ); },
  18410. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  18411. {origin: "+move", bias: 1}
  18412. ); },
  18413. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  18414. {origin: "+move", bias: -1}
  18415. ); },
  18416. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  18417. var top = cm.cursorCoords(range.head, "div").top + 5;
  18418. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  18419. }, sel_move); },
  18420. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  18421. var top = cm.cursorCoords(range.head, "div").top + 5;
  18422. return cm.coordsChar({left: 0, top: top}, "div")
  18423. }, sel_move); },
  18424. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  18425. var top = cm.cursorCoords(range.head, "div").top + 5;
  18426. var pos = cm.coordsChar({left: 0, top: top}, "div");
  18427. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  18428. return pos
  18429. }, sel_move); },
  18430. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  18431. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  18432. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  18433. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  18434. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  18435. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  18436. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  18437. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  18438. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  18439. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  18440. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  18441. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  18442. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  18443. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  18444. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  18445. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  18446. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  18447. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  18448. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  18449. indentMore: function (cm) { return cm.indentSelection("add"); },
  18450. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  18451. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  18452. insertSoftTab: function (cm) {
  18453. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  18454. for (var i = 0; i < ranges.length; i++) {
  18455. var pos = ranges[i].from();
  18456. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  18457. spaces.push(spaceStr(tabSize - col % tabSize));
  18458. }
  18459. cm.replaceSelections(spaces);
  18460. },
  18461. defaultTab: function (cm) {
  18462. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  18463. else { cm.execCommand("insertTab"); }
  18464. },
  18465. // Swap the two chars left and right of each selection's head.
  18466. // Move cursor behind the two swapped characters afterwards.
  18467. //
  18468. // Doesn't consider line feeds a character.
  18469. // Doesn't scan more than one line above to find a character.
  18470. // Doesn't do anything on an empty line.
  18471. // Doesn't do anything with non-empty selections.
  18472. transposeChars: function (cm) { return runInOp(cm, function () {
  18473. var ranges = cm.listSelections(), newSel = [];
  18474. for (var i = 0; i < ranges.length; i++) {
  18475. if (!ranges[i].empty()) { continue }
  18476. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  18477. if (line) {
  18478. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  18479. if (cur.ch > 0) {
  18480. cur = new Pos(cur.line, cur.ch + 1);
  18481. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  18482. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  18483. } else if (cur.line > cm.doc.first) {
  18484. var prev = getLine(cm.doc, cur.line - 1).text;
  18485. if (prev) {
  18486. cur = new Pos(cur.line, 1);
  18487. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  18488. prev.charAt(prev.length - 1),
  18489. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  18490. }
  18491. }
  18492. }
  18493. newSel.push(new Range(cur, cur));
  18494. }
  18495. cm.setSelections(newSel);
  18496. }); },
  18497. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  18498. var sels = cm.listSelections();
  18499. for (var i = sels.length - 1; i >= 0; i--)
  18500. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  18501. sels = cm.listSelections();
  18502. for (var i$1 = 0; i$1 < sels.length; i$1++)
  18503. { cm.indentLine(sels[i$1].from().line, null, true); }
  18504. ensureCursorVisible(cm);
  18505. }); },
  18506. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  18507. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  18508. };
  18509. function lineStart(cm, lineN) {
  18510. var line = getLine(cm.doc, lineN);
  18511. var visual = visualLine(line);
  18512. if (visual != line) { lineN = lineNo(visual); }
  18513. return endOfLine(true, cm, visual, lineN, 1)
  18514. }
  18515. function lineEnd(cm, lineN) {
  18516. var line = getLine(cm.doc, lineN);
  18517. var visual = visualLineEnd(line);
  18518. if (visual != line) { lineN = lineNo(visual); }
  18519. return endOfLine(true, cm, line, lineN, -1)
  18520. }
  18521. function lineStartSmart(cm, pos) {
  18522. var start = lineStart(cm, pos.line);
  18523. var line = getLine(cm.doc, start.line);
  18524. var order = getOrder(line, cm.doc.direction);
  18525. if (!order || order[0].level == 0) {
  18526. var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  18527. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  18528. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  18529. }
  18530. return start
  18531. }
  18532. // Run a handler that was bound to a key.
  18533. function doHandleBinding(cm, bound, dropShift) {
  18534. if (typeof bound == "string") {
  18535. bound = commands[bound];
  18536. if (!bound) { return false }
  18537. }
  18538. // Ensure previous input has been read, so that the handler sees a
  18539. // consistent view of the document
  18540. cm.display.input.ensurePolled();
  18541. var prevShift = cm.display.shift, done = false;
  18542. try {
  18543. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  18544. if (dropShift) { cm.display.shift = false; }
  18545. done = bound(cm) != Pass;
  18546. } finally {
  18547. cm.display.shift = prevShift;
  18548. cm.state.suppressEdits = false;
  18549. }
  18550. return done
  18551. }
  18552. function lookupKeyForEditor(cm, name, handle) {
  18553. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  18554. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  18555. if (result) { return result }
  18556. }
  18557. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  18558. || lookupKey(name, cm.options.keyMap, handle, cm)
  18559. }
  18560. // Note that, despite the name, this function is also used to check
  18561. // for bound mouse clicks.
  18562. var stopSeq = new Delayed;
  18563. function dispatchKey(cm, name, e, handle) {
  18564. var seq = cm.state.keySeq;
  18565. if (seq) {
  18566. if (isModifierKey(name)) { return "handled" }
  18567. if (/\'$/.test(name))
  18568. { cm.state.keySeq = null; }
  18569. else
  18570. { stopSeq.set(50, function () {
  18571. if (cm.state.keySeq == seq) {
  18572. cm.state.keySeq = null;
  18573. cm.display.input.reset();
  18574. }
  18575. }); }
  18576. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  18577. }
  18578. return dispatchKeyInner(cm, name, e, handle)
  18579. }
  18580. function dispatchKeyInner(cm, name, e, handle) {
  18581. var result = lookupKeyForEditor(cm, name, handle);
  18582. if (result == "multi")
  18583. { cm.state.keySeq = name; }
  18584. if (result == "handled")
  18585. { signalLater(cm, "keyHandled", cm, name, e); }
  18586. if (result == "handled" || result == "multi") {
  18587. e_preventDefault(e);
  18588. restartBlink(cm);
  18589. }
  18590. return !!result
  18591. }
  18592. // Handle a key from the keydown event.
  18593. function handleKeyBinding(cm, e) {
  18594. var name = keyName(e, true);
  18595. if (!name) { return false }
  18596. if (e.shiftKey && !cm.state.keySeq) {
  18597. // First try to resolve full name (including 'Shift-'). Failing
  18598. // that, see if there is a cursor-motion command (starting with
  18599. // 'go') bound to the keyname without 'Shift-'.
  18600. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  18601. || dispatchKey(cm, name, e, function (b) {
  18602. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  18603. { return doHandleBinding(cm, b) }
  18604. })
  18605. } else {
  18606. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  18607. }
  18608. }
  18609. // Handle a key from the keypress event
  18610. function handleCharBinding(cm, e, ch) {
  18611. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  18612. }
  18613. var lastStoppedKey = null;
  18614. function onKeyDown(e) {
  18615. var cm = this;
  18616. if (e.target && e.target != cm.display.input.getField()) { return }
  18617. cm.curOp.focus = activeElt();
  18618. if (signalDOMEvent(cm, e)) { return }
  18619. // IE does strange things with escape.
  18620. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  18621. var code = e.keyCode;
  18622. cm.display.shift = code == 16 || e.shiftKey;
  18623. var handled = handleKeyBinding(cm, e);
  18624. if (presto) {
  18625. lastStoppedKey = handled ? code : null;
  18626. // Opera has no cut event... we try to at least catch the key combo
  18627. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  18628. { cm.replaceSelection("", null, "cut"); }
  18629. }
  18630. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  18631. { document.execCommand("cut"); }
  18632. // Turn mouse into crosshair when Alt is held on Mac.
  18633. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  18634. { showCrossHair(cm); }
  18635. }
  18636. function showCrossHair(cm) {
  18637. var lineDiv = cm.display.lineDiv;
  18638. addClass(lineDiv, "CodeMirror-crosshair");
  18639. function up(e) {
  18640. if (e.keyCode == 18 || !e.altKey) {
  18641. rmClass(lineDiv, "CodeMirror-crosshair");
  18642. off(document, "keyup", up);
  18643. off(document, "mouseover", up);
  18644. }
  18645. }
  18646. on(document, "keyup", up);
  18647. on(document, "mouseover", up);
  18648. }
  18649. function onKeyUp(e) {
  18650. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  18651. signalDOMEvent(this, e);
  18652. }
  18653. function onKeyPress(e) {
  18654. var cm = this;
  18655. if (e.target && e.target != cm.display.input.getField()) { return }
  18656. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  18657. var keyCode = e.keyCode, charCode = e.charCode;
  18658. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  18659. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  18660. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  18661. // Some browsers fire keypress events for backspace
  18662. if (ch == "\x08") { return }
  18663. if (handleCharBinding(cm, e, ch)) { return }
  18664. cm.display.input.onKeyPress(e);
  18665. }
  18666. var DOUBLECLICK_DELAY = 400;
  18667. var PastClick = function(time, pos, button) {
  18668. this.time = time;
  18669. this.pos = pos;
  18670. this.button = button;
  18671. };
  18672. PastClick.prototype.compare = function (time, pos, button) {
  18673. return this.time + DOUBLECLICK_DELAY > time &&
  18674. cmp(pos, this.pos) == 0 && button == this.button
  18675. };
  18676. var lastClick, lastDoubleClick;
  18677. function clickRepeat(pos, button) {
  18678. var now = +new Date;
  18679. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  18680. lastClick = lastDoubleClick = null;
  18681. return "triple"
  18682. } else if (lastClick && lastClick.compare(now, pos, button)) {
  18683. lastDoubleClick = new PastClick(now, pos, button);
  18684. lastClick = null;
  18685. return "double"
  18686. } else {
  18687. lastClick = new PastClick(now, pos, button);
  18688. lastDoubleClick = null;
  18689. return "single"
  18690. }
  18691. }
  18692. // A mouse down can be a single click, double click, triple click,
  18693. // start of selection drag, start of text drag, new cursor
  18694. // (ctrl-click), rectangle drag (alt-drag), or xwin
  18695. // middle-click-paste. Or it might be a click on something we should
  18696. // not interfere with, such as a scrollbar or widget.
  18697. function onMouseDown(e) {
  18698. var cm = this, display = cm.display;
  18699. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  18700. display.input.ensurePolled();
  18701. display.shift = e.shiftKey;
  18702. if (eventInWidget(display, e)) {
  18703. if (!webkit) {
  18704. // Briefly turn off draggability, to allow widgets to do
  18705. // normal dragging things.
  18706. display.scroller.draggable = false;
  18707. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  18708. }
  18709. return
  18710. }
  18711. if (clickInGutter(cm, e)) { return }
  18712. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  18713. window.focus();
  18714. // #3261: make sure, that we're not starting a second selection
  18715. if (button == 1 && cm.state.selectingText)
  18716. { cm.state.selectingText(e); }
  18717. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  18718. if (button == 1) {
  18719. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  18720. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  18721. } else if (button == 2) {
  18722. if (pos) { extendSelection(cm.doc, pos); }
  18723. setTimeout(function () { return display.input.focus(); }, 20);
  18724. } else if (button == 3) {
  18725. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  18726. else { delayBlurEvent(cm); }
  18727. }
  18728. }
  18729. function handleMappedButton(cm, button, pos, repeat, event) {
  18730. var name = "Click";
  18731. if (repeat == "double") { name = "Double" + name; }
  18732. else if (repeat == "triple") { name = "Triple" + name; }
  18733. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  18734. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  18735. if (typeof bound == "string") { bound = commands[bound]; }
  18736. if (!bound) { return false }
  18737. var done = false;
  18738. try {
  18739. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  18740. done = bound(cm, pos) != Pass;
  18741. } finally {
  18742. cm.state.suppressEdits = false;
  18743. }
  18744. return done
  18745. })
  18746. }
  18747. function configureMouse(cm, repeat, event) {
  18748. var option = cm.getOption("configureMouse");
  18749. var value = option ? option(cm, repeat, event) : {};
  18750. if (value.unit == null) {
  18751. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  18752. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  18753. }
  18754. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  18755. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  18756. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  18757. return value
  18758. }
  18759. function leftButtonDown(cm, pos, repeat, event) {
  18760. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  18761. else { cm.curOp.focus = activeElt(); }
  18762. var behavior = configureMouse(cm, repeat, event);
  18763. var sel = cm.doc.sel, contained;
  18764. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  18765. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  18766. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  18767. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  18768. { leftButtonStartDrag(cm, event, pos, behavior); }
  18769. else
  18770. { leftButtonSelect(cm, event, pos, behavior); }
  18771. }
  18772. // Start a text drag. When it ends, see if any dragging actually
  18773. // happen, and treat as a click if it didn't.
  18774. function leftButtonStartDrag(cm, event, pos, behavior) {
  18775. var display = cm.display, moved = false;
  18776. var dragEnd = operation(cm, function (e) {
  18777. if (webkit) { display.scroller.draggable = false; }
  18778. cm.state.draggingText = false;
  18779. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  18780. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  18781. off(display.scroller, "dragstart", dragStart);
  18782. off(display.scroller, "drop", dragEnd);
  18783. if (!moved) {
  18784. e_preventDefault(e);
  18785. if (!behavior.addNew)
  18786. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  18787. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  18788. if ((webkit && !safari) || ie && ie_version == 9)
  18789. { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
  18790. else
  18791. { display.input.focus(); }
  18792. }
  18793. });
  18794. var mouseMove = function(e2) {
  18795. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  18796. };
  18797. var dragStart = function () { return moved = true; };
  18798. // Let the drag handler handle this.
  18799. if (webkit) { display.scroller.draggable = true; }
  18800. cm.state.draggingText = dragEnd;
  18801. dragEnd.copy = !behavior.moveOnDrag;
  18802. // IE's approach to draggable
  18803. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  18804. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  18805. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  18806. on(display.scroller, "dragstart", dragStart);
  18807. on(display.scroller, "drop", dragEnd);
  18808. delayBlurEvent(cm);
  18809. setTimeout(function () { return display.input.focus(); }, 20);
  18810. }
  18811. function rangeForUnit(cm, pos, unit) {
  18812. if (unit == "char") { return new Range(pos, pos) }
  18813. if (unit == "word") { return cm.findWordAt(pos) }
  18814. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  18815. var result = unit(cm, pos);
  18816. return new Range(result.from, result.to)
  18817. }
  18818. // Normal selection, as opposed to text dragging.
  18819. function leftButtonSelect(cm, event, start, behavior) {
  18820. var display = cm.display, doc = cm.doc;
  18821. e_preventDefault(event);
  18822. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  18823. if (behavior.addNew && !behavior.extend) {
  18824. ourIndex = doc.sel.contains(start);
  18825. if (ourIndex > -1)
  18826. { ourRange = ranges[ourIndex]; }
  18827. else
  18828. { ourRange = new Range(start, start); }
  18829. } else {
  18830. ourRange = doc.sel.primary();
  18831. ourIndex = doc.sel.primIndex;
  18832. }
  18833. if (behavior.unit == "rectangle") {
  18834. if (!behavior.addNew) { ourRange = new Range(start, start); }
  18835. start = posFromMouse(cm, event, true, true);
  18836. ourIndex = -1;
  18837. } else {
  18838. var range = rangeForUnit(cm, start, behavior.unit);
  18839. if (behavior.extend)
  18840. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  18841. else
  18842. { ourRange = range; }
  18843. }
  18844. if (!behavior.addNew) {
  18845. ourIndex = 0;
  18846. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  18847. startSel = doc.sel;
  18848. } else if (ourIndex == -1) {
  18849. ourIndex = ranges.length;
  18850. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  18851. {scroll: false, origin: "*mouse"});
  18852. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  18853. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  18854. {scroll: false, origin: "*mouse"});
  18855. startSel = doc.sel;
  18856. } else {
  18857. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  18858. }
  18859. var lastPos = start;
  18860. function extendTo(pos) {
  18861. if (cmp(lastPos, pos) == 0) { return }
  18862. lastPos = pos;
  18863. if (behavior.unit == "rectangle") {
  18864. var ranges = [], tabSize = cm.options.tabSize;
  18865. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  18866. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  18867. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  18868. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  18869. line <= end; line++) {
  18870. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  18871. if (left == right)
  18872. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  18873. else if (text.length > leftPos)
  18874. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  18875. }
  18876. if (!ranges.length) { ranges.push(new Range(start, start)); }
  18877. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  18878. {origin: "*mouse", scroll: false});
  18879. cm.scrollIntoView(pos);
  18880. } else {
  18881. var oldRange = ourRange;
  18882. var range = rangeForUnit(cm, pos, behavior.unit);
  18883. var anchor = oldRange.anchor, head;
  18884. if (cmp(range.anchor, anchor) > 0) {
  18885. head = range.head;
  18886. anchor = minPos(oldRange.from(), range.anchor);
  18887. } else {
  18888. head = range.anchor;
  18889. anchor = maxPos(oldRange.to(), range.head);
  18890. }
  18891. var ranges$1 = startSel.ranges.slice(0);
  18892. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  18893. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  18894. }
  18895. }
  18896. var editorSize = display.wrapper.getBoundingClientRect();
  18897. // Used to ensure timeout re-tries don't fire when another extend
  18898. // happened in the meantime (clearTimeout isn't reliable -- at
  18899. // least on Chrome, the timeouts still happen even when cleared,
  18900. // if the clear happens after their scheduled firing time).
  18901. var counter = 0;
  18902. function extend(e) {
  18903. var curCount = ++counter;
  18904. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  18905. if (!cur) { return }
  18906. if (cmp(cur, lastPos) != 0) {
  18907. cm.curOp.focus = activeElt();
  18908. extendTo(cur);
  18909. var visible = visibleLines(display, doc);
  18910. if (cur.line >= visible.to || cur.line < visible.from)
  18911. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  18912. } else {
  18913. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  18914. if (outside) { setTimeout(operation(cm, function () {
  18915. if (counter != curCount) { return }
  18916. display.scroller.scrollTop += outside;
  18917. extend(e);
  18918. }), 50); }
  18919. }
  18920. }
  18921. function done(e) {
  18922. cm.state.selectingText = false;
  18923. counter = Infinity;
  18924. // If e is null or undefined we interpret this as someone trying
  18925. // to explicitly cancel the selection rather than the user
  18926. // letting go of the mouse button.
  18927. if (e) {
  18928. e_preventDefault(e);
  18929. display.input.focus();
  18930. }
  18931. off(display.wrapper.ownerDocument, "mousemove", move);
  18932. off(display.wrapper.ownerDocument, "mouseup", up);
  18933. doc.history.lastSelOrigin = null;
  18934. }
  18935. var move = operation(cm, function (e) {
  18936. if (e.buttons === 0 || !e_button(e)) { done(e); }
  18937. else { extend(e); }
  18938. });
  18939. var up = operation(cm, done);
  18940. cm.state.selectingText = up;
  18941. on(display.wrapper.ownerDocument, "mousemove", move);
  18942. on(display.wrapper.ownerDocument, "mouseup", up);
  18943. }
  18944. // Used when mouse-selecting to adjust the anchor to the proper side
  18945. // of a bidi jump depending on the visual position of the head.
  18946. function bidiSimplify(cm, range) {
  18947. var anchor = range.anchor;
  18948. var head = range.head;
  18949. var anchorLine = getLine(cm.doc, anchor.line);
  18950. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  18951. var order = getOrder(anchorLine);
  18952. if (!order) { return range }
  18953. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  18954. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  18955. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  18956. if (boundary == 0 || boundary == order.length) { return range }
  18957. // Compute the relative visual position of the head compared to the
  18958. // anchor (<0 is to the left, >0 to the right)
  18959. var leftSide;
  18960. if (head.line != anchor.line) {
  18961. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  18962. } else {
  18963. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  18964. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  18965. if (headIndex == boundary - 1 || headIndex == boundary)
  18966. { leftSide = dir < 0; }
  18967. else
  18968. { leftSide = dir > 0; }
  18969. }
  18970. var usePart = order[boundary + (leftSide ? -1 : 0)];
  18971. var from = leftSide == (usePart.level == 1);
  18972. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  18973. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  18974. }
  18975. // Determines whether an event happened in the gutter, and fires the
  18976. // handlers for the corresponding event.
  18977. function gutterEvent(cm, e, type, prevent) {
  18978. var mX, mY;
  18979. if (e.touches) {
  18980. mX = e.touches[0].clientX;
  18981. mY = e.touches[0].clientY;
  18982. } else {
  18983. try { mX = e.clientX; mY = e.clientY; }
  18984. catch(e) { return false }
  18985. }
  18986. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  18987. if (prevent) { e_preventDefault(e); }
  18988. var display = cm.display;
  18989. var lineBox = display.lineDiv.getBoundingClientRect();
  18990. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  18991. mY -= lineBox.top - display.viewOffset;
  18992. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  18993. var g = display.gutters.childNodes[i];
  18994. if (g && g.getBoundingClientRect().right >= mX) {
  18995. var line = lineAtHeight(cm.doc, mY);
  18996. var gutter = cm.display.gutterSpecs[i];
  18997. signal(cm, type, cm, line, gutter.className, e);
  18998. return e_defaultPrevented(e)
  18999. }
  19000. }
  19001. }
  19002. function clickInGutter(cm, e) {
  19003. return gutterEvent(cm, e, "gutterClick", true)
  19004. }
  19005. // CONTEXT MENU HANDLING
  19006. // To make the context menu work, we need to briefly unhide the
  19007. // textarea (making it as unobtrusive as possible) to let the
  19008. // right-click take effect on it.
  19009. function onContextMenu(cm, e) {
  19010. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  19011. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  19012. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  19013. }
  19014. function contextMenuInGutter(cm, e) {
  19015. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  19016. return gutterEvent(cm, e, "gutterContextMenu", false)
  19017. }
  19018. function themeChanged(cm) {
  19019. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  19020. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  19021. clearCaches(cm);
  19022. }
  19023. var Init = {toString: function(){return "CodeMirror.Init"}};
  19024. var defaults = {};
  19025. var optionHandlers = {};
  19026. function defineOptions(CodeMirror) {
  19027. var optionHandlers = CodeMirror.optionHandlers;
  19028. function option(name, deflt, handle, notOnInit) {
  19029. CodeMirror.defaults[name] = deflt;
  19030. if (handle) { optionHandlers[name] =
  19031. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  19032. }
  19033. CodeMirror.defineOption = option;
  19034. // Passed to option handlers when there is no old value.
  19035. CodeMirror.Init = Init;
  19036. // These two are, on init, called from the constructor because they
  19037. // have to be initialized before the editor can start at all.
  19038. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  19039. option("mode", null, function (cm, val) {
  19040. cm.doc.modeOption = val;
  19041. loadMode(cm);
  19042. }, true);
  19043. option("indentUnit", 2, loadMode, true);
  19044. option("indentWithTabs", false);
  19045. option("smartIndent", true);
  19046. option("tabSize", 4, function (cm) {
  19047. resetModeState(cm);
  19048. clearCaches(cm);
  19049. regChange(cm);
  19050. }, true);
  19051. option("lineSeparator", null, function (cm, val) {
  19052. cm.doc.lineSep = val;
  19053. if (!val) { return }
  19054. var newBreaks = [], lineNo = cm.doc.first;
  19055. cm.doc.iter(function (line) {
  19056. for (var pos = 0;;) {
  19057. var found = line.text.indexOf(val, pos);
  19058. if (found == -1) { break }
  19059. pos = found + val.length;
  19060. newBreaks.push(Pos(lineNo, found));
  19061. }
  19062. lineNo++;
  19063. });
  19064. for (var i = newBreaks.length - 1; i >= 0; i--)
  19065. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  19066. });
  19067. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  19068. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  19069. if (old != Init) { cm.refresh(); }
  19070. });
  19071. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  19072. option("electricChars", true);
  19073. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  19074. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  19075. }, true);
  19076. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  19077. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  19078. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  19079. option("rtlMoveVisually", !windows);
  19080. option("wholeLineUpdateBefore", true);
  19081. option("theme", "default", function (cm) {
  19082. themeChanged(cm);
  19083. updateGutters(cm);
  19084. }, true);
  19085. option("keyMap", "default", function (cm, val, old) {
  19086. var next = getKeyMap(val);
  19087. var prev = old != Init && getKeyMap(old);
  19088. if (prev && prev.detach) { prev.detach(cm, next); }
  19089. if (next.attach) { next.attach(cm, prev || null); }
  19090. });
  19091. option("extraKeys", null);
  19092. option("configureMouse", null);
  19093. option("lineWrapping", false, wrappingChanged, true);
  19094. option("gutters", [], function (cm, val) {
  19095. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  19096. updateGutters(cm);
  19097. }, true);
  19098. option("fixedGutter", true, function (cm, val) {
  19099. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  19100. cm.refresh();
  19101. }, true);
  19102. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  19103. option("scrollbarStyle", "native", function (cm) {
  19104. initScrollbars(cm);
  19105. updateScrollbars(cm);
  19106. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  19107. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  19108. }, true);
  19109. option("lineNumbers", false, function (cm, val) {
  19110. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  19111. updateGutters(cm);
  19112. }, true);
  19113. option("firstLineNumber", 1, updateGutters, true);
  19114. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  19115. option("showCursorWhenSelecting", false, updateSelection, true);
  19116. option("resetSelectionOnContextMenu", true);
  19117. option("lineWiseCopyCut", true);
  19118. option("pasteLinesPerSelection", true);
  19119. option("selectionsMayTouch", false);
  19120. option("readOnly", false, function (cm, val) {
  19121. if (val == "nocursor") {
  19122. onBlur(cm);
  19123. cm.display.input.blur();
  19124. }
  19125. cm.display.input.readOnlyChanged(val);
  19126. });
  19127. option("screenReaderLabel", null, function (cm, val) {
  19128. val = (val === '') ? null : val;
  19129. cm.display.input.screenReaderLabelChanged(val);
  19130. });
  19131. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  19132. option("dragDrop", true, dragDropChanged);
  19133. option("allowDropFileTypes", null);
  19134. option("cursorBlinkRate", 530);
  19135. option("cursorScrollMargin", 0);
  19136. option("cursorHeight", 1, updateSelection, true);
  19137. option("singleCursorHeightPerLine", true, updateSelection, true);
  19138. option("workTime", 100);
  19139. option("workDelay", 100);
  19140. option("flattenSpans", true, resetModeState, true);
  19141. option("addModeClass", false, resetModeState, true);
  19142. option("pollInterval", 100);
  19143. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  19144. option("historyEventDelay", 1250);
  19145. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  19146. option("maxHighlightLength", 10000, resetModeState, true);
  19147. option("moveInputWithCursor", true, function (cm, val) {
  19148. if (!val) { cm.display.input.resetPosition(); }
  19149. });
  19150. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  19151. option("autofocus", null);
  19152. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  19153. option("phrases", null);
  19154. }
  19155. function dragDropChanged(cm, value, old) {
  19156. var wasOn = old && old != Init;
  19157. if (!value != !wasOn) {
  19158. var funcs = cm.display.dragFunctions;
  19159. var toggle = value ? on : off;
  19160. toggle(cm.display.scroller, "dragstart", funcs.start);
  19161. toggle(cm.display.scroller, "dragenter", funcs.enter);
  19162. toggle(cm.display.scroller, "dragover", funcs.over);
  19163. toggle(cm.display.scroller, "dragleave", funcs.leave);
  19164. toggle(cm.display.scroller, "drop", funcs.drop);
  19165. }
  19166. }
  19167. function wrappingChanged(cm) {
  19168. if (cm.options.lineWrapping) {
  19169. addClass(cm.display.wrapper, "CodeMirror-wrap");
  19170. cm.display.sizer.style.minWidth = "";
  19171. cm.display.sizerWidth = null;
  19172. } else {
  19173. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  19174. findMaxLine(cm);
  19175. }
  19176. estimateLineHeights(cm);
  19177. regChange(cm);
  19178. clearCaches(cm);
  19179. setTimeout(function () { return updateScrollbars(cm); }, 100);
  19180. }
  19181. // A CodeMirror instance represents an editor. This is the object
  19182. // that user code is usually dealing with.
  19183. function CodeMirror(place, options) {
  19184. var this$1 = this;
  19185. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  19186. this.options = options = options ? copyObj(options) : {};
  19187. // Determine effective options based on given values and defaults.
  19188. copyObj(defaults, options, false);
  19189. var doc = options.value;
  19190. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  19191. else if (options.mode) { doc.modeOption = options.mode; }
  19192. this.doc = doc;
  19193. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  19194. var display = this.display = new Display(place, doc, input, options);
  19195. display.wrapper.CodeMirror = this;
  19196. themeChanged(this);
  19197. if (options.lineWrapping)
  19198. { this.display.wrapper.className += " CodeMirror-wrap"; }
  19199. initScrollbars(this);
  19200. this.state = {
  19201. keyMaps: [], // stores maps added by addKeyMap
  19202. overlays: [], // highlighting overlays, as added by addOverlay
  19203. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  19204. overwrite: false,
  19205. delayingBlurEvent: false,
  19206. focused: false,
  19207. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  19208. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  19209. selectingText: false,
  19210. draggingText: false,
  19211. highlight: new Delayed(), // stores highlight worker timeout
  19212. keySeq: null, // Unfinished key sequence
  19213. specialChars: null
  19214. };
  19215. if (options.autofocus && !mobile) { display.input.focus(); }
  19216. // Override magic textarea content restore that IE sometimes does
  19217. // on our hidden textarea on reload
  19218. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  19219. registerEventHandlers(this);
  19220. ensureGlobalHandlers();
  19221. startOperation(this);
  19222. this.curOp.forceUpdate = true;
  19223. attachDoc(this, doc);
  19224. if ((options.autofocus && !mobile) || this.hasFocus())
  19225. { setTimeout(bind(onFocus, this), 20); }
  19226. else
  19227. { onBlur(this); }
  19228. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  19229. { optionHandlers[opt](this, options[opt], Init); } }
  19230. maybeUpdateLineNumberWidth(this);
  19231. if (options.finishInit) { options.finishInit(this); }
  19232. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  19233. endOperation(this);
  19234. // Suppress optimizelegibility in Webkit, since it breaks text
  19235. // measuring on line wrapping boundaries.
  19236. if (webkit && options.lineWrapping &&
  19237. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  19238. { display.lineDiv.style.textRendering = "auto"; }
  19239. }
  19240. // The default configuration options.
  19241. CodeMirror.defaults = defaults;
  19242. // Functions to run when options are changed.
  19243. CodeMirror.optionHandlers = optionHandlers;
  19244. // Attach the necessary event handlers when initializing the editor
  19245. function registerEventHandlers(cm) {
  19246. var d = cm.display;
  19247. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  19248. // Older IE's will not fire a second mousedown for a double click
  19249. if (ie && ie_version < 11)
  19250. { on(d.scroller, "dblclick", operation(cm, function (e) {
  19251. if (signalDOMEvent(cm, e)) { return }
  19252. var pos = posFromMouse(cm, e);
  19253. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  19254. e_preventDefault(e);
  19255. var word = cm.findWordAt(pos);
  19256. extendSelection(cm.doc, word.anchor, word.head);
  19257. })); }
  19258. else
  19259. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  19260. // Some browsers fire contextmenu *after* opening the menu, at
  19261. // which point we can't mess with it anymore. Context menu is
  19262. // handled in onMouseDown for these browsers.
  19263. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  19264. on(d.input.getField(), "contextmenu", function (e) {
  19265. if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  19266. });
  19267. // Used to suppress mouse event handling when a touch happens
  19268. var touchFinished, prevTouch = {end: 0};
  19269. function finishTouch() {
  19270. if (d.activeTouch) {
  19271. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  19272. prevTouch = d.activeTouch;
  19273. prevTouch.end = +new Date;
  19274. }
  19275. }
  19276. function isMouseLikeTouchEvent(e) {
  19277. if (e.touches.length != 1) { return false }
  19278. var touch = e.touches[0];
  19279. return touch.radiusX <= 1 && touch.radiusY <= 1
  19280. }
  19281. function farAway(touch, other) {
  19282. if (other.left == null) { return true }
  19283. var dx = other.left - touch.left, dy = other.top - touch.top;
  19284. return dx * dx + dy * dy > 20 * 20
  19285. }
  19286. on(d.scroller, "touchstart", function (e) {
  19287. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  19288. d.input.ensurePolled();
  19289. clearTimeout(touchFinished);
  19290. var now = +new Date;
  19291. d.activeTouch = {start: now, moved: false,
  19292. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  19293. if (e.touches.length == 1) {
  19294. d.activeTouch.left = e.touches[0].pageX;
  19295. d.activeTouch.top = e.touches[0].pageY;
  19296. }
  19297. }
  19298. });
  19299. on(d.scroller, "touchmove", function () {
  19300. if (d.activeTouch) { d.activeTouch.moved = true; }
  19301. });
  19302. on(d.scroller, "touchend", function (e) {
  19303. var touch = d.activeTouch;
  19304. if (touch && !eventInWidget(d, e) && touch.left != null &&
  19305. !touch.moved && new Date - touch.start < 300) {
  19306. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  19307. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  19308. { range = new Range(pos, pos); }
  19309. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  19310. { range = cm.findWordAt(pos); }
  19311. else // Triple tap
  19312. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  19313. cm.setSelection(range.anchor, range.head);
  19314. cm.focus();
  19315. e_preventDefault(e);
  19316. }
  19317. finishTouch();
  19318. });
  19319. on(d.scroller, "touchcancel", finishTouch);
  19320. // Sync scrolling between fake scrollbars and real scrollable
  19321. // area, ensure viewport is updated when scrolling.
  19322. on(d.scroller, "scroll", function () {
  19323. if (d.scroller.clientHeight) {
  19324. updateScrollTop(cm, d.scroller.scrollTop);
  19325. setScrollLeft(cm, d.scroller.scrollLeft, true);
  19326. signal(cm, "scroll", cm);
  19327. }
  19328. });
  19329. // Listen to wheel events in order to try and update the viewport on time.
  19330. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  19331. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  19332. // Prevent wrapper from ever scrolling
  19333. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  19334. d.dragFunctions = {
  19335. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  19336. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  19337. start: function (e) { return onDragStart(cm, e); },
  19338. drop: operation(cm, onDrop),
  19339. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  19340. };
  19341. var inp = d.input.getField();
  19342. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  19343. on(inp, "keydown", operation(cm, onKeyDown));
  19344. on(inp, "keypress", operation(cm, onKeyPress));
  19345. on(inp, "focus", function (e) { return onFocus(cm, e); });
  19346. on(inp, "blur", function (e) { return onBlur(cm, e); });
  19347. }
  19348. var initHooks = [];
  19349. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  19350. // Indent the given line. The how parameter can be "smart",
  19351. // "add"/null, "subtract", or "prev". When aggressive is false
  19352. // (typically set to true for forced single-line indents), empty
  19353. // lines are not indented, and places where the mode returns Pass
  19354. // are left alone.
  19355. function indentLine(cm, n, how, aggressive) {
  19356. var doc = cm.doc, state;
  19357. if (how == null) { how = "add"; }
  19358. if (how == "smart") {
  19359. // Fall back to "prev" when the mode doesn't have an indentation
  19360. // method.
  19361. if (!doc.mode.indent) { how = "prev"; }
  19362. else { state = getContextBefore(cm, n).state; }
  19363. }
  19364. var tabSize = cm.options.tabSize;
  19365. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  19366. if (line.stateAfter) { line.stateAfter = null; }
  19367. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  19368. if (!aggressive && !/\S/.test(line.text)) {
  19369. indentation = 0;
  19370. how = "not";
  19371. } else if (how == "smart") {
  19372. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  19373. if (indentation == Pass || indentation > 150) {
  19374. if (!aggressive) { return }
  19375. how = "prev";
  19376. }
  19377. }
  19378. if (how == "prev") {
  19379. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  19380. else { indentation = 0; }
  19381. } else if (how == "add") {
  19382. indentation = curSpace + cm.options.indentUnit;
  19383. } else if (how == "subtract") {
  19384. indentation = curSpace - cm.options.indentUnit;
  19385. } else if (typeof how == "number") {
  19386. indentation = curSpace + how;
  19387. }
  19388. indentation = Math.max(0, indentation);
  19389. var indentString = "", pos = 0;
  19390. if (cm.options.indentWithTabs)
  19391. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  19392. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  19393. if (indentString != curSpaceString) {
  19394. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  19395. line.stateAfter = null;
  19396. return true
  19397. } else {
  19398. // Ensure that, if the cursor was in the whitespace at the start
  19399. // of the line, it is moved to the end of that space.
  19400. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  19401. var range = doc.sel.ranges[i$1];
  19402. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  19403. var pos$1 = Pos(n, curSpaceString.length);
  19404. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  19405. break
  19406. }
  19407. }
  19408. }
  19409. }
  19410. // This will be set to a {lineWise: bool, text: [string]} object, so
  19411. // that, when pasting, we know what kind of selections the copied
  19412. // text was made out of.
  19413. var lastCopied = null;
  19414. function setLastCopied(newLastCopied) {
  19415. lastCopied = newLastCopied;
  19416. }
  19417. function applyTextInput(cm, inserted, deleted, sel, origin) {
  19418. var doc = cm.doc;
  19419. cm.display.shift = false;
  19420. if (!sel) { sel = doc.sel; }
  19421. var recent = +new Date - 200;
  19422. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  19423. var textLines = splitLinesAuto(inserted), multiPaste = null;
  19424. // When pasting N lines into N selections, insert one line per selection
  19425. if (paste && sel.ranges.length > 1) {
  19426. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  19427. if (sel.ranges.length % lastCopied.text.length == 0) {
  19428. multiPaste = [];
  19429. for (var i = 0; i < lastCopied.text.length; i++)
  19430. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  19431. }
  19432. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  19433. multiPaste = map(textLines, function (l) { return [l]; });
  19434. }
  19435. }
  19436. var updateInput = cm.curOp.updateInput;
  19437. // Normal behavior is to insert the new text into every selection
  19438. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  19439. var range = sel.ranges[i$1];
  19440. var from = range.from(), to = range.to();
  19441. if (range.empty()) {
  19442. if (deleted && deleted > 0) // Handle deletion
  19443. { from = Pos(from.line, from.ch - deleted); }
  19444. else if (cm.state.overwrite && !paste) // Handle overwrite
  19445. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  19446. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  19447. { from = to = Pos(from.line, 0); }
  19448. }
  19449. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  19450. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  19451. makeChange(cm.doc, changeEvent);
  19452. signalLater(cm, "inputRead", cm, changeEvent);
  19453. }
  19454. if (inserted && !paste)
  19455. { triggerElectric(cm, inserted); }
  19456. ensureCursorVisible(cm);
  19457. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  19458. cm.curOp.typing = true;
  19459. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  19460. }
  19461. function handlePaste(e, cm) {
  19462. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  19463. if (pasted) {
  19464. e.preventDefault();
  19465. if (!cm.isReadOnly() && !cm.options.disableInput)
  19466. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  19467. return true
  19468. }
  19469. }
  19470. function triggerElectric(cm, inserted) {
  19471. // When an 'electric' character is inserted, immediately trigger a reindent
  19472. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  19473. var sel = cm.doc.sel;
  19474. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  19475. var range = sel.ranges[i];
  19476. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  19477. var mode = cm.getModeAt(range.head);
  19478. var indented = false;
  19479. if (mode.electricChars) {
  19480. for (var j = 0; j < mode.electricChars.length; j++)
  19481. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  19482. indented = indentLine(cm, range.head.line, "smart");
  19483. break
  19484. } }
  19485. } else if (mode.electricInput) {
  19486. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  19487. { indented = indentLine(cm, range.head.line, "smart"); }
  19488. }
  19489. if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  19490. }
  19491. }
  19492. function copyableRanges(cm) {
  19493. var text = [], ranges = [];
  19494. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  19495. var line = cm.doc.sel.ranges[i].head.line;
  19496. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  19497. ranges.push(lineRange);
  19498. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  19499. }
  19500. return {text: text, ranges: ranges}
  19501. }
  19502. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  19503. field.setAttribute("autocorrect", autocorrect ? "" : "off");
  19504. field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  19505. field.setAttribute("spellcheck", !!spellcheck);
  19506. }
  19507. function hiddenTextarea() {
  19508. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  19509. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  19510. // The textarea is kept positioned near the cursor to prevent the
  19511. // fact that it'll be scrolled into view on input from scrolling
  19512. // our fake cursor out of view. On webkit, when wrap=off, paste is
  19513. // very slow. So make the area wide instead.
  19514. if (webkit) { te.style.width = "1000px"; }
  19515. else { te.setAttribute("wrap", "off"); }
  19516. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  19517. if (ios) { te.style.border = "1px solid black"; }
  19518. disableBrowserMagic(te);
  19519. return div
  19520. }
  19521. // The publicly visible API. Note that methodOp(f) means
  19522. // 'wrap f in an operation, performed on its `this` parameter'.
  19523. // This is not the complete set of editor methods. Most of the
  19524. // methods defined on the Doc type are also injected into
  19525. // CodeMirror.prototype, for backwards compatibility and
  19526. // convenience.
  19527. function addEditorMethods(CodeMirror) {
  19528. var optionHandlers = CodeMirror.optionHandlers;
  19529. var helpers = CodeMirror.helpers = {};
  19530. CodeMirror.prototype = {
  19531. constructor: CodeMirror,
  19532. focus: function(){window.focus(); this.display.input.focus();},
  19533. setOption: function(option, value) {
  19534. var options = this.options, old = options[option];
  19535. if (options[option] == value && option != "mode") { return }
  19536. options[option] = value;
  19537. if (optionHandlers.hasOwnProperty(option))
  19538. { operation(this, optionHandlers[option])(this, value, old); }
  19539. signal(this, "optionChange", this, option);
  19540. },
  19541. getOption: function(option) {return this.options[option]},
  19542. getDoc: function() {return this.doc},
  19543. addKeyMap: function(map, bottom) {
  19544. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  19545. },
  19546. removeKeyMap: function(map) {
  19547. var maps = this.state.keyMaps;
  19548. for (var i = 0; i < maps.length; ++i)
  19549. { if (maps[i] == map || maps[i].name == map) {
  19550. maps.splice(i, 1);
  19551. return true
  19552. } }
  19553. },
  19554. addOverlay: methodOp(function(spec, options) {
  19555. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  19556. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  19557. insertSorted(this.state.overlays,
  19558. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  19559. priority: (options && options.priority) || 0},
  19560. function (overlay) { return overlay.priority; });
  19561. this.state.modeGen++;
  19562. regChange(this);
  19563. }),
  19564. removeOverlay: methodOp(function(spec) {
  19565. var overlays = this.state.overlays;
  19566. for (var i = 0; i < overlays.length; ++i) {
  19567. var cur = overlays[i].modeSpec;
  19568. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  19569. overlays.splice(i, 1);
  19570. this.state.modeGen++;
  19571. regChange(this);
  19572. return
  19573. }
  19574. }
  19575. }),
  19576. indentLine: methodOp(function(n, dir, aggressive) {
  19577. if (typeof dir != "string" && typeof dir != "number") {
  19578. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  19579. else { dir = dir ? "add" : "subtract"; }
  19580. }
  19581. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  19582. }),
  19583. indentSelection: methodOp(function(how) {
  19584. var ranges = this.doc.sel.ranges, end = -1;
  19585. for (var i = 0; i < ranges.length; i++) {
  19586. var range = ranges[i];
  19587. if (!range.empty()) {
  19588. var from = range.from(), to = range.to();
  19589. var start = Math.max(end, from.line);
  19590. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  19591. for (var j = start; j < end; ++j)
  19592. { indentLine(this, j, how); }
  19593. var newRanges = this.doc.sel.ranges;
  19594. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  19595. { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  19596. } else if (range.head.line > end) {
  19597. indentLine(this, range.head.line, how, true);
  19598. end = range.head.line;
  19599. if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  19600. }
  19601. }
  19602. }),
  19603. // Fetch the parser token for a given character. Useful for hacks
  19604. // that want to inspect the mode state (say, for completion).
  19605. getTokenAt: function(pos, precise) {
  19606. return takeToken(this, pos, precise)
  19607. },
  19608. getLineTokens: function(line, precise) {
  19609. return takeToken(this, Pos(line), precise, true)
  19610. },
  19611. getTokenTypeAt: function(pos) {
  19612. pos = clipPos(this.doc, pos);
  19613. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  19614. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  19615. var type;
  19616. if (ch == 0) { type = styles[2]; }
  19617. else { for (;;) {
  19618. var mid = (before + after) >> 1;
  19619. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  19620. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  19621. else { type = styles[mid * 2 + 2]; break }
  19622. } }
  19623. var cut = type ? type.indexOf("overlay ") : -1;
  19624. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  19625. },
  19626. getModeAt: function(pos) {
  19627. var mode = this.doc.mode;
  19628. if (!mode.innerMode) { return mode }
  19629. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  19630. },
  19631. getHelper: function(pos, type) {
  19632. return this.getHelpers(pos, type)[0]
  19633. },
  19634. getHelpers: function(pos, type) {
  19635. var found = [];
  19636. if (!helpers.hasOwnProperty(type)) { return found }
  19637. var help = helpers[type], mode = this.getModeAt(pos);
  19638. if (typeof mode[type] == "string") {
  19639. if (help[mode[type]]) { found.push(help[mode[type]]); }
  19640. } else if (mode[type]) {
  19641. for (var i = 0; i < mode[type].length; i++) {
  19642. var val = help[mode[type][i]];
  19643. if (val) { found.push(val); }
  19644. }
  19645. } else if (mode.helperType && help[mode.helperType]) {
  19646. found.push(help[mode.helperType]);
  19647. } else if (help[mode.name]) {
  19648. found.push(help[mode.name]);
  19649. }
  19650. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  19651. var cur = help._global[i$1];
  19652. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  19653. { found.push(cur.val); }
  19654. }
  19655. return found
  19656. },
  19657. getStateAfter: function(line, precise) {
  19658. var doc = this.doc;
  19659. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  19660. return getContextBefore(this, line + 1, precise).state
  19661. },
  19662. cursorCoords: function(start, mode) {
  19663. var pos, range = this.doc.sel.primary();
  19664. if (start == null) { pos = range.head; }
  19665. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  19666. else { pos = start ? range.from() : range.to(); }
  19667. return cursorCoords(this, pos, mode || "page")
  19668. },
  19669. charCoords: function(pos, mode) {
  19670. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  19671. },
  19672. coordsChar: function(coords, mode) {
  19673. coords = fromCoordSystem(this, coords, mode || "page");
  19674. return coordsChar(this, coords.left, coords.top)
  19675. },
  19676. lineAtHeight: function(height, mode) {
  19677. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  19678. return lineAtHeight(this.doc, height + this.display.viewOffset)
  19679. },
  19680. heightAtLine: function(line, mode, includeWidgets) {
  19681. var end = false, lineObj;
  19682. if (typeof line == "number") {
  19683. var last = this.doc.first + this.doc.size - 1;
  19684. if (line < this.doc.first) { line = this.doc.first; }
  19685. else if (line > last) { line = last; end = true; }
  19686. lineObj = getLine(this.doc, line);
  19687. } else {
  19688. lineObj = line;
  19689. }
  19690. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  19691. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  19692. },
  19693. defaultTextHeight: function() { return textHeight(this.display) },
  19694. defaultCharWidth: function() { return charWidth(this.display) },
  19695. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  19696. addWidget: function(pos, node, scroll, vert, horiz) {
  19697. var display = this.display;
  19698. pos = cursorCoords(this, clipPos(this.doc, pos));
  19699. var top = pos.bottom, left = pos.left;
  19700. node.style.position = "absolute";
  19701. node.setAttribute("cm-ignore-events", "true");
  19702. this.display.input.setUneditable(node);
  19703. display.sizer.appendChild(node);
  19704. if (vert == "over") {
  19705. top = pos.top;
  19706. } else if (vert == "above" || vert == "near") {
  19707. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  19708. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  19709. // Default to positioning above (if specified and possible); otherwise default to positioning below
  19710. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  19711. { top = pos.top - node.offsetHeight; }
  19712. else if (pos.bottom + node.offsetHeight <= vspace)
  19713. { top = pos.bottom; }
  19714. if (left + node.offsetWidth > hspace)
  19715. { left = hspace - node.offsetWidth; }
  19716. }
  19717. node.style.top = top + "px";
  19718. node.style.left = node.style.right = "";
  19719. if (horiz == "right") {
  19720. left = display.sizer.clientWidth - node.offsetWidth;
  19721. node.style.right = "0px";
  19722. } else {
  19723. if (horiz == "left") { left = 0; }
  19724. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  19725. node.style.left = left + "px";
  19726. }
  19727. if (scroll)
  19728. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  19729. },
  19730. triggerOnKeyDown: methodOp(onKeyDown),
  19731. triggerOnKeyPress: methodOp(onKeyPress),
  19732. triggerOnKeyUp: onKeyUp,
  19733. triggerOnMouseDown: methodOp(onMouseDown),
  19734. execCommand: function(cmd) {
  19735. if (commands.hasOwnProperty(cmd))
  19736. { return commands[cmd].call(null, this) }
  19737. },
  19738. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  19739. findPosH: function(from, amount, unit, visually) {
  19740. var dir = 1;
  19741. if (amount < 0) { dir = -1; amount = -amount; }
  19742. var cur = clipPos(this.doc, from);
  19743. for (var i = 0; i < amount; ++i) {
  19744. cur = findPosH(this.doc, cur, dir, unit, visually);
  19745. if (cur.hitSide) { break }
  19746. }
  19747. return cur
  19748. },
  19749. moveH: methodOp(function(dir, unit) {
  19750. var this$1 = this;
  19751. this.extendSelectionsBy(function (range) {
  19752. if (this$1.display.shift || this$1.doc.extend || range.empty())
  19753. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  19754. else
  19755. { return dir < 0 ? range.from() : range.to() }
  19756. }, sel_move);
  19757. }),
  19758. deleteH: methodOp(function(dir, unit) {
  19759. var sel = this.doc.sel, doc = this.doc;
  19760. if (sel.somethingSelected())
  19761. { doc.replaceSelection("", null, "+delete"); }
  19762. else
  19763. { deleteNearSelection(this, function (range) {
  19764. var other = findPosH(doc, range.head, dir, unit, false);
  19765. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  19766. }); }
  19767. }),
  19768. findPosV: function(from, amount, unit, goalColumn) {
  19769. var dir = 1, x = goalColumn;
  19770. if (amount < 0) { dir = -1; amount = -amount; }
  19771. var cur = clipPos(this.doc, from);
  19772. for (var i = 0; i < amount; ++i) {
  19773. var coords = cursorCoords(this, cur, "div");
  19774. if (x == null) { x = coords.left; }
  19775. else { coords.left = x; }
  19776. cur = findPosV(this, coords, dir, unit);
  19777. if (cur.hitSide) { break }
  19778. }
  19779. return cur
  19780. },
  19781. moveV: methodOp(function(dir, unit) {
  19782. var this$1 = this;
  19783. var doc = this.doc, goals = [];
  19784. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  19785. doc.extendSelectionsBy(function (range) {
  19786. if (collapse)
  19787. { return dir < 0 ? range.from() : range.to() }
  19788. var headPos = cursorCoords(this$1, range.head, "div");
  19789. if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  19790. goals.push(headPos.left);
  19791. var pos = findPosV(this$1, headPos, dir, unit);
  19792. if (unit == "page" && range == doc.sel.primary())
  19793. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  19794. return pos
  19795. }, sel_move);
  19796. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  19797. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  19798. }),
  19799. // Find the word at the given position (as returned by coordsChar).
  19800. findWordAt: function(pos) {
  19801. var doc = this.doc, line = getLine(doc, pos.line).text;
  19802. var start = pos.ch, end = pos.ch;
  19803. if (line) {
  19804. var helper = this.getHelper(pos, "wordChars");
  19805. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  19806. var startChar = line.charAt(start);
  19807. var check = isWordChar(startChar, helper)
  19808. ? function (ch) { return isWordChar(ch, helper); }
  19809. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  19810. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  19811. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  19812. while (end < line.length && check(line.charAt(end))) { ++end; }
  19813. }
  19814. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  19815. },
  19816. toggleOverwrite: function(value) {
  19817. if (value != null && value == this.state.overwrite) { return }
  19818. if (this.state.overwrite = !this.state.overwrite)
  19819. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  19820. else
  19821. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  19822. signal(this, "overwriteToggle", this, this.state.overwrite);
  19823. },
  19824. hasFocus: function() { return this.display.input.getField() == activeElt() },
  19825. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  19826. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  19827. getScrollInfo: function() {
  19828. var scroller = this.display.scroller;
  19829. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  19830. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  19831. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  19832. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  19833. },
  19834. scrollIntoView: methodOp(function(range, margin) {
  19835. if (range == null) {
  19836. range = {from: this.doc.sel.primary().head, to: null};
  19837. if (margin == null) { margin = this.options.cursorScrollMargin; }
  19838. } else if (typeof range == "number") {
  19839. range = {from: Pos(range, 0), to: null};
  19840. } else if (range.from == null) {
  19841. range = {from: range, to: null};
  19842. }
  19843. if (!range.to) { range.to = range.from; }
  19844. range.margin = margin || 0;
  19845. if (range.from.line != null) {
  19846. scrollToRange(this, range);
  19847. } else {
  19848. scrollToCoordsRange(this, range.from, range.to, range.margin);
  19849. }
  19850. }),
  19851. setSize: methodOp(function(width, height) {
  19852. var this$1 = this;
  19853. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  19854. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  19855. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  19856. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  19857. var lineNo = this.display.viewFrom;
  19858. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  19859. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  19860. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  19861. ++lineNo;
  19862. });
  19863. this.curOp.forceUpdate = true;
  19864. signal(this, "refresh", this);
  19865. }),
  19866. operation: function(f){return runInOp(this, f)},
  19867. startOperation: function(){return startOperation(this)},
  19868. endOperation: function(){return endOperation(this)},
  19869. refresh: methodOp(function() {
  19870. var oldHeight = this.display.cachedTextHeight;
  19871. regChange(this);
  19872. this.curOp.forceUpdate = true;
  19873. clearCaches(this);
  19874. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  19875. updateGutterSpace(this.display);
  19876. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  19877. { estimateLineHeights(this); }
  19878. signal(this, "refresh", this);
  19879. }),
  19880. swapDoc: methodOp(function(doc) {
  19881. var old = this.doc;
  19882. old.cm = null;
  19883. // Cancel the current text selection if any (#5821)
  19884. if (this.state.selectingText) { this.state.selectingText(); }
  19885. attachDoc(this, doc);
  19886. clearCaches(this);
  19887. this.display.input.reset();
  19888. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  19889. this.curOp.forceScroll = true;
  19890. signalLater(this, "swapDoc", this, old);
  19891. return old
  19892. }),
  19893. phrase: function(phraseText) {
  19894. var phrases = this.options.phrases;
  19895. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  19896. },
  19897. getInputField: function(){return this.display.input.getField()},
  19898. getWrapperElement: function(){return this.display.wrapper},
  19899. getScrollerElement: function(){return this.display.scroller},
  19900. getGutterElement: function(){return this.display.gutters}
  19901. };
  19902. eventMixin(CodeMirror);
  19903. CodeMirror.registerHelper = function(type, name, value) {
  19904. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  19905. helpers[type][name] = value;
  19906. };
  19907. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  19908. CodeMirror.registerHelper(type, name, value);
  19909. helpers[type]._global.push({pred: predicate, val: value});
  19910. };
  19911. }
  19912. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  19913. // right), unit can be "char", "column" (like char, but doesn't
  19914. // cross line boundaries), "word" (across next word), or "group" (to
  19915. // the start of next group of word or non-word-non-whitespace
  19916. // chars). The visually param controls whether, in right-to-left
  19917. // text, direction 1 means to move towards the next index in the
  19918. // string, or towards the character to the right of the current
  19919. // position. The resulting position will have a hitSide=true
  19920. // property if it reached the end of the document.
  19921. function findPosH(doc, pos, dir, unit, visually) {
  19922. var oldPos = pos;
  19923. var origDir = dir;
  19924. var lineObj = getLine(doc, pos.line);
  19925. var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  19926. function findNextLine() {
  19927. var l = pos.line + lineDir;
  19928. if (l < doc.first || l >= doc.first + doc.size) { return false }
  19929. pos = new Pos(l, pos.ch, pos.sticky);
  19930. return lineObj = getLine(doc, l)
  19931. }
  19932. function moveOnce(boundToLine) {
  19933. var next;
  19934. if (visually) {
  19935. next = moveVisually(doc.cm, lineObj, pos, dir);
  19936. } else {
  19937. next = moveLogically(lineObj, pos, dir);
  19938. }
  19939. if (next == null) {
  19940. if (!boundToLine && findNextLine())
  19941. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  19942. else
  19943. { return false }
  19944. } else {
  19945. pos = next;
  19946. }
  19947. return true
  19948. }
  19949. if (unit == "char") {
  19950. moveOnce();
  19951. } else if (unit == "column") {
  19952. moveOnce(true);
  19953. } else if (unit == "word" || unit == "group") {
  19954. var sawType = null, group = unit == "group";
  19955. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  19956. for (var first = true;; first = false) {
  19957. if (dir < 0 && !moveOnce(!first)) { break }
  19958. var cur = lineObj.text.charAt(pos.ch) || "\n";
  19959. var type = isWordChar(cur, helper) ? "w"
  19960. : group && cur == "\n" ? "n"
  19961. : !group || /\s/.test(cur) ? null
  19962. : "p";
  19963. if (group && !first && !type) { type = "s"; }
  19964. if (sawType && sawType != type) {
  19965. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  19966. break
  19967. }
  19968. if (type) { sawType = type; }
  19969. if (dir > 0 && !moveOnce(!first)) { break }
  19970. }
  19971. }
  19972. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  19973. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  19974. return result
  19975. }
  19976. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  19977. // "page" or "line". The resulting position will have a hitSide=true
  19978. // property if it reached the end of the document.
  19979. function findPosV(cm, pos, dir, unit) {
  19980. var doc = cm.doc, x = pos.left, y;
  19981. if (unit == "page") {
  19982. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  19983. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  19984. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  19985. } else if (unit == "line") {
  19986. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  19987. }
  19988. var target;
  19989. for (;;) {
  19990. target = coordsChar(cm, x, y);
  19991. if (!target.outside) { break }
  19992. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  19993. y += dir * 5;
  19994. }
  19995. return target
  19996. }
  19997. // CONTENTEDITABLE INPUT STYLE
  19998. var ContentEditableInput = function(cm) {
  19999. this.cm = cm;
  20000. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  20001. this.polling = new Delayed();
  20002. this.composing = null;
  20003. this.gracePeriod = false;
  20004. this.readDOMTimeout = null;
  20005. };
  20006. ContentEditableInput.prototype.init = function (display) {
  20007. var this$1 = this;
  20008. var input = this, cm = input.cm;
  20009. var div = input.div = display.lineDiv;
  20010. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  20011. function belongsToInput(e) {
  20012. for (var t = e.target; t; t = t.parentNode) {
  20013. if (t == div) { return true }
  20014. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  20015. }
  20016. return false
  20017. }
  20018. on(div, "paste", function (e) {
  20019. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  20020. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  20021. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  20022. });
  20023. on(div, "compositionstart", function (e) {
  20024. this$1.composing = {data: e.data, done: false};
  20025. });
  20026. on(div, "compositionupdate", function (e) {
  20027. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  20028. });
  20029. on(div, "compositionend", function (e) {
  20030. if (this$1.composing) {
  20031. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  20032. this$1.composing.done = true;
  20033. }
  20034. });
  20035. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  20036. on(div, "input", function () {
  20037. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  20038. });
  20039. function onCopyCut(e) {
  20040. if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  20041. if (cm.somethingSelected()) {
  20042. setLastCopied({lineWise: false, text: cm.getSelections()});
  20043. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  20044. } else if (!cm.options.lineWiseCopyCut) {
  20045. return
  20046. } else {
  20047. var ranges = copyableRanges(cm);
  20048. setLastCopied({lineWise: true, text: ranges.text});
  20049. if (e.type == "cut") {
  20050. cm.operation(function () {
  20051. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  20052. cm.replaceSelection("", null, "cut");
  20053. });
  20054. }
  20055. }
  20056. if (e.clipboardData) {
  20057. e.clipboardData.clearData();
  20058. var content = lastCopied.text.join("\n");
  20059. // iOS exposes the clipboard API, but seems to discard content inserted into it
  20060. e.clipboardData.setData("Text", content);
  20061. if (e.clipboardData.getData("Text") == content) {
  20062. e.preventDefault();
  20063. return
  20064. }
  20065. }
  20066. // Old-fashioned briefly-focus-a-textarea hack
  20067. var kludge = hiddenTextarea(), te = kludge.firstChild;
  20068. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  20069. te.value = lastCopied.text.join("\n");
  20070. var hadFocus = document.activeElement;
  20071. selectInput(te);
  20072. setTimeout(function () {
  20073. cm.display.lineSpace.removeChild(kludge);
  20074. hadFocus.focus();
  20075. if (hadFocus == div) { input.showPrimarySelection(); }
  20076. }, 50);
  20077. }
  20078. on(div, "copy", onCopyCut);
  20079. on(div, "cut", onCopyCut);
  20080. };
  20081. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  20082. // Label for screenreaders, accessibility
  20083. if(label) {
  20084. this.div.setAttribute('aria-label', label);
  20085. } else {
  20086. this.div.removeAttribute('aria-label');
  20087. }
  20088. };
  20089. ContentEditableInput.prototype.prepareSelection = function () {
  20090. var result = prepareSelection(this.cm, false);
  20091. result.focus = document.activeElement == this.div;
  20092. return result
  20093. };
  20094. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  20095. if (!info || !this.cm.display.view.length) { return }
  20096. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  20097. this.showMultipleSelections(info);
  20098. };
  20099. ContentEditableInput.prototype.getSelection = function () {
  20100. return this.cm.display.wrapper.ownerDocument.getSelection()
  20101. };
  20102. ContentEditableInput.prototype.showPrimarySelection = function () {
  20103. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  20104. var from = prim.from(), to = prim.to();
  20105. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  20106. sel.removeAllRanges();
  20107. return
  20108. }
  20109. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  20110. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  20111. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  20112. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  20113. cmp(maxPos(curAnchor, curFocus), to) == 0)
  20114. { return }
  20115. var view = cm.display.view;
  20116. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  20117. {node: view[0].measure.map[2], offset: 0};
  20118. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  20119. if (!end) {
  20120. var measure = view[view.length - 1].measure;
  20121. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  20122. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  20123. }
  20124. if (!start || !end) {
  20125. sel.removeAllRanges();
  20126. return
  20127. }
  20128. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  20129. try { rng = range(start.node, start.offset, end.offset, end.node); }
  20130. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  20131. if (rng) {
  20132. if (!gecko && cm.state.focused) {
  20133. sel.collapse(start.node, start.offset);
  20134. if (!rng.collapsed) {
  20135. sel.removeAllRanges();
  20136. sel.addRange(rng);
  20137. }
  20138. } else {
  20139. sel.removeAllRanges();
  20140. sel.addRange(rng);
  20141. }
  20142. if (old && sel.anchorNode == null) { sel.addRange(old); }
  20143. else if (gecko) { this.startGracePeriod(); }
  20144. }
  20145. this.rememberSelection();
  20146. };
  20147. ContentEditableInput.prototype.startGracePeriod = function () {
  20148. var this$1 = this;
  20149. clearTimeout(this.gracePeriod);
  20150. this.gracePeriod = setTimeout(function () {
  20151. this$1.gracePeriod = false;
  20152. if (this$1.selectionChanged())
  20153. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  20154. }, 20);
  20155. };
  20156. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  20157. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  20158. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  20159. };
  20160. ContentEditableInput.prototype.rememberSelection = function () {
  20161. var sel = this.getSelection();
  20162. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  20163. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  20164. };
  20165. ContentEditableInput.prototype.selectionInEditor = function () {
  20166. var sel = this.getSelection();
  20167. if (!sel.rangeCount) { return false }
  20168. var node = sel.getRangeAt(0).commonAncestorContainer;
  20169. return contains(this.div, node)
  20170. };
  20171. ContentEditableInput.prototype.focus = function () {
  20172. if (this.cm.options.readOnly != "nocursor") {
  20173. if (!this.selectionInEditor() || document.activeElement != this.div)
  20174. { this.showSelection(this.prepareSelection(), true); }
  20175. this.div.focus();
  20176. }
  20177. };
  20178. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  20179. ContentEditableInput.prototype.getField = function () { return this.div };
  20180. ContentEditableInput.prototype.supportsTouch = function () { return true };
  20181. ContentEditableInput.prototype.receivedFocus = function () {
  20182. var input = this;
  20183. if (this.selectionInEditor())
  20184. { this.pollSelection(); }
  20185. else
  20186. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  20187. function poll() {
  20188. if (input.cm.state.focused) {
  20189. input.pollSelection();
  20190. input.polling.set(input.cm.options.pollInterval, poll);
  20191. }
  20192. }
  20193. this.polling.set(this.cm.options.pollInterval, poll);
  20194. };
  20195. ContentEditableInput.prototype.selectionChanged = function () {
  20196. var sel = this.getSelection();
  20197. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  20198. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  20199. };
  20200. ContentEditableInput.prototype.pollSelection = function () {
  20201. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  20202. var sel = this.getSelection(), cm = this.cm;
  20203. // On Android Chrome (version 56, at least), backspacing into an
  20204. // uneditable block element will put the cursor in that element,
  20205. // and then, because it's not editable, hide the virtual keyboard.
  20206. // Because Android doesn't allow us to actually detect backspace
  20207. // presses in a sane way, this code checks for when that happens
  20208. // and simulates a backspace press in this case.
  20209. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  20210. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  20211. this.blur();
  20212. this.focus();
  20213. return
  20214. }
  20215. if (this.composing) { return }
  20216. this.rememberSelection();
  20217. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  20218. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  20219. if (anchor && head) { runInOp(cm, function () {
  20220. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  20221. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  20222. }); }
  20223. };
  20224. ContentEditableInput.prototype.pollContent = function () {
  20225. if (this.readDOMTimeout != null) {
  20226. clearTimeout(this.readDOMTimeout);
  20227. this.readDOMTimeout = null;
  20228. }
  20229. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  20230. var from = sel.from(), to = sel.to();
  20231. if (from.ch == 0 && from.line > cm.firstLine())
  20232. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  20233. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  20234. { to = Pos(to.line + 1, 0); }
  20235. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  20236. var fromIndex, fromLine, fromNode;
  20237. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  20238. fromLine = lineNo(display.view[0].line);
  20239. fromNode = display.view[0].node;
  20240. } else {
  20241. fromLine = lineNo(display.view[fromIndex].line);
  20242. fromNode = display.view[fromIndex - 1].node.nextSibling;
  20243. }
  20244. var toIndex = findViewIndex(cm, to.line);
  20245. var toLine, toNode;
  20246. if (toIndex == display.view.length - 1) {
  20247. toLine = display.viewTo - 1;
  20248. toNode = display.lineDiv.lastChild;
  20249. } else {
  20250. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  20251. toNode = display.view[toIndex + 1].node.previousSibling;
  20252. }
  20253. if (!fromNode) { return false }
  20254. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  20255. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  20256. while (newText.length > 1 && oldText.length > 1) {
  20257. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  20258. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  20259. else { break }
  20260. }
  20261. var cutFront = 0, cutEnd = 0;
  20262. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  20263. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  20264. { ++cutFront; }
  20265. var newBot = lst(newText), oldBot = lst(oldText);
  20266. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  20267. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  20268. while (cutEnd < maxCutEnd &&
  20269. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  20270. { ++cutEnd; }
  20271. // Try to move start of change to start of selection if ambiguous
  20272. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  20273. while (cutFront && cutFront > from.ch &&
  20274. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  20275. cutFront--;
  20276. cutEnd++;
  20277. }
  20278. }
  20279. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  20280. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  20281. var chFrom = Pos(fromLine, cutFront);
  20282. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  20283. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  20284. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  20285. return true
  20286. }
  20287. };
  20288. ContentEditableInput.prototype.ensurePolled = function () {
  20289. this.forceCompositionEnd();
  20290. };
  20291. ContentEditableInput.prototype.reset = function () {
  20292. this.forceCompositionEnd();
  20293. };
  20294. ContentEditableInput.prototype.forceCompositionEnd = function () {
  20295. if (!this.composing) { return }
  20296. clearTimeout(this.readDOMTimeout);
  20297. this.composing = null;
  20298. this.updateFromDOM();
  20299. this.div.blur();
  20300. this.div.focus();
  20301. };
  20302. ContentEditableInput.prototype.readFromDOMSoon = function () {
  20303. var this$1 = this;
  20304. if (this.readDOMTimeout != null) { return }
  20305. this.readDOMTimeout = setTimeout(function () {
  20306. this$1.readDOMTimeout = null;
  20307. if (this$1.composing) {
  20308. if (this$1.composing.done) { this$1.composing = null; }
  20309. else { return }
  20310. }
  20311. this$1.updateFromDOM();
  20312. }, 80);
  20313. };
  20314. ContentEditableInput.prototype.updateFromDOM = function () {
  20315. var this$1 = this;
  20316. if (this.cm.isReadOnly() || !this.pollContent())
  20317. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  20318. };
  20319. ContentEditableInput.prototype.setUneditable = function (node) {
  20320. node.contentEditable = "false";
  20321. };
  20322. ContentEditableInput.prototype.onKeyPress = function (e) {
  20323. if (e.charCode == 0 || this.composing) { return }
  20324. e.preventDefault();
  20325. if (!this.cm.isReadOnly())
  20326. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  20327. };
  20328. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  20329. this.div.contentEditable = String(val != "nocursor");
  20330. };
  20331. ContentEditableInput.prototype.onContextMenu = function () {};
  20332. ContentEditableInput.prototype.resetPosition = function () {};
  20333. ContentEditableInput.prototype.needsContentAttribute = true;
  20334. function posToDOM(cm, pos) {
  20335. var view = findViewForLine(cm, pos.line);
  20336. if (!view || view.hidden) { return null }
  20337. var line = getLine(cm.doc, pos.line);
  20338. var info = mapFromLineView(view, line, pos.line);
  20339. var order = getOrder(line, cm.doc.direction), side = "left";
  20340. if (order) {
  20341. var partPos = getBidiPartAt(order, pos.ch);
  20342. side = partPos % 2 ? "right" : "left";
  20343. }
  20344. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  20345. result.offset = result.collapse == "right" ? result.end : result.start;
  20346. return result
  20347. }
  20348. function isInGutter(node) {
  20349. for (var scan = node; scan; scan = scan.parentNode)
  20350. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  20351. return false
  20352. }
  20353. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  20354. function domTextBetween(cm, from, to, fromLine, toLine) {
  20355. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  20356. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  20357. function close() {
  20358. if (closing) {
  20359. text += lineSep;
  20360. if (extraLinebreak) { text += lineSep; }
  20361. closing = extraLinebreak = false;
  20362. }
  20363. }
  20364. function addText(str) {
  20365. if (str) {
  20366. close();
  20367. text += str;
  20368. }
  20369. }
  20370. function walk(node) {
  20371. if (node.nodeType == 1) {
  20372. var cmText = node.getAttribute("cm-text");
  20373. if (cmText) {
  20374. addText(cmText);
  20375. return
  20376. }
  20377. var markerID = node.getAttribute("cm-marker"), range;
  20378. if (markerID) {
  20379. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  20380. if (found.length && (range = found[0].find(0)))
  20381. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  20382. return
  20383. }
  20384. if (node.getAttribute("contenteditable") == "false") { return }
  20385. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  20386. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  20387. if (isBlock) { close(); }
  20388. for (var i = 0; i < node.childNodes.length; i++)
  20389. { walk(node.childNodes[i]); }
  20390. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  20391. if (isBlock) { closing = true; }
  20392. } else if (node.nodeType == 3) {
  20393. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  20394. }
  20395. }
  20396. for (;;) {
  20397. walk(from);
  20398. if (from == to) { break }
  20399. from = from.nextSibling;
  20400. extraLinebreak = false;
  20401. }
  20402. return text
  20403. }
  20404. function domToPos(cm, node, offset) {
  20405. var lineNode;
  20406. if (node == cm.display.lineDiv) {
  20407. lineNode = cm.display.lineDiv.childNodes[offset];
  20408. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  20409. node = null; offset = 0;
  20410. } else {
  20411. for (lineNode = node;; lineNode = lineNode.parentNode) {
  20412. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  20413. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  20414. }
  20415. }
  20416. for (var i = 0; i < cm.display.view.length; i++) {
  20417. var lineView = cm.display.view[i];
  20418. if (lineView.node == lineNode)
  20419. { return locateNodeInLineView(lineView, node, offset) }
  20420. }
  20421. }
  20422. function locateNodeInLineView(lineView, node, offset) {
  20423. var wrapper = lineView.text.firstChild, bad = false;
  20424. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  20425. if (node == wrapper) {
  20426. bad = true;
  20427. node = wrapper.childNodes[offset];
  20428. offset = 0;
  20429. if (!node) {
  20430. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  20431. return badPos(Pos(lineNo(line), line.text.length), bad)
  20432. }
  20433. }
  20434. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  20435. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  20436. textNode = node.firstChild;
  20437. if (offset) { offset = textNode.nodeValue.length; }
  20438. }
  20439. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  20440. var measure = lineView.measure, maps = measure.maps;
  20441. function find(textNode, topNode, offset) {
  20442. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  20443. var map = i < 0 ? measure.map : maps[i];
  20444. for (var j = 0; j < map.length; j += 3) {
  20445. var curNode = map[j + 2];
  20446. if (curNode == textNode || curNode == topNode) {
  20447. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  20448. var ch = map[j] + offset;
  20449. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  20450. return Pos(line, ch)
  20451. }
  20452. }
  20453. }
  20454. }
  20455. var found = find(textNode, topNode, offset);
  20456. if (found) { return badPos(found, bad) }
  20457. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  20458. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  20459. found = find(after, after.firstChild, 0);
  20460. if (found)
  20461. { return badPos(Pos(found.line, found.ch - dist), bad) }
  20462. else
  20463. { dist += after.textContent.length; }
  20464. }
  20465. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  20466. found = find(before, before.firstChild, -1);
  20467. if (found)
  20468. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  20469. else
  20470. { dist$1 += before.textContent.length; }
  20471. }
  20472. }
  20473. // TEXTAREA INPUT STYLE
  20474. var TextareaInput = function(cm) {
  20475. this.cm = cm;
  20476. // See input.poll and input.reset
  20477. this.prevInput = "";
  20478. // Flag that indicates whether we expect input to appear real soon
  20479. // now (after some event like 'keypress' or 'input') and are
  20480. // polling intensively.
  20481. this.pollingFast = false;
  20482. // Self-resetting timeout for the poller
  20483. this.polling = new Delayed();
  20484. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  20485. this.hasSelection = false;
  20486. this.composing = null;
  20487. };
  20488. TextareaInput.prototype.init = function (display) {
  20489. var this$1 = this;
  20490. var input = this, cm = this.cm;
  20491. this.createField(display);
  20492. var te = this.textarea;
  20493. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  20494. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  20495. if (ios) { te.style.width = "0px"; }
  20496. on(te, "input", function () {
  20497. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  20498. input.poll();
  20499. });
  20500. on(te, "paste", function (e) {
  20501. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  20502. cm.state.pasteIncoming = +new Date;
  20503. input.fastPoll();
  20504. });
  20505. function prepareCopyCut(e) {
  20506. if (signalDOMEvent(cm, e)) { return }
  20507. if (cm.somethingSelected()) {
  20508. setLastCopied({lineWise: false, text: cm.getSelections()});
  20509. } else if (!cm.options.lineWiseCopyCut) {
  20510. return
  20511. } else {
  20512. var ranges = copyableRanges(cm);
  20513. setLastCopied({lineWise: true, text: ranges.text});
  20514. if (e.type == "cut") {
  20515. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  20516. } else {
  20517. input.prevInput = "";
  20518. te.value = ranges.text.join("\n");
  20519. selectInput(te);
  20520. }
  20521. }
  20522. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  20523. }
  20524. on(te, "cut", prepareCopyCut);
  20525. on(te, "copy", prepareCopyCut);
  20526. on(display.scroller, "paste", function (e) {
  20527. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  20528. if (!te.dispatchEvent) {
  20529. cm.state.pasteIncoming = +new Date;
  20530. input.focus();
  20531. return
  20532. }
  20533. // Pass the `paste` event to the textarea so it's handled by its event listener.
  20534. var event = new Event("paste");
  20535. event.clipboardData = e.clipboardData;
  20536. te.dispatchEvent(event);
  20537. });
  20538. // Prevent normal selection in the editor (we handle our own)
  20539. on(display.lineSpace, "selectstart", function (e) {
  20540. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  20541. });
  20542. on(te, "compositionstart", function () {
  20543. var start = cm.getCursor("from");
  20544. if (input.composing) { input.composing.range.clear(); }
  20545. input.composing = {
  20546. start: start,
  20547. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  20548. };
  20549. });
  20550. on(te, "compositionend", function () {
  20551. if (input.composing) {
  20552. input.poll();
  20553. input.composing.range.clear();
  20554. input.composing = null;
  20555. }
  20556. });
  20557. };
  20558. TextareaInput.prototype.createField = function (_display) {
  20559. // Wraps and hides input textarea
  20560. this.wrapper = hiddenTextarea();
  20561. // The semihidden textarea that is focused when the editor is
  20562. // focused, and receives input.
  20563. this.textarea = this.wrapper.firstChild;
  20564. };
  20565. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  20566. // Label for screenreaders, accessibility
  20567. if(label) {
  20568. this.textarea.setAttribute('aria-label', label);
  20569. } else {
  20570. this.textarea.removeAttribute('aria-label');
  20571. }
  20572. };
  20573. TextareaInput.prototype.prepareSelection = function () {
  20574. // Redraw the selection and/or cursor
  20575. var cm = this.cm, display = cm.display, doc = cm.doc;
  20576. var result = prepareSelection(cm);
  20577. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  20578. if (cm.options.moveInputWithCursor) {
  20579. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  20580. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  20581. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  20582. headPos.top + lineOff.top - wrapOff.top));
  20583. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  20584. headPos.left + lineOff.left - wrapOff.left));
  20585. }
  20586. return result
  20587. };
  20588. TextareaInput.prototype.showSelection = function (drawn) {
  20589. var cm = this.cm, display = cm.display;
  20590. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  20591. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  20592. if (drawn.teTop != null) {
  20593. this.wrapper.style.top = drawn.teTop + "px";
  20594. this.wrapper.style.left = drawn.teLeft + "px";
  20595. }
  20596. };
  20597. // Reset the input to correspond to the selection (or to be empty,
  20598. // when not typing and nothing is selected)
  20599. TextareaInput.prototype.reset = function (typing) {
  20600. if (this.contextMenuPending || this.composing) { return }
  20601. var cm = this.cm;
  20602. if (cm.somethingSelected()) {
  20603. this.prevInput = "";
  20604. var content = cm.getSelection();
  20605. this.textarea.value = content;
  20606. if (cm.state.focused) { selectInput(this.textarea); }
  20607. if (ie && ie_version >= 9) { this.hasSelection = content; }
  20608. } else if (!typing) {
  20609. this.prevInput = this.textarea.value = "";
  20610. if (ie && ie_version >= 9) { this.hasSelection = null; }
  20611. }
  20612. };
  20613. TextareaInput.prototype.getField = function () { return this.textarea };
  20614. TextareaInput.prototype.supportsTouch = function () { return false };
  20615. TextareaInput.prototype.focus = function () {
  20616. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  20617. try { this.textarea.focus(); }
  20618. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  20619. }
  20620. };
  20621. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  20622. TextareaInput.prototype.resetPosition = function () {
  20623. this.wrapper.style.top = this.wrapper.style.left = 0;
  20624. };
  20625. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  20626. // Poll for input changes, using the normal rate of polling. This
  20627. // runs as long as the editor is focused.
  20628. TextareaInput.prototype.slowPoll = function () {
  20629. var this$1 = this;
  20630. if (this.pollingFast) { return }
  20631. this.polling.set(this.cm.options.pollInterval, function () {
  20632. this$1.poll();
  20633. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  20634. });
  20635. };
  20636. // When an event has just come in that is likely to add or change
  20637. // something in the input textarea, we poll faster, to ensure that
  20638. // the change appears on the screen quickly.
  20639. TextareaInput.prototype.fastPoll = function () {
  20640. var missed = false, input = this;
  20641. input.pollingFast = true;
  20642. function p() {
  20643. var changed = input.poll();
  20644. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  20645. else {input.pollingFast = false; input.slowPoll();}
  20646. }
  20647. input.polling.set(20, p);
  20648. };
  20649. // Read input from the textarea, and update the document to match.
  20650. // When something is selected, it is present in the textarea, and
  20651. // selected (unless it is huge, in which case a placeholder is
  20652. // used). When nothing is selected, the cursor sits after previously
  20653. // seen text (can be empty), which is stored in prevInput (we must
  20654. // not reset the textarea when typing, because that breaks IME).
  20655. TextareaInput.prototype.poll = function () {
  20656. var this$1 = this;
  20657. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  20658. // Since this is called a *lot*, try to bail out as cheaply as
  20659. // possible when it is clear that nothing happened. hasSelection
  20660. // will be the case when there is a lot of text in the textarea,
  20661. // in which case reading its value would be expensive.
  20662. if (this.contextMenuPending || !cm.state.focused ||
  20663. (hasSelection(input) && !prevInput && !this.composing) ||
  20664. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  20665. { return false }
  20666. var text = input.value;
  20667. // If nothing changed, bail.
  20668. if (text == prevInput && !cm.somethingSelected()) { return false }
  20669. // Work around nonsensical selection resetting in IE9/10, and
  20670. // inexplicable appearance of private area unicode characters on
  20671. // some key combos in Mac (#2689).
  20672. if (ie && ie_version >= 9 && this.hasSelection === text ||
  20673. mac && /[\uf700-\uf7ff]/.test(text)) {
  20674. cm.display.input.reset();
  20675. return false
  20676. }
  20677. if (cm.doc.sel == cm.display.selForContextMenu) {
  20678. var first = text.charCodeAt(0);
  20679. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  20680. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  20681. }
  20682. // Find the part of the input that is actually new
  20683. var same = 0, l = Math.min(prevInput.length, text.length);
  20684. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  20685. runInOp(cm, function () {
  20686. applyTextInput(cm, text.slice(same), prevInput.length - same,
  20687. null, this$1.composing ? "*compose" : null);
  20688. // Don't leave long text in the textarea, since it makes further polling slow
  20689. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  20690. else { this$1.prevInput = text; }
  20691. if (this$1.composing) {
  20692. this$1.composing.range.clear();
  20693. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  20694. {className: "CodeMirror-composing"});
  20695. }
  20696. });
  20697. return true
  20698. };
  20699. TextareaInput.prototype.ensurePolled = function () {
  20700. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  20701. };
  20702. TextareaInput.prototype.onKeyPress = function () {
  20703. if (ie && ie_version >= 9) { this.hasSelection = null; }
  20704. this.fastPoll();
  20705. };
  20706. TextareaInput.prototype.onContextMenu = function (e) {
  20707. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  20708. if (input.contextMenuPending) { input.contextMenuPending(); }
  20709. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  20710. if (!pos || presto) { return } // Opera is difficult.
  20711. // Reset the current text selection only if the click is done outside of the selection
  20712. // and 'resetSelectionOnContextMenu' option is true.
  20713. var reset = cm.options.resetSelectionOnContextMenu;
  20714. if (reset && cm.doc.sel.contains(pos) == -1)
  20715. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  20716. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  20717. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  20718. input.wrapper.style.cssText = "position: static";
  20719. 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);";
  20720. var oldScrollY;
  20721. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  20722. display.input.focus();
  20723. if (webkit) { window.scrollTo(null, oldScrollY); }
  20724. display.input.reset();
  20725. // Adds "Select all" to context menu in FF
  20726. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  20727. input.contextMenuPending = rehide;
  20728. display.selForContextMenu = cm.doc.sel;
  20729. clearTimeout(display.detectingSelectAll);
  20730. // Select-all will be greyed out if there's nothing to select, so
  20731. // this adds a zero-width space so that we can later check whether
  20732. // it got selected.
  20733. function prepareSelectAllHack() {
  20734. if (te.selectionStart != null) {
  20735. var selected = cm.somethingSelected();
  20736. var extval = "\u200b" + (selected ? te.value : "");
  20737. te.value = "\u21da"; // Used to catch context-menu undo
  20738. te.value = extval;
  20739. input.prevInput = selected ? "" : "\u200b";
  20740. te.selectionStart = 1; te.selectionEnd = extval.length;
  20741. // Re-set this, in case some other handler touched the
  20742. // selection in the meantime.
  20743. display.selForContextMenu = cm.doc.sel;
  20744. }
  20745. }
  20746. function rehide() {
  20747. if (input.contextMenuPending != rehide) { return }
  20748. input.contextMenuPending = false;
  20749. input.wrapper.style.cssText = oldWrapperCSS;
  20750. te.style.cssText = oldCSS;
  20751. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  20752. // Try to detect the user choosing select-all
  20753. if (te.selectionStart != null) {
  20754. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  20755. var i = 0, poll = function () {
  20756. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  20757. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  20758. operation(cm, selectAll)(cm);
  20759. } else if (i++ < 10) {
  20760. display.detectingSelectAll = setTimeout(poll, 500);
  20761. } else {
  20762. display.selForContextMenu = null;
  20763. display.input.reset();
  20764. }
  20765. };
  20766. display.detectingSelectAll = setTimeout(poll, 200);
  20767. }
  20768. }
  20769. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  20770. if (captureRightClick) {
  20771. e_stop(e);
  20772. var mouseup = function () {
  20773. off(window, "mouseup", mouseup);
  20774. setTimeout(rehide, 20);
  20775. };
  20776. on(window, "mouseup", mouseup);
  20777. } else {
  20778. setTimeout(rehide, 50);
  20779. }
  20780. };
  20781. TextareaInput.prototype.readOnlyChanged = function (val) {
  20782. if (!val) { this.reset(); }
  20783. this.textarea.disabled = val == "nocursor";
  20784. };
  20785. TextareaInput.prototype.setUneditable = function () {};
  20786. TextareaInput.prototype.needsContentAttribute = false;
  20787. function fromTextArea(textarea, options) {
  20788. options = options ? copyObj(options) : {};
  20789. options.value = textarea.value;
  20790. if (!options.tabindex && textarea.tabIndex)
  20791. { options.tabindex = textarea.tabIndex; }
  20792. if (!options.placeholder && textarea.placeholder)
  20793. { options.placeholder = textarea.placeholder; }
  20794. // Set autofocus to true if this textarea is focused, or if it has
  20795. // autofocus and no other element is focused.
  20796. if (options.autofocus == null) {
  20797. var hasFocus = activeElt();
  20798. options.autofocus = hasFocus == textarea ||
  20799. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  20800. }
  20801. function save() {textarea.value = cm.getValue();}
  20802. var realSubmit;
  20803. if (textarea.form) {
  20804. on(textarea.form, "submit", save);
  20805. // Deplorable hack to make the submit method do the right thing.
  20806. if (!options.leaveSubmitMethodAlone) {
  20807. var form = textarea.form;
  20808. realSubmit = form.submit;
  20809. try {
  20810. var wrappedSubmit = form.submit = function () {
  20811. save();
  20812. form.submit = realSubmit;
  20813. form.submit();
  20814. form.submit = wrappedSubmit;
  20815. };
  20816. } catch(e) {}
  20817. }
  20818. }
  20819. options.finishInit = function (cm) {
  20820. cm.save = save;
  20821. cm.getTextArea = function () { return textarea; };
  20822. cm.toTextArea = function () {
  20823. cm.toTextArea = isNaN; // Prevent this from being ran twice
  20824. save();
  20825. textarea.parentNode.removeChild(cm.getWrapperElement());
  20826. textarea.style.display = "";
  20827. if (textarea.form) {
  20828. off(textarea.form, "submit", save);
  20829. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  20830. { textarea.form.submit = realSubmit; }
  20831. }
  20832. };
  20833. };
  20834. textarea.style.display = "none";
  20835. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  20836. options);
  20837. return cm
  20838. }
  20839. function addLegacyProps(CodeMirror) {
  20840. CodeMirror.off = off;
  20841. CodeMirror.on = on;
  20842. CodeMirror.wheelEventPixels = wheelEventPixels;
  20843. CodeMirror.Doc = Doc;
  20844. CodeMirror.splitLines = splitLinesAuto;
  20845. CodeMirror.countColumn = countColumn;
  20846. CodeMirror.findColumn = findColumn;
  20847. CodeMirror.isWordChar = isWordCharBasic;
  20848. CodeMirror.Pass = Pass;
  20849. CodeMirror.signal = signal;
  20850. CodeMirror.Line = Line;
  20851. CodeMirror.changeEnd = changeEnd;
  20852. CodeMirror.scrollbarModel = scrollbarModel;
  20853. CodeMirror.Pos = Pos;
  20854. CodeMirror.cmpPos = cmp;
  20855. CodeMirror.modes = modes;
  20856. CodeMirror.mimeModes = mimeModes;
  20857. CodeMirror.resolveMode = resolveMode;
  20858. CodeMirror.getMode = getMode;
  20859. CodeMirror.modeExtensions = modeExtensions;
  20860. CodeMirror.extendMode = extendMode;
  20861. CodeMirror.copyState = copyState;
  20862. CodeMirror.startState = startState;
  20863. CodeMirror.innerMode = innerMode;
  20864. CodeMirror.commands = commands;
  20865. CodeMirror.keyMap = keyMap;
  20866. CodeMirror.keyName = keyName;
  20867. CodeMirror.isModifierKey = isModifierKey;
  20868. CodeMirror.lookupKey = lookupKey;
  20869. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  20870. CodeMirror.StringStream = StringStream;
  20871. CodeMirror.SharedTextMarker = SharedTextMarker;
  20872. CodeMirror.TextMarker = TextMarker;
  20873. CodeMirror.LineWidget = LineWidget;
  20874. CodeMirror.e_preventDefault = e_preventDefault;
  20875. CodeMirror.e_stopPropagation = e_stopPropagation;
  20876. CodeMirror.e_stop = e_stop;
  20877. CodeMirror.addClass = addClass;
  20878. CodeMirror.contains = contains;
  20879. CodeMirror.rmClass = rmClass;
  20880. CodeMirror.keyNames = keyNames;
  20881. }
  20882. // EDITOR CONSTRUCTOR
  20883. defineOptions(CodeMirror);
  20884. addEditorMethods(CodeMirror);
  20885. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  20886. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  20887. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  20888. { CodeMirror.prototype[prop] = (function(method) {
  20889. return function() {return method.apply(this.doc, arguments)}
  20890. })(Doc.prototype[prop]); } }
  20891. eventMixin(Doc);
  20892. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  20893. // Extra arguments are stored as the mode's dependencies, which is
  20894. // used by (legacy) mechanisms like loadmode.js to automatically
  20895. // load a mode. (Preferred mechanism is the require/define calls.)
  20896. CodeMirror.defineMode = function(name/*, mode, …*/) {
  20897. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  20898. defineMode.apply(this, arguments);
  20899. };
  20900. CodeMirror.defineMIME = defineMIME;
  20901. // Minimal default mode.
  20902. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  20903. CodeMirror.defineMIME("text/plain", "null");
  20904. // EXTENSIONS
  20905. CodeMirror.defineExtension = function (name, func) {
  20906. CodeMirror.prototype[name] = func;
  20907. };
  20908. CodeMirror.defineDocExtension = function (name, func) {
  20909. Doc.prototype[name] = func;
  20910. };
  20911. CodeMirror.fromTextArea = fromTextArea;
  20912. addLegacyProps(CodeMirror);
  20913. CodeMirror.version = "5.54.0";
  20914. return CodeMirror;
  20915. })));
  20916. /***/ }),
  20917. /***/ "./node_modules/decimal.js/decimal.js":
  20918. /*!********************************************!*\
  20919. !*** ./node_modules/decimal.js/decimal.js ***!
  20920. \********************************************/
  20921. /*! no static exports found */
  20922. /***/ (function(module, exports, __webpack_require__) {
  20923. var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalScope) {
  20924. 'use strict';
  20925. /*
  20926. * decimal.js v10.2.0
  20927. * An arbitrary-precision Decimal type for JavaScript.
  20928. * https://github.com/MikeMcl/decimal.js
  20929. * Copyright (c) 2019 Michael Mclaughlin <M8ch88l@gmail.com>
  20930. * MIT Licence
  20931. */
  20932. // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
  20933. // The maximum exponent magnitude.
  20934. // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
  20935. var EXP_LIMIT = 9e15, // 0 to 9e15
  20936. // The limit on the value of `precision`, and on the value of the first argument to
  20937. // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
  20938. MAX_DIGITS = 1e9, // 0 to 1e9
  20939. // Base conversion alphabet.
  20940. NUMERALS = '0123456789abcdef',
  20941. // The natural logarithm of 10 (1025 digits).
  20942. LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
  20943. // Pi (1025 digits).
  20944. PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
  20945. // The initial configuration properties of the Decimal constructor.
  20946. DEFAULTS = {
  20947. // These values must be integers within the stated ranges (inclusive).
  20948. // Most of these values can be changed at run-time using the `Decimal.config` method.
  20949. // The maximum number of significant digits of the result of a calculation or base conversion.
  20950. // E.g. `Decimal.config({ precision: 20 });`
  20951. precision: 20, // 1 to MAX_DIGITS
  20952. // The rounding mode used when rounding to `precision`.
  20953. //
  20954. // ROUND_UP 0 Away from zero.
  20955. // ROUND_DOWN 1 Towards zero.
  20956. // ROUND_CEIL 2 Towards +Infinity.
  20957. // ROUND_FLOOR 3 Towards -Infinity.
  20958. // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
  20959. // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
  20960. // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
  20961. // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
  20962. // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  20963. //
  20964. // E.g.
  20965. // `Decimal.rounding = 4;`
  20966. // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
  20967. rounding: 4, // 0 to 8
  20968. // The modulo mode used when calculating the modulus: a mod n.
  20969. // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
  20970. // The remainder (r) is calculated as: r = a - n * q.
  20971. //
  20972. // UP 0 The remainder is positive if the dividend is negative, else is negative.
  20973. // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).
  20974. // FLOOR 3 The remainder has the same sign as the divisor (Python %).
  20975. // HALF_EVEN 6 The IEEE 754 remainder function.
  20976. // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
  20977. //
  20978. // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
  20979. // division (9) are commonly used for the modulus operation. The other rounding modes can also
  20980. // be used, but they may not give useful results.
  20981. modulo: 1, // 0 to 9
  20982. // The exponent value at and beneath which `toString` returns exponential notation.
  20983. // JavaScript numbers: -7
  20984. toExpNeg: -7, // 0 to -EXP_LIMIT
  20985. // The exponent value at and above which `toString` returns exponential notation.
  20986. // JavaScript numbers: 21
  20987. toExpPos: 21, // 0 to EXP_LIMIT
  20988. // The minimum exponent value, beneath which underflow to zero occurs.
  20989. // JavaScript numbers: -324 (5e-324)
  20990. minE: -EXP_LIMIT, // -1 to -EXP_LIMIT
  20991. // The maximum exponent value, above which overflow to Infinity occurs.
  20992. // JavaScript numbers: 308 (1.7976931348623157e+308)
  20993. maxE: EXP_LIMIT, // 1 to EXP_LIMIT
  20994. // Whether to use cryptographically-secure random number generation, if available.
  20995. crypto: false // true/false
  20996. },
  20997. // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
  20998. Decimal, inexact, noConflict, quadrant,
  20999. external = true,
  21000. decimalError = '[DecimalError] ',
  21001. invalidArgument = decimalError + 'Invalid argument: ',
  21002. precisionLimitExceeded = decimalError + 'Precision limit exceeded',
  21003. cryptoUnavailable = decimalError + 'crypto unavailable',
  21004. mathfloor = Math.floor,
  21005. mathpow = Math.pow,
  21006. isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
  21007. isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
  21008. isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
  21009. isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
  21010. BASE = 1e7,
  21011. LOG_BASE = 7,
  21012. MAX_SAFE_INTEGER = 9007199254740991,
  21013. LN10_PRECISION = LN10.length - 1,
  21014. PI_PRECISION = PI.length - 1,
  21015. // Decimal.prototype object
  21016. P = { name: '[object Decimal]' };
  21017. // Decimal prototype methods
  21018. /*
  21019. * absoluteValue abs
  21020. * ceil
  21021. * comparedTo cmp
  21022. * cosine cos
  21023. * cubeRoot cbrt
  21024. * decimalPlaces dp
  21025. * dividedBy div
  21026. * dividedToIntegerBy divToInt
  21027. * equals eq
  21028. * floor
  21029. * greaterThan gt
  21030. * greaterThanOrEqualTo gte
  21031. * hyperbolicCosine cosh
  21032. * hyperbolicSine sinh
  21033. * hyperbolicTangent tanh
  21034. * inverseCosine acos
  21035. * inverseHyperbolicCosine acosh
  21036. * inverseHyperbolicSine asinh
  21037. * inverseHyperbolicTangent atanh
  21038. * inverseSine asin
  21039. * inverseTangent atan
  21040. * isFinite
  21041. * isInteger isInt
  21042. * isNaN
  21043. * isNegative isNeg
  21044. * isPositive isPos
  21045. * isZero
  21046. * lessThan lt
  21047. * lessThanOrEqualTo lte
  21048. * logarithm log
  21049. * [maximum] [max]
  21050. * [minimum] [min]
  21051. * minus sub
  21052. * modulo mod
  21053. * naturalExponential exp
  21054. * naturalLogarithm ln
  21055. * negated neg
  21056. * plus add
  21057. * precision sd
  21058. * round
  21059. * sine sin
  21060. * squareRoot sqrt
  21061. * tangent tan
  21062. * times mul
  21063. * toBinary
  21064. * toDecimalPlaces toDP
  21065. * toExponential
  21066. * toFixed
  21067. * toFraction
  21068. * toHexadecimal toHex
  21069. * toNearest
  21070. * toNumber
  21071. * toOctal
  21072. * toPower pow
  21073. * toPrecision
  21074. * toSignificantDigits toSD
  21075. * toString
  21076. * truncated trunc
  21077. * valueOf toJSON
  21078. */
  21079. /*
  21080. * Return a new Decimal whose value is the absolute value of this Decimal.
  21081. *
  21082. */
  21083. P.absoluteValue = P.abs = function () {
  21084. var x = new this.constructor(this);
  21085. if (x.s < 0) x.s = 1;
  21086. return finalise(x);
  21087. };
  21088. /*
  21089. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  21090. * direction of positive Infinity.
  21091. *
  21092. */
  21093. P.ceil = function () {
  21094. return finalise(new this.constructor(this), this.e + 1, 2);
  21095. };
  21096. /*
  21097. * Return
  21098. * 1 if the value of this Decimal is greater than the value of `y`,
  21099. * -1 if the value of this Decimal is less than the value of `y`,
  21100. * 0 if they have the same value,
  21101. * NaN if the value of either Decimal is NaN.
  21102. *
  21103. */
  21104. P.comparedTo = P.cmp = function (y) {
  21105. var i, j, xdL, ydL,
  21106. x = this,
  21107. xd = x.d,
  21108. yd = (y = new x.constructor(y)).d,
  21109. xs = x.s,
  21110. ys = y.s;
  21111. // Either NaN or ±Infinity?
  21112. if (!xd || !yd) {
  21113. return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
  21114. }
  21115. // Either zero?
  21116. if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
  21117. // Signs differ?
  21118. if (xs !== ys) return xs;
  21119. // Compare exponents.
  21120. if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
  21121. xdL = xd.length;
  21122. ydL = yd.length;
  21123. // Compare digit by digit.
  21124. for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
  21125. if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
  21126. }
  21127. // Compare lengths.
  21128. return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
  21129. };
  21130. /*
  21131. * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
  21132. *
  21133. * Domain: [-Infinity, Infinity]
  21134. * Range: [-1, 1]
  21135. *
  21136. * cos(0) = 1
  21137. * cos(-0) = 1
  21138. * cos(Infinity) = NaN
  21139. * cos(-Infinity) = NaN
  21140. * cos(NaN) = NaN
  21141. *
  21142. */
  21143. P.cosine = P.cos = function () {
  21144. var pr, rm,
  21145. x = this,
  21146. Ctor = x.constructor;
  21147. if (!x.d) return new Ctor(NaN);
  21148. // cos(0) = cos(-0) = 1
  21149. if (!x.d[0]) return new Ctor(1);
  21150. pr = Ctor.precision;
  21151. rm = Ctor.rounding;
  21152. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  21153. Ctor.rounding = 1;
  21154. x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
  21155. Ctor.precision = pr;
  21156. Ctor.rounding = rm;
  21157. return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
  21158. };
  21159. /*
  21160. *
  21161. * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
  21162. * `precision` significant digits using rounding mode `rounding`.
  21163. *
  21164. * cbrt(0) = 0
  21165. * cbrt(-0) = -0
  21166. * cbrt(1) = 1
  21167. * cbrt(-1) = -1
  21168. * cbrt(N) = N
  21169. * cbrt(-I) = -I
  21170. * cbrt(I) = I
  21171. *
  21172. * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
  21173. *
  21174. */
  21175. P.cubeRoot = P.cbrt = function () {
  21176. var e, m, n, r, rep, s, sd, t, t3, t3plusx,
  21177. x = this,
  21178. Ctor = x.constructor;
  21179. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  21180. external = false;
  21181. // Initial estimate.
  21182. s = x.s * mathpow(x.s * x, 1 / 3);
  21183. // Math.cbrt underflow/overflow?
  21184. // Pass x to Math.pow as integer, then adjust the exponent of the result.
  21185. if (!s || Math.abs(s) == 1 / 0) {
  21186. n = digitsToString(x.d);
  21187. e = x.e;
  21188. // Adjust n exponent so it is a multiple of 3 away from x exponent.
  21189. if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
  21190. s = mathpow(n, 1 / 3);
  21191. // Rarely, e may be one less than the result exponent value.
  21192. e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
  21193. if (s == 1 / 0) {
  21194. n = '5e' + e;
  21195. } else {
  21196. n = s.toExponential();
  21197. n = n.slice(0, n.indexOf('e') + 1) + e;
  21198. }
  21199. r = new Ctor(n);
  21200. r.s = x.s;
  21201. } else {
  21202. r = new Ctor(s.toString());
  21203. }
  21204. sd = (e = Ctor.precision) + 3;
  21205. // Halley's method.
  21206. // TODO? Compare Newton's method.
  21207. for (;;) {
  21208. t = r;
  21209. t3 = t.times(t).times(t);
  21210. t3plusx = t3.plus(x);
  21211. r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
  21212. // TODO? Replace with for-loop and checkRoundingDigits.
  21213. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  21214. n = n.slice(sd - 3, sd + 1);
  21215. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
  21216. // , i.e. approaching a rounding boundary, continue the iteration.
  21217. if (n == '9999' || !rep && n == '4999') {
  21218. // On the first iteration only, check to see if rounding up gives the exact result as the
  21219. // nines may infinitely repeat.
  21220. if (!rep) {
  21221. finalise(t, e + 1, 0);
  21222. if (t.times(t).times(t).eq(x)) {
  21223. r = t;
  21224. break;
  21225. }
  21226. }
  21227. sd += 4;
  21228. rep = 1;
  21229. } else {
  21230. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  21231. // If not, then there are further digits and m will be truthy.
  21232. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  21233. // Truncate to the first rounding digit.
  21234. finalise(r, e + 1, 1);
  21235. m = !r.times(r).times(r).eq(x);
  21236. }
  21237. break;
  21238. }
  21239. }
  21240. }
  21241. external = true;
  21242. return finalise(r, e, Ctor.rounding, m);
  21243. };
  21244. /*
  21245. * Return the number of decimal places of the value of this Decimal.
  21246. *
  21247. */
  21248. P.decimalPlaces = P.dp = function () {
  21249. var w,
  21250. d = this.d,
  21251. n = NaN;
  21252. if (d) {
  21253. w = d.length - 1;
  21254. n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
  21255. // Subtract the number of trailing zeros of the last word.
  21256. w = d[w];
  21257. if (w) for (; w % 10 == 0; w /= 10) n--;
  21258. if (n < 0) n = 0;
  21259. }
  21260. return n;
  21261. };
  21262. /*
  21263. * n / 0 = I
  21264. * n / N = N
  21265. * n / I = 0
  21266. * 0 / n = 0
  21267. * 0 / 0 = N
  21268. * 0 / N = N
  21269. * 0 / I = 0
  21270. * N / n = N
  21271. * N / 0 = N
  21272. * N / N = N
  21273. * N / I = N
  21274. * I / n = I
  21275. * I / 0 = I
  21276. * I / N = N
  21277. * I / I = N
  21278. *
  21279. * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
  21280. * `precision` significant digits using rounding mode `rounding`.
  21281. *
  21282. */
  21283. P.dividedBy = P.div = function (y) {
  21284. return divide(this, new this.constructor(y));
  21285. };
  21286. /*
  21287. * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
  21288. * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
  21289. *
  21290. */
  21291. P.dividedToIntegerBy = P.divToInt = function (y) {
  21292. var x = this,
  21293. Ctor = x.constructor;
  21294. return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
  21295. };
  21296. /*
  21297. * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
  21298. *
  21299. */
  21300. P.equals = P.eq = function (y) {
  21301. return this.cmp(y) === 0;
  21302. };
  21303. /*
  21304. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  21305. * direction of negative Infinity.
  21306. *
  21307. */
  21308. P.floor = function () {
  21309. return finalise(new this.constructor(this), this.e + 1, 3);
  21310. };
  21311. /*
  21312. * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
  21313. * false.
  21314. *
  21315. */
  21316. P.greaterThan = P.gt = function (y) {
  21317. return this.cmp(y) > 0;
  21318. };
  21319. /*
  21320. * Return true if the value of this Decimal is greater than or equal to the value of `y`,
  21321. * otherwise return false.
  21322. *
  21323. */
  21324. P.greaterThanOrEqualTo = P.gte = function (y) {
  21325. var k = this.cmp(y);
  21326. return k == 1 || k === 0;
  21327. };
  21328. /*
  21329. * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
  21330. * Decimal.
  21331. *
  21332. * Domain: [-Infinity, Infinity]
  21333. * Range: [1, Infinity]
  21334. *
  21335. * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
  21336. *
  21337. * cosh(0) = 1
  21338. * cosh(-0) = 1
  21339. * cosh(Infinity) = Infinity
  21340. * cosh(-Infinity) = Infinity
  21341. * cosh(NaN) = NaN
  21342. *
  21343. * x time taken (ms) result
  21344. * 1000 9 9.8503555700852349694e+433
  21345. * 10000 25 4.4034091128314607936e+4342
  21346. * 100000 171 1.4033316802130615897e+43429
  21347. * 1000000 3817 1.5166076984010437725e+434294
  21348. * 10000000 abandoned after 2 minute wait
  21349. *
  21350. * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
  21351. *
  21352. */
  21353. P.hyperbolicCosine = P.cosh = function () {
  21354. var k, n, pr, rm, len,
  21355. x = this,
  21356. Ctor = x.constructor,
  21357. one = new Ctor(1);
  21358. if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
  21359. if (x.isZero()) return one;
  21360. pr = Ctor.precision;
  21361. rm = Ctor.rounding;
  21362. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  21363. Ctor.rounding = 1;
  21364. len = x.d.length;
  21365. // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
  21366. // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
  21367. // Estimate the optimum number of times to use the argument reduction.
  21368. // TODO? Estimation reused from cosine() and may not be optimal here.
  21369. if (len < 32) {
  21370. k = Math.ceil(len / 3);
  21371. n = (1 / tinyPow(4, k)).toString();
  21372. } else {
  21373. k = 16;
  21374. n = '2.3283064365386962890625e-10';
  21375. }
  21376. x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
  21377. // Reverse argument reduction
  21378. var cosh2_x,
  21379. i = k,
  21380. d8 = new Ctor(8);
  21381. for (; i--;) {
  21382. cosh2_x = x.times(x);
  21383. x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
  21384. }
  21385. return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
  21386. };
  21387. /*
  21388. * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
  21389. * Decimal.
  21390. *
  21391. * Domain: [-Infinity, Infinity]
  21392. * Range: [-Infinity, Infinity]
  21393. *
  21394. * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
  21395. *
  21396. * sinh(0) = 0
  21397. * sinh(-0) = -0
  21398. * sinh(Infinity) = Infinity
  21399. * sinh(-Infinity) = -Infinity
  21400. * sinh(NaN) = NaN
  21401. *
  21402. * x time taken (ms)
  21403. * 10 2 ms
  21404. * 100 5 ms
  21405. * 1000 14 ms
  21406. * 10000 82 ms
  21407. * 100000 886 ms 1.4033316802130615897e+43429
  21408. * 200000 2613 ms
  21409. * 300000 5407 ms
  21410. * 400000 8824 ms
  21411. * 500000 13026 ms 8.7080643612718084129e+217146
  21412. * 1000000 48543 ms
  21413. *
  21414. * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
  21415. *
  21416. */
  21417. P.hyperbolicSine = P.sinh = function () {
  21418. var k, pr, rm, len,
  21419. x = this,
  21420. Ctor = x.constructor;
  21421. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  21422. pr = Ctor.precision;
  21423. rm = Ctor.rounding;
  21424. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  21425. Ctor.rounding = 1;
  21426. len = x.d.length;
  21427. if (len < 3) {
  21428. x = taylorSeries(Ctor, 2, x, x, true);
  21429. } else {
  21430. // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
  21431. // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
  21432. // 3 multiplications and 1 addition
  21433. // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
  21434. // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
  21435. // 4 multiplications and 2 additions
  21436. // Estimate the optimum number of times to use the argument reduction.
  21437. k = 1.4 * Math.sqrt(len);
  21438. k = k > 16 ? 16 : k | 0;
  21439. x = x.times(1 / tinyPow(5, k));
  21440. x = taylorSeries(Ctor, 2, x, x, true);
  21441. // Reverse argument reduction
  21442. var sinh2_x,
  21443. d5 = new Ctor(5),
  21444. d16 = new Ctor(16),
  21445. d20 = new Ctor(20);
  21446. for (; k--;) {
  21447. sinh2_x = x.times(x);
  21448. x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
  21449. }
  21450. }
  21451. Ctor.precision = pr;
  21452. Ctor.rounding = rm;
  21453. return finalise(x, pr, rm, true);
  21454. };
  21455. /*
  21456. * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
  21457. * Decimal.
  21458. *
  21459. * Domain: [-Infinity, Infinity]
  21460. * Range: [-1, 1]
  21461. *
  21462. * tanh(x) = sinh(x) / cosh(x)
  21463. *
  21464. * tanh(0) = 0
  21465. * tanh(-0) = -0
  21466. * tanh(Infinity) = 1
  21467. * tanh(-Infinity) = -1
  21468. * tanh(NaN) = NaN
  21469. *
  21470. */
  21471. P.hyperbolicTangent = P.tanh = function () {
  21472. var pr, rm,
  21473. x = this,
  21474. Ctor = x.constructor;
  21475. if (!x.isFinite()) return new Ctor(x.s);
  21476. if (x.isZero()) return new Ctor(x);
  21477. pr = Ctor.precision;
  21478. rm = Ctor.rounding;
  21479. Ctor.precision = pr + 7;
  21480. Ctor.rounding = 1;
  21481. return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
  21482. };
  21483. /*
  21484. * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
  21485. * this Decimal.
  21486. *
  21487. * Domain: [-1, 1]
  21488. * Range: [0, pi]
  21489. *
  21490. * acos(x) = pi/2 - asin(x)
  21491. *
  21492. * acos(0) = pi/2
  21493. * acos(-0) = pi/2
  21494. * acos(1) = 0
  21495. * acos(-1) = pi
  21496. * acos(1/2) = pi/3
  21497. * acos(-1/2) = 2*pi/3
  21498. * acos(|x| > 1) = NaN
  21499. * acos(NaN) = NaN
  21500. *
  21501. */
  21502. P.inverseCosine = P.acos = function () {
  21503. var halfPi,
  21504. x = this,
  21505. Ctor = x.constructor,
  21506. k = x.abs().cmp(1),
  21507. pr = Ctor.precision,
  21508. rm = Ctor.rounding;
  21509. if (k !== -1) {
  21510. return k === 0
  21511. // |x| is 1
  21512. ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
  21513. // |x| > 1 or x is NaN
  21514. : new Ctor(NaN);
  21515. }
  21516. if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
  21517. // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
  21518. Ctor.precision = pr + 6;
  21519. Ctor.rounding = 1;
  21520. x = x.asin();
  21521. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  21522. Ctor.precision = pr;
  21523. Ctor.rounding = rm;
  21524. return halfPi.minus(x);
  21525. };
  21526. /*
  21527. * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
  21528. * value of this Decimal.
  21529. *
  21530. * Domain: [1, Infinity]
  21531. * Range: [0, Infinity]
  21532. *
  21533. * acosh(x) = ln(x + sqrt(x^2 - 1))
  21534. *
  21535. * acosh(x < 1) = NaN
  21536. * acosh(NaN) = NaN
  21537. * acosh(Infinity) = Infinity
  21538. * acosh(-Infinity) = NaN
  21539. * acosh(0) = NaN
  21540. * acosh(-0) = NaN
  21541. * acosh(1) = 0
  21542. * acosh(-1) = NaN
  21543. *
  21544. */
  21545. P.inverseHyperbolicCosine = P.acosh = function () {
  21546. var pr, rm,
  21547. x = this,
  21548. Ctor = x.constructor;
  21549. if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
  21550. if (!x.isFinite()) return new Ctor(x);
  21551. pr = Ctor.precision;
  21552. rm = Ctor.rounding;
  21553. Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
  21554. Ctor.rounding = 1;
  21555. external = false;
  21556. x = x.times(x).minus(1).sqrt().plus(x);
  21557. external = true;
  21558. Ctor.precision = pr;
  21559. Ctor.rounding = rm;
  21560. return x.ln();
  21561. };
  21562. /*
  21563. * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
  21564. * of this Decimal.
  21565. *
  21566. * Domain: [-Infinity, Infinity]
  21567. * Range: [-Infinity, Infinity]
  21568. *
  21569. * asinh(x) = ln(x + sqrt(x^2 + 1))
  21570. *
  21571. * asinh(NaN) = NaN
  21572. * asinh(Infinity) = Infinity
  21573. * asinh(-Infinity) = -Infinity
  21574. * asinh(0) = 0
  21575. * asinh(-0) = -0
  21576. *
  21577. */
  21578. P.inverseHyperbolicSine = P.asinh = function () {
  21579. var pr, rm,
  21580. x = this,
  21581. Ctor = x.constructor;
  21582. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  21583. pr = Ctor.precision;
  21584. rm = Ctor.rounding;
  21585. Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
  21586. Ctor.rounding = 1;
  21587. external = false;
  21588. x = x.times(x).plus(1).sqrt().plus(x);
  21589. external = true;
  21590. Ctor.precision = pr;
  21591. Ctor.rounding = rm;
  21592. return x.ln();
  21593. };
  21594. /*
  21595. * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
  21596. * value of this Decimal.
  21597. *
  21598. * Domain: [-1, 1]
  21599. * Range: [-Infinity, Infinity]
  21600. *
  21601. * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
  21602. *
  21603. * atanh(|x| > 1) = NaN
  21604. * atanh(NaN) = NaN
  21605. * atanh(Infinity) = NaN
  21606. * atanh(-Infinity) = NaN
  21607. * atanh(0) = 0
  21608. * atanh(-0) = -0
  21609. * atanh(1) = Infinity
  21610. * atanh(-1) = -Infinity
  21611. *
  21612. */
  21613. P.inverseHyperbolicTangent = P.atanh = function () {
  21614. var pr, rm, wpr, xsd,
  21615. x = this,
  21616. Ctor = x.constructor;
  21617. if (!x.isFinite()) return new Ctor(NaN);
  21618. if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
  21619. pr = Ctor.precision;
  21620. rm = Ctor.rounding;
  21621. xsd = x.sd();
  21622. if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
  21623. Ctor.precision = wpr = xsd - x.e;
  21624. x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
  21625. Ctor.precision = pr + 4;
  21626. Ctor.rounding = 1;
  21627. x = x.ln();
  21628. Ctor.precision = pr;
  21629. Ctor.rounding = rm;
  21630. return x.times(0.5);
  21631. };
  21632. /*
  21633. * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
  21634. * Decimal.
  21635. *
  21636. * Domain: [-Infinity, Infinity]
  21637. * Range: [-pi/2, pi/2]
  21638. *
  21639. * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
  21640. *
  21641. * asin(0) = 0
  21642. * asin(-0) = -0
  21643. * asin(1/2) = pi/6
  21644. * asin(-1/2) = -pi/6
  21645. * asin(1) = pi/2
  21646. * asin(-1) = -pi/2
  21647. * asin(|x| > 1) = NaN
  21648. * asin(NaN) = NaN
  21649. *
  21650. * TODO? Compare performance of Taylor series.
  21651. *
  21652. */
  21653. P.inverseSine = P.asin = function () {
  21654. var halfPi, k,
  21655. pr, rm,
  21656. x = this,
  21657. Ctor = x.constructor;
  21658. if (x.isZero()) return new Ctor(x);
  21659. k = x.abs().cmp(1);
  21660. pr = Ctor.precision;
  21661. rm = Ctor.rounding;
  21662. if (k !== -1) {
  21663. // |x| is 1
  21664. if (k === 0) {
  21665. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  21666. halfPi.s = x.s;
  21667. return halfPi;
  21668. }
  21669. // |x| > 1 or x is NaN
  21670. return new Ctor(NaN);
  21671. }
  21672. // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
  21673. Ctor.precision = pr + 6;
  21674. Ctor.rounding = 1;
  21675. x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
  21676. Ctor.precision = pr;
  21677. Ctor.rounding = rm;
  21678. return x.times(2);
  21679. };
  21680. /*
  21681. * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
  21682. * of this Decimal.
  21683. *
  21684. * Domain: [-Infinity, Infinity]
  21685. * Range: [-pi/2, pi/2]
  21686. *
  21687. * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  21688. *
  21689. * atan(0) = 0
  21690. * atan(-0) = -0
  21691. * atan(1) = pi/4
  21692. * atan(-1) = -pi/4
  21693. * atan(Infinity) = pi/2
  21694. * atan(-Infinity) = -pi/2
  21695. * atan(NaN) = NaN
  21696. *
  21697. */
  21698. P.inverseTangent = P.atan = function () {
  21699. var i, j, k, n, px, t, r, wpr, x2,
  21700. x = this,
  21701. Ctor = x.constructor,
  21702. pr = Ctor.precision,
  21703. rm = Ctor.rounding;
  21704. if (!x.isFinite()) {
  21705. if (!x.s) return new Ctor(NaN);
  21706. if (pr + 4 <= PI_PRECISION) {
  21707. r = getPi(Ctor, pr + 4, rm).times(0.5);
  21708. r.s = x.s;
  21709. return r;
  21710. }
  21711. } else if (x.isZero()) {
  21712. return new Ctor(x);
  21713. } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
  21714. r = getPi(Ctor, pr + 4, rm).times(0.25);
  21715. r.s = x.s;
  21716. return r;
  21717. }
  21718. Ctor.precision = wpr = pr + 10;
  21719. Ctor.rounding = 1;
  21720. // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
  21721. // Argument reduction
  21722. // Ensure |x| < 0.42
  21723. // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
  21724. k = Math.min(28, wpr / LOG_BASE + 2 | 0);
  21725. for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
  21726. external = false;
  21727. j = Math.ceil(wpr / LOG_BASE);
  21728. n = 1;
  21729. x2 = x.times(x);
  21730. r = new Ctor(x);
  21731. px = x;
  21732. // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  21733. for (; i !== -1;) {
  21734. px = px.times(x2);
  21735. t = r.minus(px.div(n += 2));
  21736. px = px.times(x2);
  21737. r = t.plus(px.div(n += 2));
  21738. if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
  21739. }
  21740. if (k) r = r.times(2 << (k - 1));
  21741. external = true;
  21742. return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
  21743. };
  21744. /*
  21745. * Return true if the value of this Decimal is a finite number, otherwise return false.
  21746. *
  21747. */
  21748. P.isFinite = function () {
  21749. return !!this.d;
  21750. };
  21751. /*
  21752. * Return true if the value of this Decimal is an integer, otherwise return false.
  21753. *
  21754. */
  21755. P.isInteger = P.isInt = function () {
  21756. return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
  21757. };
  21758. /*
  21759. * Return true if the value of this Decimal is NaN, otherwise return false.
  21760. *
  21761. */
  21762. P.isNaN = function () {
  21763. return !this.s;
  21764. };
  21765. /*
  21766. * Return true if the value of this Decimal is negative, otherwise return false.
  21767. *
  21768. */
  21769. P.isNegative = P.isNeg = function () {
  21770. return this.s < 0;
  21771. };
  21772. /*
  21773. * Return true if the value of this Decimal is positive, otherwise return false.
  21774. *
  21775. */
  21776. P.isPositive = P.isPos = function () {
  21777. return this.s > 0;
  21778. };
  21779. /*
  21780. * Return true if the value of this Decimal is 0 or -0, otherwise return false.
  21781. *
  21782. */
  21783. P.isZero = function () {
  21784. return !!this.d && this.d[0] === 0;
  21785. };
  21786. /*
  21787. * Return true if the value of this Decimal is less than `y`, otherwise return false.
  21788. *
  21789. */
  21790. P.lessThan = P.lt = function (y) {
  21791. return this.cmp(y) < 0;
  21792. };
  21793. /*
  21794. * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
  21795. *
  21796. */
  21797. P.lessThanOrEqualTo = P.lte = function (y) {
  21798. return this.cmp(y) < 1;
  21799. };
  21800. /*
  21801. * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
  21802. * significant digits using rounding mode `rounding`.
  21803. *
  21804. * If no base is specified, return log[10](arg).
  21805. *
  21806. * log[base](arg) = ln(arg) / ln(base)
  21807. *
  21808. * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
  21809. * otherwise:
  21810. *
  21811. * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
  21812. * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
  21813. * between the result and the correctly rounded result will be one ulp (unit in the last place).
  21814. *
  21815. * log[-b](a) = NaN
  21816. * log[0](a) = NaN
  21817. * log[1](a) = NaN
  21818. * log[NaN](a) = NaN
  21819. * log[Infinity](a) = NaN
  21820. * log[b](0) = -Infinity
  21821. * log[b](-0) = -Infinity
  21822. * log[b](-a) = NaN
  21823. * log[b](1) = 0
  21824. * log[b](Infinity) = Infinity
  21825. * log[b](NaN) = NaN
  21826. *
  21827. * [base] {number|string|Decimal} The base of the logarithm.
  21828. *
  21829. */
  21830. P.logarithm = P.log = function (base) {
  21831. var isBase10, d, denominator, k, inf, num, sd, r,
  21832. arg = this,
  21833. Ctor = arg.constructor,
  21834. pr = Ctor.precision,
  21835. rm = Ctor.rounding,
  21836. guard = 5;
  21837. // Default base is 10.
  21838. if (base == null) {
  21839. base = new Ctor(10);
  21840. isBase10 = true;
  21841. } else {
  21842. base = new Ctor(base);
  21843. d = base.d;
  21844. // Return NaN if base is negative, or non-finite, or is 0 or 1.
  21845. if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
  21846. isBase10 = base.eq(10);
  21847. }
  21848. d = arg.d;
  21849. // Is arg negative, non-finite, 0 or 1?
  21850. if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
  21851. return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
  21852. }
  21853. // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
  21854. // integer power of 10.
  21855. if (isBase10) {
  21856. if (d.length > 1) {
  21857. inf = true;
  21858. } else {
  21859. for (k = d[0]; k % 10 === 0;) k /= 10;
  21860. inf = k !== 1;
  21861. }
  21862. }
  21863. external = false;
  21864. sd = pr + guard;
  21865. num = naturalLogarithm(arg, sd);
  21866. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  21867. // The result will have 5 rounding digits.
  21868. r = divide(num, denominator, sd, 1);
  21869. // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
  21870. // calculate 10 further digits.
  21871. //
  21872. // If the result is known to have an infinite decimal expansion, repeat this until it is clear
  21873. // that the result is above or below the boundary. Otherwise, if after calculating the 10
  21874. // further digits, the last 14 are nines, round up and assume the result is exact.
  21875. // Also assume the result is exact if the last 14 are zero.
  21876. //
  21877. // Example of a result that will be incorrectly rounded:
  21878. // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
  21879. // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
  21880. // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
  21881. // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
  21882. // place is still 2.6.
  21883. if (checkRoundingDigits(r.d, k = pr, rm)) {
  21884. do {
  21885. sd += 10;
  21886. num = naturalLogarithm(arg, sd);
  21887. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  21888. r = divide(num, denominator, sd, 1);
  21889. if (!inf) {
  21890. // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
  21891. if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
  21892. r = finalise(r, pr + 1, 0);
  21893. }
  21894. break;
  21895. }
  21896. } while (checkRoundingDigits(r.d, k += 10, rm));
  21897. }
  21898. external = true;
  21899. return finalise(r, pr, rm);
  21900. };
  21901. /*
  21902. * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
  21903. *
  21904. * arguments {number|string|Decimal}
  21905. *
  21906. P.max = function () {
  21907. Array.prototype.push.call(arguments, this);
  21908. return maxOrMin(this.constructor, arguments, 'lt');
  21909. };
  21910. */
  21911. /*
  21912. * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
  21913. *
  21914. * arguments {number|string|Decimal}
  21915. *
  21916. P.min = function () {
  21917. Array.prototype.push.call(arguments, this);
  21918. return maxOrMin(this.constructor, arguments, 'gt');
  21919. };
  21920. */
  21921. /*
  21922. * n - 0 = n
  21923. * n - N = N
  21924. * n - I = -I
  21925. * 0 - n = -n
  21926. * 0 - 0 = 0
  21927. * 0 - N = N
  21928. * 0 - I = -I
  21929. * N - n = N
  21930. * N - 0 = N
  21931. * N - N = N
  21932. * N - I = N
  21933. * I - n = I
  21934. * I - 0 = I
  21935. * I - N = N
  21936. * I - I = N
  21937. *
  21938. * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
  21939. * significant digits using rounding mode `rounding`.
  21940. *
  21941. */
  21942. P.minus = P.sub = function (y) {
  21943. var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
  21944. x = this,
  21945. Ctor = x.constructor;
  21946. y = new Ctor(y);
  21947. // If either is not finite...
  21948. if (!x.d || !y.d) {
  21949. // Return NaN if either is NaN.
  21950. if (!x.s || !y.s) y = new Ctor(NaN);
  21951. // Return y negated if x is finite and y is ±Infinity.
  21952. else if (x.d) y.s = -y.s;
  21953. // Return x if y is finite and x is ±Infinity.
  21954. // Return x if both are ±Infinity with different signs.
  21955. // Return NaN if both are ±Infinity with the same sign.
  21956. else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
  21957. return y;
  21958. }
  21959. // If signs differ...
  21960. if (x.s != y.s) {
  21961. y.s = -y.s;
  21962. return x.plus(y);
  21963. }
  21964. xd = x.d;
  21965. yd = y.d;
  21966. pr = Ctor.precision;
  21967. rm = Ctor.rounding;
  21968. // If either is zero...
  21969. if (!xd[0] || !yd[0]) {
  21970. // Return y negated if x is zero and y is non-zero.
  21971. if (yd[0]) y.s = -y.s;
  21972. // Return x if y is zero and x is non-zero.
  21973. else if (xd[0]) y = new Ctor(x);
  21974. // Return zero if both are zero.
  21975. // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
  21976. else return new Ctor(rm === 3 ? -0 : 0);
  21977. return external ? finalise(y, pr, rm) : y;
  21978. }
  21979. // x and y are finite, non-zero numbers with the same sign.
  21980. // Calculate base 1e7 exponents.
  21981. e = mathfloor(y.e / LOG_BASE);
  21982. xe = mathfloor(x.e / LOG_BASE);
  21983. xd = xd.slice();
  21984. k = xe - e;
  21985. // If base 1e7 exponents differ...
  21986. if (k) {
  21987. xLTy = k < 0;
  21988. if (xLTy) {
  21989. d = xd;
  21990. k = -k;
  21991. len = yd.length;
  21992. } else {
  21993. d = yd;
  21994. e = xe;
  21995. len = xd.length;
  21996. }
  21997. // Numbers with massively different exponents would result in a very high number of
  21998. // zeros needing to be prepended, but this can be avoided while still ensuring correct
  21999. // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
  22000. i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
  22001. if (k > i) {
  22002. k = i;
  22003. d.length = 1;
  22004. }
  22005. // Prepend zeros to equalise exponents.
  22006. d.reverse();
  22007. for (i = k; i--;) d.push(0);
  22008. d.reverse();
  22009. // Base 1e7 exponents equal.
  22010. } else {
  22011. // Check digits to determine which is the bigger number.
  22012. i = xd.length;
  22013. len = yd.length;
  22014. xLTy = i < len;
  22015. if (xLTy) len = i;
  22016. for (i = 0; i < len; i++) {
  22017. if (xd[i] != yd[i]) {
  22018. xLTy = xd[i] < yd[i];
  22019. break;
  22020. }
  22021. }
  22022. k = 0;
  22023. }
  22024. if (xLTy) {
  22025. d = xd;
  22026. xd = yd;
  22027. yd = d;
  22028. y.s = -y.s;
  22029. }
  22030. len = xd.length;
  22031. // Append zeros to `xd` if shorter.
  22032. // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
  22033. for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
  22034. // Subtract yd from xd.
  22035. for (i = yd.length; i > k;) {
  22036. if (xd[--i] < yd[i]) {
  22037. for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
  22038. --xd[j];
  22039. xd[i] += BASE;
  22040. }
  22041. xd[i] -= yd[i];
  22042. }
  22043. // Remove trailing zeros.
  22044. for (; xd[--len] === 0;) xd.pop();
  22045. // Remove leading zeros and adjust exponent accordingly.
  22046. for (; xd[0] === 0; xd.shift()) --e;
  22047. // Zero?
  22048. if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
  22049. y.d = xd;
  22050. y.e = getBase10Exponent(xd, e);
  22051. return external ? finalise(y, pr, rm) : y;
  22052. };
  22053. /*
  22054. * n % 0 = N
  22055. * n % N = N
  22056. * n % I = n
  22057. * 0 % n = 0
  22058. * -0 % n = -0
  22059. * 0 % 0 = N
  22060. * 0 % N = N
  22061. * 0 % I = 0
  22062. * N % n = N
  22063. * N % 0 = N
  22064. * N % N = N
  22065. * N % I = N
  22066. * I % n = N
  22067. * I % 0 = N
  22068. * I % N = N
  22069. * I % I = N
  22070. *
  22071. * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
  22072. * `precision` significant digits using rounding mode `rounding`.
  22073. *
  22074. * The result depends on the modulo mode.
  22075. *
  22076. */
  22077. P.modulo = P.mod = function (y) {
  22078. var q,
  22079. x = this,
  22080. Ctor = x.constructor;
  22081. y = new Ctor(y);
  22082. // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
  22083. if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
  22084. // Return x if y is ±Infinity or x is ±0.
  22085. if (!y.d || x.d && !x.d[0]) {
  22086. return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
  22087. }
  22088. // Prevent rounding of intermediate calculations.
  22089. external = false;
  22090. if (Ctor.modulo == 9) {
  22091. // Euclidian division: q = sign(y) * floor(x / abs(y))
  22092. // result = x - q * y where 0 <= result < abs(y)
  22093. q = divide(x, y.abs(), 0, 3, 1);
  22094. q.s *= y.s;
  22095. } else {
  22096. q = divide(x, y, 0, Ctor.modulo, 1);
  22097. }
  22098. q = q.times(y);
  22099. external = true;
  22100. return x.minus(q);
  22101. };
  22102. /*
  22103. * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
  22104. * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
  22105. * significant digits using rounding mode `rounding`.
  22106. *
  22107. */
  22108. P.naturalExponential = P.exp = function () {
  22109. return naturalExponential(this);
  22110. };
  22111. /*
  22112. * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
  22113. * rounded to `precision` significant digits using rounding mode `rounding`.
  22114. *
  22115. */
  22116. P.naturalLogarithm = P.ln = function () {
  22117. return naturalLogarithm(this);
  22118. };
  22119. /*
  22120. * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
  22121. * -1.
  22122. *
  22123. */
  22124. P.negated = P.neg = function () {
  22125. var x = new this.constructor(this);
  22126. x.s = -x.s;
  22127. return finalise(x);
  22128. };
  22129. /*
  22130. * n + 0 = n
  22131. * n + N = N
  22132. * n + I = I
  22133. * 0 + n = n
  22134. * 0 + 0 = 0
  22135. * 0 + N = N
  22136. * 0 + I = I
  22137. * N + n = N
  22138. * N + 0 = N
  22139. * N + N = N
  22140. * N + I = N
  22141. * I + n = I
  22142. * I + 0 = I
  22143. * I + N = N
  22144. * I + I = I
  22145. *
  22146. * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
  22147. * significant digits using rounding mode `rounding`.
  22148. *
  22149. */
  22150. P.plus = P.add = function (y) {
  22151. var carry, d, e, i, k, len, pr, rm, xd, yd,
  22152. x = this,
  22153. Ctor = x.constructor;
  22154. y = new Ctor(y);
  22155. // If either is not finite...
  22156. if (!x.d || !y.d) {
  22157. // Return NaN if either is NaN.
  22158. if (!x.s || !y.s) y = new Ctor(NaN);
  22159. // Return x if y is finite and x is ±Infinity.
  22160. // Return x if both are ±Infinity with the same sign.
  22161. // Return NaN if both are ±Infinity with different signs.
  22162. // Return y if x is finite and y is ±Infinity.
  22163. else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
  22164. return y;
  22165. }
  22166. // If signs differ...
  22167. if (x.s != y.s) {
  22168. y.s = -y.s;
  22169. return x.minus(y);
  22170. }
  22171. xd = x.d;
  22172. yd = y.d;
  22173. pr = Ctor.precision;
  22174. rm = Ctor.rounding;
  22175. // If either is zero...
  22176. if (!xd[0] || !yd[0]) {
  22177. // Return x if y is zero.
  22178. // Return y if y is non-zero.
  22179. if (!yd[0]) y = new Ctor(x);
  22180. return external ? finalise(y, pr, rm) : y;
  22181. }
  22182. // x and y are finite, non-zero numbers with the same sign.
  22183. // Calculate base 1e7 exponents.
  22184. k = mathfloor(x.e / LOG_BASE);
  22185. e = mathfloor(y.e / LOG_BASE);
  22186. xd = xd.slice();
  22187. i = k - e;
  22188. // If base 1e7 exponents differ...
  22189. if (i) {
  22190. if (i < 0) {
  22191. d = xd;
  22192. i = -i;
  22193. len = yd.length;
  22194. } else {
  22195. d = yd;
  22196. e = k;
  22197. len = xd.length;
  22198. }
  22199. // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
  22200. k = Math.ceil(pr / LOG_BASE);
  22201. len = k > len ? k + 1 : len + 1;
  22202. if (i > len) {
  22203. i = len;
  22204. d.length = 1;
  22205. }
  22206. // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
  22207. d.reverse();
  22208. for (; i--;) d.push(0);
  22209. d.reverse();
  22210. }
  22211. len = xd.length;
  22212. i = yd.length;
  22213. // If yd is longer than xd, swap xd and yd so xd points to the longer array.
  22214. if (len - i < 0) {
  22215. i = len;
  22216. d = yd;
  22217. yd = xd;
  22218. xd = d;
  22219. }
  22220. // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
  22221. for (carry = 0; i;) {
  22222. carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
  22223. xd[i] %= BASE;
  22224. }
  22225. if (carry) {
  22226. xd.unshift(carry);
  22227. ++e;
  22228. }
  22229. // Remove trailing zeros.
  22230. // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  22231. for (len = xd.length; xd[--len] == 0;) xd.pop();
  22232. y.d = xd;
  22233. y.e = getBase10Exponent(xd, e);
  22234. return external ? finalise(y, pr, rm) : y;
  22235. };
  22236. /*
  22237. * Return the number of significant digits of the value of this Decimal.
  22238. *
  22239. * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
  22240. *
  22241. */
  22242. P.precision = P.sd = function (z) {
  22243. var k,
  22244. x = this;
  22245. if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
  22246. if (x.d) {
  22247. k = getPrecision(x.d);
  22248. if (z && x.e + 1 > k) k = x.e + 1;
  22249. } else {
  22250. k = NaN;
  22251. }
  22252. return k;
  22253. };
  22254. /*
  22255. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
  22256. * rounding mode `rounding`.
  22257. *
  22258. */
  22259. P.round = function () {
  22260. var x = this,
  22261. Ctor = x.constructor;
  22262. return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
  22263. };
  22264. /*
  22265. * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
  22266. *
  22267. * Domain: [-Infinity, Infinity]
  22268. * Range: [-1, 1]
  22269. *
  22270. * sin(x) = x - x^3/3! + x^5/5! - ...
  22271. *
  22272. * sin(0) = 0
  22273. * sin(-0) = -0
  22274. * sin(Infinity) = NaN
  22275. * sin(-Infinity) = NaN
  22276. * sin(NaN) = NaN
  22277. *
  22278. */
  22279. P.sine = P.sin = function () {
  22280. var pr, rm,
  22281. x = this,
  22282. Ctor = x.constructor;
  22283. if (!x.isFinite()) return new Ctor(NaN);
  22284. if (x.isZero()) return new Ctor(x);
  22285. pr = Ctor.precision;
  22286. rm = Ctor.rounding;
  22287. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  22288. Ctor.rounding = 1;
  22289. x = sine(Ctor, toLessThanHalfPi(Ctor, x));
  22290. Ctor.precision = pr;
  22291. Ctor.rounding = rm;
  22292. return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
  22293. };
  22294. /*
  22295. * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
  22296. * significant digits using rounding mode `rounding`.
  22297. *
  22298. * sqrt(-n) = N
  22299. * sqrt(N) = N
  22300. * sqrt(-I) = N
  22301. * sqrt(I) = I
  22302. * sqrt(0) = 0
  22303. * sqrt(-0) = -0
  22304. *
  22305. */
  22306. P.squareRoot = P.sqrt = function () {
  22307. var m, n, sd, r, rep, t,
  22308. x = this,
  22309. d = x.d,
  22310. e = x.e,
  22311. s = x.s,
  22312. Ctor = x.constructor;
  22313. // Negative/NaN/Infinity/zero?
  22314. if (s !== 1 || !d || !d[0]) {
  22315. return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
  22316. }
  22317. external = false;
  22318. // Initial estimate.
  22319. s = Math.sqrt(+x);
  22320. // Math.sqrt underflow/overflow?
  22321. // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  22322. if (s == 0 || s == 1 / 0) {
  22323. n = digitsToString(d);
  22324. if ((n.length + e) % 2 == 0) n += '0';
  22325. s = Math.sqrt(n);
  22326. e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
  22327. if (s == 1 / 0) {
  22328. n = '1e' + e;
  22329. } else {
  22330. n = s.toExponential();
  22331. n = n.slice(0, n.indexOf('e') + 1) + e;
  22332. }
  22333. r = new Ctor(n);
  22334. } else {
  22335. r = new Ctor(s.toString());
  22336. }
  22337. sd = (e = Ctor.precision) + 3;
  22338. // Newton-Raphson iteration.
  22339. for (;;) {
  22340. t = r;
  22341. r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
  22342. // TODO? Replace with for-loop and checkRoundingDigits.
  22343. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  22344. n = n.slice(sd - 3, sd + 1);
  22345. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
  22346. // 4999, i.e. approaching a rounding boundary, continue the iteration.
  22347. if (n == '9999' || !rep && n == '4999') {
  22348. // On the first iteration only, check to see if rounding up gives the exact result as the
  22349. // nines may infinitely repeat.
  22350. if (!rep) {
  22351. finalise(t, e + 1, 0);
  22352. if (t.times(t).eq(x)) {
  22353. r = t;
  22354. break;
  22355. }
  22356. }
  22357. sd += 4;
  22358. rep = 1;
  22359. } else {
  22360. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  22361. // If not, then there are further digits and m will be truthy.
  22362. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  22363. // Truncate to the first rounding digit.
  22364. finalise(r, e + 1, 1);
  22365. m = !r.times(r).eq(x);
  22366. }
  22367. break;
  22368. }
  22369. }
  22370. }
  22371. external = true;
  22372. return finalise(r, e, Ctor.rounding, m);
  22373. };
  22374. /*
  22375. * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
  22376. *
  22377. * Domain: [-Infinity, Infinity]
  22378. * Range: [-Infinity, Infinity]
  22379. *
  22380. * tan(0) = 0
  22381. * tan(-0) = -0
  22382. * tan(Infinity) = NaN
  22383. * tan(-Infinity) = NaN
  22384. * tan(NaN) = NaN
  22385. *
  22386. */
  22387. P.tangent = P.tan = function () {
  22388. var pr, rm,
  22389. x = this,
  22390. Ctor = x.constructor;
  22391. if (!x.isFinite()) return new Ctor(NaN);
  22392. if (x.isZero()) return new Ctor(x);
  22393. pr = Ctor.precision;
  22394. rm = Ctor.rounding;
  22395. Ctor.precision = pr + 10;
  22396. Ctor.rounding = 1;
  22397. x = x.sin();
  22398. x.s = 1;
  22399. x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
  22400. Ctor.precision = pr;
  22401. Ctor.rounding = rm;
  22402. return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
  22403. };
  22404. /*
  22405. * n * 0 = 0
  22406. * n * N = N
  22407. * n * I = I
  22408. * 0 * n = 0
  22409. * 0 * 0 = 0
  22410. * 0 * N = N
  22411. * 0 * I = N
  22412. * N * n = N
  22413. * N * 0 = N
  22414. * N * N = N
  22415. * N * I = N
  22416. * I * n = I
  22417. * I * 0 = N
  22418. * I * N = N
  22419. * I * I = I
  22420. *
  22421. * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
  22422. * digits using rounding mode `rounding`.
  22423. *
  22424. */
  22425. P.times = P.mul = function (y) {
  22426. var carry, e, i, k, r, rL, t, xdL, ydL,
  22427. x = this,
  22428. Ctor = x.constructor,
  22429. xd = x.d,
  22430. yd = (y = new Ctor(y)).d;
  22431. y.s *= x.s;
  22432. // If either is NaN, ±Infinity or ±0...
  22433. if (!xd || !xd[0] || !yd || !yd[0]) {
  22434. return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
  22435. // Return NaN if either is NaN.
  22436. // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
  22437. ? NaN
  22438. // Return ±Infinity if either is ±Infinity.
  22439. // Return ±0 if either is ±0.
  22440. : !xd || !yd ? y.s / 0 : y.s * 0);
  22441. }
  22442. e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
  22443. xdL = xd.length;
  22444. ydL = yd.length;
  22445. // Ensure xd points to the longer array.
  22446. if (xdL < ydL) {
  22447. r = xd;
  22448. xd = yd;
  22449. yd = r;
  22450. rL = xdL;
  22451. xdL = ydL;
  22452. ydL = rL;
  22453. }
  22454. // Initialise the result array with zeros.
  22455. r = [];
  22456. rL = xdL + ydL;
  22457. for (i = rL; i--;) r.push(0);
  22458. // Multiply!
  22459. for (i = ydL; --i >= 0;) {
  22460. carry = 0;
  22461. for (k = xdL + i; k > i;) {
  22462. t = r[k] + yd[i] * xd[k - i - 1] + carry;
  22463. r[k--] = t % BASE | 0;
  22464. carry = t / BASE | 0;
  22465. }
  22466. r[k] = (r[k] + carry) % BASE | 0;
  22467. }
  22468. // Remove trailing zeros.
  22469. for (; !r[--rL];) r.pop();
  22470. if (carry) ++e;
  22471. else r.shift();
  22472. y.d = r;
  22473. y.e = getBase10Exponent(r, e);
  22474. return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
  22475. };
  22476. /*
  22477. * Return a string representing the value of this Decimal in base 2, round to `sd` significant
  22478. * digits using rounding mode `rm`.
  22479. *
  22480. * If the optional `sd` argument is present then return binary exponential notation.
  22481. *
  22482. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22483. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22484. *
  22485. */
  22486. P.toBinary = function (sd, rm) {
  22487. return toStringBinary(this, 2, sd, rm);
  22488. };
  22489. /*
  22490. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
  22491. * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
  22492. *
  22493. * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
  22494. *
  22495. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  22496. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22497. *
  22498. */
  22499. P.toDecimalPlaces = P.toDP = function (dp, rm) {
  22500. var x = this,
  22501. Ctor = x.constructor;
  22502. x = new Ctor(x);
  22503. if (dp === void 0) return x;
  22504. checkInt32(dp, 0, MAX_DIGITS);
  22505. if (rm === void 0) rm = Ctor.rounding;
  22506. else checkInt32(rm, 0, 8);
  22507. return finalise(x, dp + x.e + 1, rm);
  22508. };
  22509. /*
  22510. * Return a string representing the value of this Decimal in exponential notation rounded to
  22511. * `dp` fixed decimal places using rounding mode `rounding`.
  22512. *
  22513. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  22514. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22515. *
  22516. */
  22517. P.toExponential = function (dp, rm) {
  22518. var str,
  22519. x = this,
  22520. Ctor = x.constructor;
  22521. if (dp === void 0) {
  22522. str = finiteToString(x, true);
  22523. } else {
  22524. checkInt32(dp, 0, MAX_DIGITS);
  22525. if (rm === void 0) rm = Ctor.rounding;
  22526. else checkInt32(rm, 0, 8);
  22527. x = finalise(new Ctor(x), dp + 1, rm);
  22528. str = finiteToString(x, true, dp + 1);
  22529. }
  22530. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22531. };
  22532. /*
  22533. * Return a string representing the value of this Decimal in normal (fixed-point) notation to
  22534. * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
  22535. * omitted.
  22536. *
  22537. * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
  22538. *
  22539. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  22540. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22541. *
  22542. * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
  22543. * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
  22544. * (-0).toFixed(3) is '0.000'.
  22545. * (-0.5).toFixed(0) is '-0'.
  22546. *
  22547. */
  22548. P.toFixed = function (dp, rm) {
  22549. var str, y,
  22550. x = this,
  22551. Ctor = x.constructor;
  22552. if (dp === void 0) {
  22553. str = finiteToString(x);
  22554. } else {
  22555. checkInt32(dp, 0, MAX_DIGITS);
  22556. if (rm === void 0) rm = Ctor.rounding;
  22557. else checkInt32(rm, 0, 8);
  22558. y = finalise(new Ctor(x), dp + x.e + 1, rm);
  22559. str = finiteToString(y, false, dp + y.e + 1);
  22560. }
  22561. // To determine whether to add the minus sign look at the value before it was rounded,
  22562. // i.e. look at `x` rather than `y`.
  22563. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22564. };
  22565. /*
  22566. * Return an array representing the value of this Decimal as a simple fraction with an integer
  22567. * numerator and an integer denominator.
  22568. *
  22569. * The denominator will be a positive non-zero value less than or equal to the specified maximum
  22570. * denominator. If a maximum denominator is not specified, the denominator will be the lowest
  22571. * value necessary to represent the number exactly.
  22572. *
  22573. * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
  22574. *
  22575. */
  22576. P.toFraction = function (maxD) {
  22577. var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
  22578. x = this,
  22579. xd = x.d,
  22580. Ctor = x.constructor;
  22581. if (!xd) return new Ctor(x);
  22582. n1 = d0 = new Ctor(1);
  22583. d1 = n0 = new Ctor(0);
  22584. d = new Ctor(d1);
  22585. e = d.e = getPrecision(xd) - x.e - 1;
  22586. k = e % LOG_BASE;
  22587. d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
  22588. if (maxD == null) {
  22589. // d is 10**e, the minimum max-denominator needed.
  22590. maxD = e > 0 ? d : n1;
  22591. } else {
  22592. n = new Ctor(maxD);
  22593. if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
  22594. maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
  22595. }
  22596. external = false;
  22597. n = new Ctor(digitsToString(xd));
  22598. pr = Ctor.precision;
  22599. Ctor.precision = e = xd.length * LOG_BASE * 2;
  22600. for (;;) {
  22601. q = divide(n, d, 0, 1, 1);
  22602. d2 = d0.plus(q.times(d1));
  22603. if (d2.cmp(maxD) == 1) break;
  22604. d0 = d1;
  22605. d1 = d2;
  22606. d2 = n1;
  22607. n1 = n0.plus(q.times(d2));
  22608. n0 = d2;
  22609. d2 = d;
  22610. d = n.minus(q.times(d2));
  22611. n = d2;
  22612. }
  22613. d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
  22614. n0 = n0.plus(d2.times(n1));
  22615. d0 = d0.plus(d2.times(d1));
  22616. n0.s = n1.s = x.s;
  22617. // Determine which fraction is closer to x, n0/d0 or n1/d1?
  22618. r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
  22619. ? [n1, d1] : [n0, d0];
  22620. Ctor.precision = pr;
  22621. external = true;
  22622. return r;
  22623. };
  22624. /*
  22625. * Return a string representing the value of this Decimal in base 16, round to `sd` significant
  22626. * digits using rounding mode `rm`.
  22627. *
  22628. * If the optional `sd` argument is present then return binary exponential notation.
  22629. *
  22630. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22631. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22632. *
  22633. */
  22634. P.toHexadecimal = P.toHex = function (sd, rm) {
  22635. return toStringBinary(this, 16, sd, rm);
  22636. };
  22637. /*
  22638. * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding
  22639. * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.
  22640. *
  22641. * The return value will always have the same sign as this Decimal, unless either this Decimal
  22642. * or `y` is NaN, in which case the return value will be also be NaN.
  22643. *
  22644. * The return value is not affected by the value of `precision`.
  22645. *
  22646. * y {number|string|Decimal} The magnitude to round to a multiple of.
  22647. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22648. *
  22649. * 'toNearest() rounding mode not an integer: {rm}'
  22650. * 'toNearest() rounding mode out of range: {rm}'
  22651. *
  22652. */
  22653. P.toNearest = function (y, rm) {
  22654. var x = this,
  22655. Ctor = x.constructor;
  22656. x = new Ctor(x);
  22657. if (y == null) {
  22658. // If x is not finite, return x.
  22659. if (!x.d) return x;
  22660. y = new Ctor(1);
  22661. rm = Ctor.rounding;
  22662. } else {
  22663. y = new Ctor(y);
  22664. if (rm === void 0) {
  22665. rm = Ctor.rounding;
  22666. } else {
  22667. checkInt32(rm, 0, 8);
  22668. }
  22669. // If x is not finite, return x if y is not NaN, else NaN.
  22670. if (!x.d) return y.s ? x : y;
  22671. // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
  22672. if (!y.d) {
  22673. if (y.s) y.s = x.s;
  22674. return y;
  22675. }
  22676. }
  22677. // If y is not zero, calculate the nearest multiple of y to x.
  22678. if (y.d[0]) {
  22679. external = false;
  22680. x = divide(x, y, 0, rm, 1).times(y);
  22681. external = true;
  22682. finalise(x);
  22683. // If y is zero, return zero with the sign of x.
  22684. } else {
  22685. y.s = x.s;
  22686. x = y;
  22687. }
  22688. return x;
  22689. };
  22690. /*
  22691. * Return the value of this Decimal converted to a number primitive.
  22692. * Zero keeps its sign.
  22693. *
  22694. */
  22695. P.toNumber = function () {
  22696. return +this;
  22697. };
  22698. /*
  22699. * Return a string representing the value of this Decimal in base 8, round to `sd` significant
  22700. * digits using rounding mode `rm`.
  22701. *
  22702. * If the optional `sd` argument is present then return binary exponential notation.
  22703. *
  22704. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22705. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22706. *
  22707. */
  22708. P.toOctal = function (sd, rm) {
  22709. return toStringBinary(this, 8, sd, rm);
  22710. };
  22711. /*
  22712. * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
  22713. * to `precision` significant digits using rounding mode `rounding`.
  22714. *
  22715. * ECMAScript compliant.
  22716. *
  22717. * pow(x, NaN) = NaN
  22718. * pow(x, ±0) = 1
  22719. * pow(NaN, non-zero) = NaN
  22720. * pow(abs(x) > 1, +Infinity) = +Infinity
  22721. * pow(abs(x) > 1, -Infinity) = +0
  22722. * pow(abs(x) == 1, ±Infinity) = NaN
  22723. * pow(abs(x) < 1, +Infinity) = +0
  22724. * pow(abs(x) < 1, -Infinity) = +Infinity
  22725. * pow(+Infinity, y > 0) = +Infinity
  22726. * pow(+Infinity, y < 0) = +0
  22727. * pow(-Infinity, odd integer > 0) = -Infinity
  22728. * pow(-Infinity, even integer > 0) = +Infinity
  22729. * pow(-Infinity, odd integer < 0) = -0
  22730. * pow(-Infinity, even integer < 0) = +0
  22731. * pow(+0, y > 0) = +0
  22732. * pow(+0, y < 0) = +Infinity
  22733. * pow(-0, odd integer > 0) = -0
  22734. * pow(-0, even integer > 0) = +0
  22735. * pow(-0, odd integer < 0) = -Infinity
  22736. * pow(-0, even integer < 0) = +Infinity
  22737. * pow(finite x < 0, finite non-integer) = NaN
  22738. *
  22739. * For non-integer or very large exponents pow(x, y) is calculated using
  22740. *
  22741. * x^y = exp(y*ln(x))
  22742. *
  22743. * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
  22744. * probability of an incorrectly rounded result
  22745. * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
  22746. * i.e. 1 in 250,000,000,000,000
  22747. *
  22748. * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
  22749. *
  22750. * y {number|string|Decimal} The power to which to raise this Decimal.
  22751. *
  22752. */
  22753. P.toPower = P.pow = function (y) {
  22754. var e, k, pr, r, rm, s,
  22755. x = this,
  22756. Ctor = x.constructor,
  22757. yn = +(y = new Ctor(y));
  22758. // Either ±Infinity, NaN or ±0?
  22759. if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
  22760. x = new Ctor(x);
  22761. if (x.eq(1)) return x;
  22762. pr = Ctor.precision;
  22763. rm = Ctor.rounding;
  22764. if (y.eq(1)) return finalise(x, pr, rm);
  22765. // y exponent
  22766. e = mathfloor(y.e / LOG_BASE);
  22767. // If y is a small integer use the 'exponentiation by squaring' algorithm.
  22768. if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
  22769. r = intPow(Ctor, x, k, pr);
  22770. return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
  22771. }
  22772. s = x.s;
  22773. // if x is negative
  22774. if (s < 0) {
  22775. // if y is not an integer
  22776. if (e < y.d.length - 1) return new Ctor(NaN);
  22777. // Result is positive if x is negative and the last digit of integer y is even.
  22778. if ((y.d[e] & 1) == 0) s = 1;
  22779. // if x.eq(-1)
  22780. if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
  22781. x.s = s;
  22782. return x;
  22783. }
  22784. }
  22785. // Estimate result exponent.
  22786. // x^y = 10^e, where e = y * log10(x)
  22787. // log10(x) = log10(x_significand) + x_exponent
  22788. // log10(x_significand) = ln(x_significand) / ln(10)
  22789. k = mathpow(+x, yn);
  22790. e = k == 0 || !isFinite(k)
  22791. ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
  22792. : new Ctor(k + '').e;
  22793. // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
  22794. // Overflow/underflow?
  22795. if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);
  22796. external = false;
  22797. Ctor.rounding = x.s = 1;
  22798. // Estimate the extra guard digits needed to ensure five correct rounding digits from
  22799. // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
  22800. // new Decimal(2.32456).pow('2087987436534566.46411')
  22801. // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
  22802. k = Math.min(12, (e + '').length);
  22803. // r = x^y = exp(y*ln(x))
  22804. r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
  22805. // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
  22806. if (r.d) {
  22807. // Truncate to the required precision plus five rounding digits.
  22808. r = finalise(r, pr + 5, 1);
  22809. // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
  22810. // the result.
  22811. if (checkRoundingDigits(r.d, pr, rm)) {
  22812. e = pr + 10;
  22813. // Truncate to the increased precision plus five rounding digits.
  22814. r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
  22815. // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
  22816. if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
  22817. r = finalise(r, pr + 1, 0);
  22818. }
  22819. }
  22820. }
  22821. r.s = s;
  22822. external = true;
  22823. Ctor.rounding = rm;
  22824. return finalise(r, pr, rm);
  22825. };
  22826. /*
  22827. * Return a string representing the value of this Decimal rounded to `sd` significant digits
  22828. * using rounding mode `rounding`.
  22829. *
  22830. * Return exponential notation if `sd` is less than the number of digits necessary to represent
  22831. * the integer part of the value in normal notation.
  22832. *
  22833. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22834. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22835. *
  22836. */
  22837. P.toPrecision = function (sd, rm) {
  22838. var str,
  22839. x = this,
  22840. Ctor = x.constructor;
  22841. if (sd === void 0) {
  22842. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  22843. } else {
  22844. checkInt32(sd, 1, MAX_DIGITS);
  22845. if (rm === void 0) rm = Ctor.rounding;
  22846. else checkInt32(rm, 0, 8);
  22847. x = finalise(new Ctor(x), sd, rm);
  22848. str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
  22849. }
  22850. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22851. };
  22852. /*
  22853. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
  22854. * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
  22855. * omitted.
  22856. *
  22857. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22858. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22859. *
  22860. * 'toSD() digits out of range: {sd}'
  22861. * 'toSD() digits not an integer: {sd}'
  22862. * 'toSD() rounding mode not an integer: {rm}'
  22863. * 'toSD() rounding mode out of range: {rm}'
  22864. *
  22865. */
  22866. P.toSignificantDigits = P.toSD = function (sd, rm) {
  22867. var x = this,
  22868. Ctor = x.constructor;
  22869. if (sd === void 0) {
  22870. sd = Ctor.precision;
  22871. rm = Ctor.rounding;
  22872. } else {
  22873. checkInt32(sd, 1, MAX_DIGITS);
  22874. if (rm === void 0) rm = Ctor.rounding;
  22875. else checkInt32(rm, 0, 8);
  22876. }
  22877. return finalise(new Ctor(x), sd, rm);
  22878. };
  22879. /*
  22880. * Return a string representing the value of this Decimal.
  22881. *
  22882. * Return exponential notation if this Decimal has a positive exponent equal to or greater than
  22883. * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
  22884. *
  22885. */
  22886. P.toString = function () {
  22887. var x = this,
  22888. Ctor = x.constructor,
  22889. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  22890. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22891. };
  22892. /*
  22893. * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
  22894. *
  22895. */
  22896. P.truncated = P.trunc = function () {
  22897. return finalise(new this.constructor(this), this.e + 1, 1);
  22898. };
  22899. /*
  22900. * Return a string representing the value of this Decimal.
  22901. * Unlike `toString`, negative zero will include the minus sign.
  22902. *
  22903. */
  22904. P.valueOf = P.toJSON = function () {
  22905. var x = this,
  22906. Ctor = x.constructor,
  22907. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  22908. return x.isNeg() ? '-' + str : str;
  22909. };
  22910. /*
  22911. // Add aliases to match BigDecimal method names.
  22912. // P.add = P.plus;
  22913. P.subtract = P.minus;
  22914. P.multiply = P.times;
  22915. P.divide = P.div;
  22916. P.remainder = P.mod;
  22917. P.compareTo = P.cmp;
  22918. P.negate = P.neg;
  22919. */
  22920. // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
  22921. /*
  22922. * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
  22923. * finiteToString, naturalExponential, naturalLogarithm
  22924. * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
  22925. * P.toPrecision, P.toSignificantDigits, toStringBinary, random
  22926. * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm
  22927. * convertBase toStringBinary, parseOther
  22928. * cos P.cos
  22929. * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
  22930. * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
  22931. * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
  22932. * taylorSeries, atan2, parseOther
  22933. * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
  22934. * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
  22935. * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
  22936. * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
  22937. * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
  22938. * P.truncated, divide, getLn10, getPi, naturalExponential,
  22939. * naturalLogarithm, ceil, floor, round, trunc
  22940. * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
  22941. * toStringBinary
  22942. * getBase10Exponent P.minus, P.plus, P.times, parseOther
  22943. * getLn10 P.logarithm, naturalLogarithm
  22944. * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
  22945. * getPrecision P.precision, P.toFraction
  22946. * getZeroString digitsToString, finiteToString
  22947. * intPow P.toPower, parseOther
  22948. * isOdd toLessThanHalfPi
  22949. * maxOrMin max, min
  22950. * naturalExponential P.naturalExponential, P.toPower
  22951. * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
  22952. * P.toPower, naturalExponential
  22953. * nonFiniteToString finiteToString, toStringBinary
  22954. * parseDecimal Decimal
  22955. * parseOther Decimal
  22956. * sin P.sin
  22957. * taylorSeries P.cosh, P.sinh, cos, sin
  22958. * toLessThanHalfPi P.cos, P.sin
  22959. * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal
  22960. * truncate intPow
  22961. *
  22962. * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
  22963. * naturalLogarithm, config, parseOther, random, Decimal
  22964. */
  22965. function digitsToString(d) {
  22966. var i, k, ws,
  22967. indexOfLastWord = d.length - 1,
  22968. str = '',
  22969. w = d[0];
  22970. if (indexOfLastWord > 0) {
  22971. str += w;
  22972. for (i = 1; i < indexOfLastWord; i++) {
  22973. ws = d[i] + '';
  22974. k = LOG_BASE - ws.length;
  22975. if (k) str += getZeroString(k);
  22976. str += ws;
  22977. }
  22978. w = d[i];
  22979. ws = w + '';
  22980. k = LOG_BASE - ws.length;
  22981. if (k) str += getZeroString(k);
  22982. } else if (w === 0) {
  22983. return '0';
  22984. }
  22985. // Remove trailing zeros of last w.
  22986. for (; w % 10 === 0;) w /= 10;
  22987. return str + w;
  22988. }
  22989. function checkInt32(i, min, max) {
  22990. if (i !== ~~i || i < min || i > max) {
  22991. throw Error(invalidArgument + i);
  22992. }
  22993. }
  22994. /*
  22995. * Check 5 rounding digits if `repeating` is null, 4 otherwise.
  22996. * `repeating == null` if caller is `log` or `pow`,
  22997. * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
  22998. */
  22999. function checkRoundingDigits(d, i, rm, repeating) {
  23000. var di, k, r, rd;
  23001. // Get the length of the first word of the array d.
  23002. for (k = d[0]; k >= 10; k /= 10) --i;
  23003. // Is the rounding digit in the first word of d?
  23004. if (--i < 0) {
  23005. i += LOG_BASE;
  23006. di = 0;
  23007. } else {
  23008. di = Math.ceil((i + 1) / LOG_BASE);
  23009. i %= LOG_BASE;
  23010. }
  23011. // i is the index (0 - 6) of the rounding digit.
  23012. // E.g. if within the word 3487563 the first rounding digit is 5,
  23013. // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
  23014. k = mathpow(10, LOG_BASE - i);
  23015. rd = d[di] % k | 0;
  23016. if (repeating == null) {
  23017. if (i < 3) {
  23018. if (i == 0) rd = rd / 100 | 0;
  23019. else if (i == 1) rd = rd / 10 | 0;
  23020. r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
  23021. } else {
  23022. r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
  23023. (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
  23024. (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
  23025. }
  23026. } else {
  23027. if (i < 4) {
  23028. if (i == 0) rd = rd / 1000 | 0;
  23029. else if (i == 1) rd = rd / 100 | 0;
  23030. else if (i == 2) rd = rd / 10 | 0;
  23031. r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
  23032. } else {
  23033. r = ((repeating || rm < 4) && rd + 1 == k ||
  23034. (!repeating && rm > 3) && rd + 1 == k / 2) &&
  23035. (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
  23036. }
  23037. }
  23038. return r;
  23039. }
  23040. // Convert string of `baseIn` to an array of numbers of `baseOut`.
  23041. // Eg. convertBase('255', 10, 16) returns [15, 15].
  23042. // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
  23043. function convertBase(str, baseIn, baseOut) {
  23044. var j,
  23045. arr = [0],
  23046. arrL,
  23047. i = 0,
  23048. strL = str.length;
  23049. for (; i < strL;) {
  23050. for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
  23051. arr[0] += NUMERALS.indexOf(str.charAt(i++));
  23052. for (j = 0; j < arr.length; j++) {
  23053. if (arr[j] > baseOut - 1) {
  23054. if (arr[j + 1] === void 0) arr[j + 1] = 0;
  23055. arr[j + 1] += arr[j] / baseOut | 0;
  23056. arr[j] %= baseOut;
  23057. }
  23058. }
  23059. }
  23060. return arr.reverse();
  23061. }
  23062. /*
  23063. * cos(x) = 1 - x^2/2! + x^4/4! - ...
  23064. * |x| < pi/2
  23065. *
  23066. */
  23067. function cosine(Ctor, x) {
  23068. var k, y,
  23069. len = x.d.length;
  23070. // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
  23071. // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
  23072. // Estimate the optimum number of times to use the argument reduction.
  23073. if (len < 32) {
  23074. k = Math.ceil(len / 3);
  23075. y = (1 / tinyPow(4, k)).toString();
  23076. } else {
  23077. k = 16;
  23078. y = '2.3283064365386962890625e-10';
  23079. }
  23080. Ctor.precision += k;
  23081. x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
  23082. // Reverse argument reduction
  23083. for (var i = k; i--;) {
  23084. var cos2x = x.times(x);
  23085. x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
  23086. }
  23087. Ctor.precision -= k;
  23088. return x;
  23089. }
  23090. /*
  23091. * Perform division in the specified base.
  23092. */
  23093. var divide = (function () {
  23094. // Assumes non-zero x and k, and hence non-zero result.
  23095. function multiplyInteger(x, k, base) {
  23096. var temp,
  23097. carry = 0,
  23098. i = x.length;
  23099. for (x = x.slice(); i--;) {
  23100. temp = x[i] * k + carry;
  23101. x[i] = temp % base | 0;
  23102. carry = temp / base | 0;
  23103. }
  23104. if (carry) x.unshift(carry);
  23105. return x;
  23106. }
  23107. function compare(a, b, aL, bL) {
  23108. var i, r;
  23109. if (aL != bL) {
  23110. r = aL > bL ? 1 : -1;
  23111. } else {
  23112. for (i = r = 0; i < aL; i++) {
  23113. if (a[i] != b[i]) {
  23114. r = a[i] > b[i] ? 1 : -1;
  23115. break;
  23116. }
  23117. }
  23118. }
  23119. return r;
  23120. }
  23121. function subtract(a, b, aL, base) {
  23122. var i = 0;
  23123. // Subtract b from a.
  23124. for (; aL--;) {
  23125. a[aL] -= i;
  23126. i = a[aL] < b[aL] ? 1 : 0;
  23127. a[aL] = i * base + a[aL] - b[aL];
  23128. }
  23129. // Remove leading zeros.
  23130. for (; !a[0] && a.length > 1;) a.shift();
  23131. }
  23132. return function (x, y, pr, rm, dp, base) {
  23133. var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
  23134. yL, yz,
  23135. Ctor = x.constructor,
  23136. sign = x.s == y.s ? 1 : -1,
  23137. xd = x.d,
  23138. yd = y.d;
  23139. // Either NaN, Infinity or 0?
  23140. if (!xd || !xd[0] || !yd || !yd[0]) {
  23141. return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
  23142. !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
  23143. // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
  23144. xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
  23145. }
  23146. if (base) {
  23147. logBase = 1;
  23148. e = x.e - y.e;
  23149. } else {
  23150. base = BASE;
  23151. logBase = LOG_BASE;
  23152. e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
  23153. }
  23154. yL = yd.length;
  23155. xL = xd.length;
  23156. q = new Ctor(sign);
  23157. qd = q.d = [];
  23158. // Result exponent may be one less than e.
  23159. // The digit array of a Decimal from toStringBinary may have trailing zeros.
  23160. for (i = 0; yd[i] == (xd[i] || 0); i++);
  23161. if (yd[i] > (xd[i] || 0)) e--;
  23162. if (pr == null) {
  23163. sd = pr = Ctor.precision;
  23164. rm = Ctor.rounding;
  23165. } else if (dp) {
  23166. sd = pr + (x.e - y.e) + 1;
  23167. } else {
  23168. sd = pr;
  23169. }
  23170. if (sd < 0) {
  23171. qd.push(1);
  23172. more = true;
  23173. } else {
  23174. // Convert precision in number of base 10 digits to base 1e7 digits.
  23175. sd = sd / logBase + 2 | 0;
  23176. i = 0;
  23177. // divisor < 1e7
  23178. if (yL == 1) {
  23179. k = 0;
  23180. yd = yd[0];
  23181. sd++;
  23182. // k is the carry.
  23183. for (; (i < xL || k) && sd--; i++) {
  23184. t = k * base + (xd[i] || 0);
  23185. qd[i] = t / yd | 0;
  23186. k = t % yd | 0;
  23187. }
  23188. more = k || i < xL;
  23189. // divisor >= 1e7
  23190. } else {
  23191. // Normalise xd and yd so highest order digit of yd is >= base/2
  23192. k = base / (yd[0] + 1) | 0;
  23193. if (k > 1) {
  23194. yd = multiplyInteger(yd, k, base);
  23195. xd = multiplyInteger(xd, k, base);
  23196. yL = yd.length;
  23197. xL = xd.length;
  23198. }
  23199. xi = yL;
  23200. rem = xd.slice(0, yL);
  23201. remL = rem.length;
  23202. // Add zeros to make remainder as long as divisor.
  23203. for (; remL < yL;) rem[remL++] = 0;
  23204. yz = yd.slice();
  23205. yz.unshift(0);
  23206. yd0 = yd[0];
  23207. if (yd[1] >= base / 2) ++yd0;
  23208. do {
  23209. k = 0;
  23210. // Compare divisor and remainder.
  23211. cmp = compare(yd, rem, yL, remL);
  23212. // If divisor < remainder.
  23213. if (cmp < 0) {
  23214. // Calculate trial digit, k.
  23215. rem0 = rem[0];
  23216. if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
  23217. // k will be how many times the divisor goes into the current remainder.
  23218. k = rem0 / yd0 | 0;
  23219. // Algorithm:
  23220. // 1. product = divisor * trial digit (k)
  23221. // 2. if product > remainder: product -= divisor, k--
  23222. // 3. remainder -= product
  23223. // 4. if product was < remainder at 2:
  23224. // 5. compare new remainder and divisor
  23225. // 6. If remainder > divisor: remainder -= divisor, k++
  23226. if (k > 1) {
  23227. if (k >= base) k = base - 1;
  23228. // product = divisor * trial digit.
  23229. prod = multiplyInteger(yd, k, base);
  23230. prodL = prod.length;
  23231. remL = rem.length;
  23232. // Compare product and remainder.
  23233. cmp = compare(prod, rem, prodL, remL);
  23234. // product > remainder.
  23235. if (cmp == 1) {
  23236. k--;
  23237. // Subtract divisor from product.
  23238. subtract(prod, yL < prodL ? yz : yd, prodL, base);
  23239. }
  23240. } else {
  23241. // cmp is -1.
  23242. // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
  23243. // to avoid it. If k is 1 there is a need to compare yd and rem again below.
  23244. if (k == 0) cmp = k = 1;
  23245. prod = yd.slice();
  23246. }
  23247. prodL = prod.length;
  23248. if (prodL < remL) prod.unshift(0);
  23249. // Subtract product from remainder.
  23250. subtract(rem, prod, remL, base);
  23251. // If product was < previous remainder.
  23252. if (cmp == -1) {
  23253. remL = rem.length;
  23254. // Compare divisor and new remainder.
  23255. cmp = compare(yd, rem, yL, remL);
  23256. // If divisor < new remainder, subtract divisor from remainder.
  23257. if (cmp < 1) {
  23258. k++;
  23259. // Subtract divisor from remainder.
  23260. subtract(rem, yL < remL ? yz : yd, remL, base);
  23261. }
  23262. }
  23263. remL = rem.length;
  23264. } else if (cmp === 0) {
  23265. k++;
  23266. rem = [0];
  23267. } // if cmp === 1, k will be 0
  23268. // Add the next digit, k, to the result array.
  23269. qd[i++] = k;
  23270. // Update the remainder.
  23271. if (cmp && rem[0]) {
  23272. rem[remL++] = xd[xi] || 0;
  23273. } else {
  23274. rem = [xd[xi]];
  23275. remL = 1;
  23276. }
  23277. } while ((xi++ < xL || rem[0] !== void 0) && sd--);
  23278. more = rem[0] !== void 0;
  23279. }
  23280. // Leading zero?
  23281. if (!qd[0]) qd.shift();
  23282. }
  23283. // logBase is 1 when divide is being used for base conversion.
  23284. if (logBase == 1) {
  23285. q.e = e;
  23286. inexact = more;
  23287. } else {
  23288. // To calculate q.e, first get the number of digits of qd[0].
  23289. for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
  23290. q.e = i + e * logBase - 1;
  23291. finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
  23292. }
  23293. return q;
  23294. };
  23295. })();
  23296. /*
  23297. * Round `x` to `sd` significant digits using rounding mode `rm`.
  23298. * Check for over/under-flow.
  23299. */
  23300. function finalise(x, sd, rm, isTruncated) {
  23301. var digits, i, j, k, rd, roundUp, w, xd, xdi,
  23302. Ctor = x.constructor;
  23303. // Don't round if sd is null or undefined.
  23304. out: if (sd != null) {
  23305. xd = x.d;
  23306. // Infinity/NaN.
  23307. if (!xd) return x;
  23308. // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
  23309. // w: the word of xd containing rd, a base 1e7 number.
  23310. // xdi: the index of w within xd.
  23311. // digits: the number of digits of w.
  23312. // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
  23313. // they had leading zeros)
  23314. // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
  23315. // Get the length of the first word of the digits array xd.
  23316. for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
  23317. i = sd - digits;
  23318. // Is the rounding digit in the first word of xd?
  23319. if (i < 0) {
  23320. i += LOG_BASE;
  23321. j = sd;
  23322. w = xd[xdi = 0];
  23323. // Get the rounding digit at index j of w.
  23324. rd = w / mathpow(10, digits - j - 1) % 10 | 0;
  23325. } else {
  23326. xdi = Math.ceil((i + 1) / LOG_BASE);
  23327. k = xd.length;
  23328. if (xdi >= k) {
  23329. if (isTruncated) {
  23330. // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
  23331. for (; k++ <= xdi;) xd.push(0);
  23332. w = rd = 0;
  23333. digits = 1;
  23334. i %= LOG_BASE;
  23335. j = i - LOG_BASE + 1;
  23336. } else {
  23337. break out;
  23338. }
  23339. } else {
  23340. w = k = xd[xdi];
  23341. // Get the number of digits of w.
  23342. for (digits = 1; k >= 10; k /= 10) digits++;
  23343. // Get the index of rd within w.
  23344. i %= LOG_BASE;
  23345. // Get the index of rd within w, adjusted for leading zeros.
  23346. // The number of leading zeros of w is given by LOG_BASE - digits.
  23347. j = i - LOG_BASE + digits;
  23348. // Get the rounding digit at index j of w.
  23349. rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
  23350. }
  23351. }
  23352. // Are there any non-zero digits after the rounding digit?
  23353. isTruncated = isTruncated || sd < 0 ||
  23354. xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
  23355. // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
  23356. // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
  23357. // will give 714.
  23358. roundUp = rm < 4
  23359. ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
  23360. : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
  23361. // Check whether the digit to the left of the rounding digit is odd.
  23362. ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
  23363. rm == (x.s < 0 ? 8 : 7));
  23364. if (sd < 1 || !xd[0]) {
  23365. xd.length = 0;
  23366. if (roundUp) {
  23367. // Convert sd to decimal places.
  23368. sd -= x.e + 1;
  23369. // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  23370. xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
  23371. x.e = -sd || 0;
  23372. } else {
  23373. // Zero.
  23374. xd[0] = x.e = 0;
  23375. }
  23376. return x;
  23377. }
  23378. // Remove excess digits.
  23379. if (i == 0) {
  23380. xd.length = xdi;
  23381. k = 1;
  23382. xdi--;
  23383. } else {
  23384. xd.length = xdi + 1;
  23385. k = mathpow(10, LOG_BASE - i);
  23386. // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  23387. // j > 0 means i > number of leading zeros of w.
  23388. xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
  23389. }
  23390. if (roundUp) {
  23391. for (;;) {
  23392. // Is the digit to be rounded up in the first word of xd?
  23393. if (xdi == 0) {
  23394. // i will be the length of xd[0] before k is added.
  23395. for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
  23396. j = xd[0] += k;
  23397. for (k = 1; j >= 10; j /= 10) k++;
  23398. // if i != k the length has increased.
  23399. if (i != k) {
  23400. x.e++;
  23401. if (xd[0] == BASE) xd[0] = 1;
  23402. }
  23403. break;
  23404. } else {
  23405. xd[xdi] += k;
  23406. if (xd[xdi] != BASE) break;
  23407. xd[xdi--] = 0;
  23408. k = 1;
  23409. }
  23410. }
  23411. }
  23412. // Remove trailing zeros.
  23413. for (i = xd.length; xd[--i] === 0;) xd.pop();
  23414. }
  23415. if (external) {
  23416. // Overflow?
  23417. if (x.e > Ctor.maxE) {
  23418. // Infinity.
  23419. x.d = null;
  23420. x.e = NaN;
  23421. // Underflow?
  23422. } else if (x.e < Ctor.minE) {
  23423. // Zero.
  23424. x.e = 0;
  23425. x.d = [0];
  23426. // Ctor.underflow = true;
  23427. } // else Ctor.underflow = false;
  23428. }
  23429. return x;
  23430. }
  23431. function finiteToString(x, isExp, sd) {
  23432. if (!x.isFinite()) return nonFiniteToString(x);
  23433. var k,
  23434. e = x.e,
  23435. str = digitsToString(x.d),
  23436. len = str.length;
  23437. if (isExp) {
  23438. if (sd && (k = sd - len) > 0) {
  23439. str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
  23440. } else if (len > 1) {
  23441. str = str.charAt(0) + '.' + str.slice(1);
  23442. }
  23443. str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
  23444. } else if (e < 0) {
  23445. str = '0.' + getZeroString(-e - 1) + str;
  23446. if (sd && (k = sd - len) > 0) str += getZeroString(k);
  23447. } else if (e >= len) {
  23448. str += getZeroString(e + 1 - len);
  23449. if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
  23450. } else {
  23451. if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
  23452. if (sd && (k = sd - len) > 0) {
  23453. if (e + 1 === len) str += '.';
  23454. str += getZeroString(k);
  23455. }
  23456. }
  23457. return str;
  23458. }
  23459. // Calculate the base 10 exponent from the base 1e7 exponent.
  23460. function getBase10Exponent(digits, e) {
  23461. var w = digits[0];
  23462. // Add the number of digits of the first word of the digits array.
  23463. for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
  23464. return e;
  23465. }
  23466. function getLn10(Ctor, sd, pr) {
  23467. if (sd > LN10_PRECISION) {
  23468. // Reset global state in case the exception is caught.
  23469. external = true;
  23470. if (pr) Ctor.precision = pr;
  23471. throw Error(precisionLimitExceeded);
  23472. }
  23473. return finalise(new Ctor(LN10), sd, 1, true);
  23474. }
  23475. function getPi(Ctor, sd, rm) {
  23476. if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
  23477. return finalise(new Ctor(PI), sd, rm, true);
  23478. }
  23479. function getPrecision(digits) {
  23480. var w = digits.length - 1,
  23481. len = w * LOG_BASE + 1;
  23482. w = digits[w];
  23483. // If non-zero...
  23484. if (w) {
  23485. // Subtract the number of trailing zeros of the last word.
  23486. for (; w % 10 == 0; w /= 10) len--;
  23487. // Add the number of digits of the first word.
  23488. for (w = digits[0]; w >= 10; w /= 10) len++;
  23489. }
  23490. return len;
  23491. }
  23492. function getZeroString(k) {
  23493. var zs = '';
  23494. for (; k--;) zs += '0';
  23495. return zs;
  23496. }
  23497. /*
  23498. * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
  23499. * integer of type number.
  23500. *
  23501. * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
  23502. *
  23503. */
  23504. function intPow(Ctor, x, n, pr) {
  23505. var isTruncated,
  23506. r = new Ctor(1),
  23507. // Max n of 9007199254740991 takes 53 loop iterations.
  23508. // Maximum digits array length; leaves [28, 34] guard digits.
  23509. k = Math.ceil(pr / LOG_BASE + 4);
  23510. external = false;
  23511. for (;;) {
  23512. if (n % 2) {
  23513. r = r.times(x);
  23514. if (truncate(r.d, k)) isTruncated = true;
  23515. }
  23516. n = mathfloor(n / 2);
  23517. if (n === 0) {
  23518. // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
  23519. n = r.d.length - 1;
  23520. if (isTruncated && r.d[n] === 0) ++r.d[n];
  23521. break;
  23522. }
  23523. x = x.times(x);
  23524. truncate(x.d, k);
  23525. }
  23526. external = true;
  23527. return r;
  23528. }
  23529. function isOdd(n) {
  23530. return n.d[n.d.length - 1] & 1;
  23531. }
  23532. /*
  23533. * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
  23534. */
  23535. function maxOrMin(Ctor, args, ltgt) {
  23536. var y,
  23537. x = new Ctor(args[0]),
  23538. i = 0;
  23539. for (; ++i < args.length;) {
  23540. y = new Ctor(args[i]);
  23541. if (!y.s) {
  23542. x = y;
  23543. break;
  23544. } else if (x[ltgt](y)) {
  23545. x = y;
  23546. }
  23547. }
  23548. return x;
  23549. }
  23550. /*
  23551. * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
  23552. * digits.
  23553. *
  23554. * Taylor/Maclaurin series.
  23555. *
  23556. * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
  23557. *
  23558. * Argument reduction:
  23559. * Repeat x = x / 32, k += 5, until |x| < 0.1
  23560. * exp(x) = exp(x / 2^k)^(2^k)
  23561. *
  23562. * Previously, the argument was initially reduced by
  23563. * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
  23564. * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
  23565. * found to be slower than just dividing repeatedly by 32 as above.
  23566. *
  23567. * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
  23568. * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
  23569. * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
  23570. *
  23571. * exp(Infinity) = Infinity
  23572. * exp(-Infinity) = 0
  23573. * exp(NaN) = NaN
  23574. * exp(±0) = 1
  23575. *
  23576. * exp(x) is non-terminating for any finite, non-zero x.
  23577. *
  23578. * The result will always be correctly rounded.
  23579. *
  23580. */
  23581. function naturalExponential(x, sd) {
  23582. var denominator, guard, j, pow, sum, t, wpr,
  23583. rep = 0,
  23584. i = 0,
  23585. k = 0,
  23586. Ctor = x.constructor,
  23587. rm = Ctor.rounding,
  23588. pr = Ctor.precision;
  23589. // 0/NaN/Infinity?
  23590. if (!x.d || !x.d[0] || x.e > 17) {
  23591. return new Ctor(x.d
  23592. ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
  23593. : x.s ? x.s < 0 ? 0 : x : 0 / 0);
  23594. }
  23595. if (sd == null) {
  23596. external = false;
  23597. wpr = pr;
  23598. } else {
  23599. wpr = sd;
  23600. }
  23601. t = new Ctor(0.03125);
  23602. // while abs(x) >= 0.1
  23603. while (x.e > -2) {
  23604. // x = x / 2^5
  23605. x = x.times(t);
  23606. k += 5;
  23607. }
  23608. // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
  23609. // necessary to ensure the first 4 rounding digits are correct.
  23610. guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
  23611. wpr += guard;
  23612. denominator = pow = sum = new Ctor(1);
  23613. Ctor.precision = wpr;
  23614. for (;;) {
  23615. pow = finalise(pow.times(x), wpr, 1);
  23616. denominator = denominator.times(++i);
  23617. t = sum.plus(divide(pow, denominator, wpr, 1));
  23618. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  23619. j = k;
  23620. while (j--) sum = finalise(sum.times(sum), wpr, 1);
  23621. // Check to see if the first 4 rounding digits are [49]999.
  23622. // If so, repeat the summation with a higher precision, otherwise
  23623. // e.g. with precision: 18, rounding: 1
  23624. // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
  23625. // `wpr - guard` is the index of first rounding digit.
  23626. if (sd == null) {
  23627. if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  23628. Ctor.precision = wpr += 10;
  23629. denominator = pow = t = new Ctor(1);
  23630. i = 0;
  23631. rep++;
  23632. } else {
  23633. return finalise(sum, Ctor.precision = pr, rm, external = true);
  23634. }
  23635. } else {
  23636. Ctor.precision = pr;
  23637. return sum;
  23638. }
  23639. }
  23640. sum = t;
  23641. }
  23642. }
  23643. /*
  23644. * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
  23645. * digits.
  23646. *
  23647. * ln(-n) = NaN
  23648. * ln(0) = -Infinity
  23649. * ln(-0) = -Infinity
  23650. * ln(1) = 0
  23651. * ln(Infinity) = Infinity
  23652. * ln(-Infinity) = NaN
  23653. * ln(NaN) = NaN
  23654. *
  23655. * ln(n) (n != 1) is non-terminating.
  23656. *
  23657. */
  23658. function naturalLogarithm(y, sd) {
  23659. var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
  23660. n = 1,
  23661. guard = 10,
  23662. x = y,
  23663. xd = x.d,
  23664. Ctor = x.constructor,
  23665. rm = Ctor.rounding,
  23666. pr = Ctor.precision;
  23667. // Is x negative or Infinity, NaN, 0 or 1?
  23668. if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
  23669. return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
  23670. }
  23671. if (sd == null) {
  23672. external = false;
  23673. wpr = pr;
  23674. } else {
  23675. wpr = sd;
  23676. }
  23677. Ctor.precision = wpr += guard;
  23678. c = digitsToString(xd);
  23679. c0 = c.charAt(0);
  23680. if (Math.abs(e = x.e) < 1.5e15) {
  23681. // Argument reduction.
  23682. // The series converges faster the closer the argument is to 1, so using
  23683. // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
  23684. // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
  23685. // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
  23686. // later be divided by this number, then separate out the power of 10 using
  23687. // ln(a*10^b) = ln(a) + b*ln(10).
  23688. // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
  23689. //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
  23690. // max n is 6 (gives 0.7 - 1.3)
  23691. while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
  23692. x = x.times(y);
  23693. c = digitsToString(x.d);
  23694. c0 = c.charAt(0);
  23695. n++;
  23696. }
  23697. e = x.e;
  23698. if (c0 > 1) {
  23699. x = new Ctor('0.' + c);
  23700. e++;
  23701. } else {
  23702. x = new Ctor(c0 + '.' + c.slice(1));
  23703. }
  23704. } else {
  23705. // The argument reduction method above may result in overflow if the argument y is a massive
  23706. // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
  23707. // function using ln(x*10^e) = ln(x) + e*ln(10).
  23708. t = getLn10(Ctor, wpr + 2, pr).times(e + '');
  23709. x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
  23710. Ctor.precision = pr;
  23711. return sd == null ? finalise(x, pr, rm, external = true) : x;
  23712. }
  23713. // x1 is x reduced to a value near 1.
  23714. x1 = x;
  23715. // Taylor series.
  23716. // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
  23717. // where x = (y - 1)/(y + 1) (|x| < 1)
  23718. sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
  23719. x2 = finalise(x.times(x), wpr, 1);
  23720. denominator = 3;
  23721. for (;;) {
  23722. numerator = finalise(numerator.times(x2), wpr, 1);
  23723. t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
  23724. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  23725. sum = sum.times(2);
  23726. // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
  23727. // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
  23728. if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
  23729. sum = divide(sum, new Ctor(n), wpr, 1);
  23730. // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
  23731. // been repeated previously) and the first 4 rounding digits 9999?
  23732. // If so, restart the summation with a higher precision, otherwise
  23733. // e.g. with precision: 12, rounding: 1
  23734. // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
  23735. // `wpr - guard` is the index of first rounding digit.
  23736. if (sd == null) {
  23737. if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  23738. Ctor.precision = wpr += guard;
  23739. t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
  23740. x2 = finalise(x.times(x), wpr, 1);
  23741. denominator = rep = 1;
  23742. } else {
  23743. return finalise(sum, Ctor.precision = pr, rm, external = true);
  23744. }
  23745. } else {
  23746. Ctor.precision = pr;
  23747. return sum;
  23748. }
  23749. }
  23750. sum = t;
  23751. denominator += 2;
  23752. }
  23753. }
  23754. // ±Infinity, NaN.
  23755. function nonFiniteToString(x) {
  23756. // Unsigned.
  23757. return String(x.s * x.s / 0);
  23758. }
  23759. /*
  23760. * Parse the value of a new Decimal `x` from string `str`.
  23761. */
  23762. function parseDecimal(x, str) {
  23763. var e, i, len;
  23764. // Decimal point?
  23765. if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
  23766. // Exponential form?
  23767. if ((i = str.search(/e/i)) > 0) {
  23768. // Determine exponent.
  23769. if (e < 0) e = i;
  23770. e += +str.slice(i + 1);
  23771. str = str.substring(0, i);
  23772. } else if (e < 0) {
  23773. // Integer.
  23774. e = str.length;
  23775. }
  23776. // Determine leading zeros.
  23777. for (i = 0; str.charCodeAt(i) === 48; i++);
  23778. // Determine trailing zeros.
  23779. for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
  23780. str = str.slice(i, len);
  23781. if (str) {
  23782. len -= i;
  23783. x.e = e = e - i - 1;
  23784. x.d = [];
  23785. // Transform base
  23786. // e is the base 10 exponent.
  23787. // i is where to slice str to get the first word of the digits array.
  23788. i = (e + 1) % LOG_BASE;
  23789. if (e < 0) i += LOG_BASE;
  23790. if (i < len) {
  23791. if (i) x.d.push(+str.slice(0, i));
  23792. for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
  23793. str = str.slice(i);
  23794. i = LOG_BASE - str.length;
  23795. } else {
  23796. i -= len;
  23797. }
  23798. for (; i--;) str += '0';
  23799. x.d.push(+str);
  23800. if (external) {
  23801. // Overflow?
  23802. if (x.e > x.constructor.maxE) {
  23803. // Infinity.
  23804. x.d = null;
  23805. x.e = NaN;
  23806. // Underflow?
  23807. } else if (x.e < x.constructor.minE) {
  23808. // Zero.
  23809. x.e = 0;
  23810. x.d = [0];
  23811. // x.constructor.underflow = true;
  23812. } // else x.constructor.underflow = false;
  23813. }
  23814. } else {
  23815. // Zero.
  23816. x.e = 0;
  23817. x.d = [0];
  23818. }
  23819. return x;
  23820. }
  23821. /*
  23822. * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
  23823. */
  23824. function parseOther(x, str) {
  23825. var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
  23826. if (str === 'Infinity' || str === 'NaN') {
  23827. if (!+str) x.s = NaN;
  23828. x.e = NaN;
  23829. x.d = null;
  23830. return x;
  23831. }
  23832. if (isHex.test(str)) {
  23833. base = 16;
  23834. str = str.toLowerCase();
  23835. } else if (isBinary.test(str)) {
  23836. base = 2;
  23837. } else if (isOctal.test(str)) {
  23838. base = 8;
  23839. } else {
  23840. throw Error(invalidArgument + str);
  23841. }
  23842. // Is there a binary exponent part?
  23843. i = str.search(/p/i);
  23844. if (i > 0) {
  23845. p = +str.slice(i + 1);
  23846. str = str.substring(2, i);
  23847. } else {
  23848. str = str.slice(2);
  23849. }
  23850. // Convert `str` as an integer then divide the result by `base` raised to a power such that the
  23851. // fraction part will be restored.
  23852. i = str.indexOf('.');
  23853. isFloat = i >= 0;
  23854. Ctor = x.constructor;
  23855. if (isFloat) {
  23856. str = str.replace('.', '');
  23857. len = str.length;
  23858. i = len - i;
  23859. // log[10](16) = 1.2041... , log[10](88) = 1.9444....
  23860. divisor = intPow(Ctor, new Ctor(base), i, i * 2);
  23861. }
  23862. xd = convertBase(str, base, BASE);
  23863. xe = xd.length - 1;
  23864. // Remove trailing zeros.
  23865. for (i = xe; xd[i] === 0; --i) xd.pop();
  23866. if (i < 0) return new Ctor(x.s * 0);
  23867. x.e = getBase10Exponent(xd, xe);
  23868. x.d = xd;
  23869. external = false;
  23870. // At what precision to perform the division to ensure exact conversion?
  23871. // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
  23872. // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
  23873. // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
  23874. // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
  23875. // Therefore using 4 * the number of digits of str will always be enough.
  23876. if (isFloat) x = divide(x, divisor, len * 4);
  23877. // Multiply by the binary exponent part if present.
  23878. if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));
  23879. external = true;
  23880. return x;
  23881. }
  23882. /*
  23883. * sin(x) = x - x^3/3! + x^5/5! - ...
  23884. * |x| < pi/2
  23885. *
  23886. */
  23887. function sine(Ctor, x) {
  23888. var k,
  23889. len = x.d.length;
  23890. if (len < 3) return taylorSeries(Ctor, 2, x, x);
  23891. // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
  23892. // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
  23893. // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
  23894. // Estimate the optimum number of times to use the argument reduction.
  23895. k = 1.4 * Math.sqrt(len);
  23896. k = k > 16 ? 16 : k | 0;
  23897. x = x.times(1 / tinyPow(5, k));
  23898. x = taylorSeries(Ctor, 2, x, x);
  23899. // Reverse argument reduction
  23900. var sin2_x,
  23901. d5 = new Ctor(5),
  23902. d16 = new Ctor(16),
  23903. d20 = new Ctor(20);
  23904. for (; k--;) {
  23905. sin2_x = x.times(x);
  23906. x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
  23907. }
  23908. return x;
  23909. }
  23910. // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
  23911. function taylorSeries(Ctor, n, x, y, isHyperbolic) {
  23912. var j, t, u, x2,
  23913. i = 1,
  23914. pr = Ctor.precision,
  23915. k = Math.ceil(pr / LOG_BASE);
  23916. external = false;
  23917. x2 = x.times(x);
  23918. u = new Ctor(y);
  23919. for (;;) {
  23920. t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
  23921. u = isHyperbolic ? y.plus(t) : y.minus(t);
  23922. y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
  23923. t = u.plus(y);
  23924. if (t.d[k] !== void 0) {
  23925. for (j = k; t.d[j] === u.d[j] && j--;);
  23926. if (j == -1) break;
  23927. }
  23928. j = u;
  23929. u = y;
  23930. y = t;
  23931. t = j;
  23932. i++;
  23933. }
  23934. external = true;
  23935. t.d.length = k + 1;
  23936. return t;
  23937. }
  23938. // Exponent e must be positive and non-zero.
  23939. function tinyPow(b, e) {
  23940. var n = b;
  23941. while (--e) n *= b;
  23942. return n;
  23943. }
  23944. // Return the absolute value of `x` reduced to less than or equal to half pi.
  23945. function toLessThanHalfPi(Ctor, x) {
  23946. var t,
  23947. isNeg = x.s < 0,
  23948. pi = getPi(Ctor, Ctor.precision, 1),
  23949. halfPi = pi.times(0.5);
  23950. x = x.abs();
  23951. if (x.lte(halfPi)) {
  23952. quadrant = isNeg ? 4 : 1;
  23953. return x;
  23954. }
  23955. t = x.divToInt(pi);
  23956. if (t.isZero()) {
  23957. quadrant = isNeg ? 3 : 2;
  23958. } else {
  23959. x = x.minus(t.times(pi));
  23960. // 0 <= x < pi
  23961. if (x.lte(halfPi)) {
  23962. quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
  23963. return x;
  23964. }
  23965. quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
  23966. }
  23967. return x.minus(pi).abs();
  23968. }
  23969. /*
  23970. * Return the value of Decimal `x` as a string in base `baseOut`.
  23971. *
  23972. * If the optional `sd` argument is present include a binary exponent suffix.
  23973. */
  23974. function toStringBinary(x, baseOut, sd, rm) {
  23975. var base, e, i, k, len, roundUp, str, xd, y,
  23976. Ctor = x.constructor,
  23977. isExp = sd !== void 0;
  23978. if (isExp) {
  23979. checkInt32(sd, 1, MAX_DIGITS);
  23980. if (rm === void 0) rm = Ctor.rounding;
  23981. else checkInt32(rm, 0, 8);
  23982. } else {
  23983. sd = Ctor.precision;
  23984. rm = Ctor.rounding;
  23985. }
  23986. if (!x.isFinite()) {
  23987. str = nonFiniteToString(x);
  23988. } else {
  23989. str = finiteToString(x);
  23990. i = str.indexOf('.');
  23991. // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
  23992. // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
  23993. // minBinaryExponent = floor(decimalExponent * log[2](10))
  23994. // log[2](10) = 3.321928094887362347870319429489390175864
  23995. if (isExp) {
  23996. base = 2;
  23997. if (baseOut == 16) {
  23998. sd = sd * 4 - 3;
  23999. } else if (baseOut == 8) {
  24000. sd = sd * 3 - 2;
  24001. }
  24002. } else {
  24003. base = baseOut;
  24004. }
  24005. // Convert the number as an integer then divide the result by its base raised to a power such
  24006. // that the fraction part will be restored.
  24007. // Non-integer.
  24008. if (i >= 0) {
  24009. str = str.replace('.', '');
  24010. y = new Ctor(1);
  24011. y.e = str.length - i;
  24012. y.d = convertBase(finiteToString(y), 10, base);
  24013. y.e = y.d.length;
  24014. }
  24015. xd = convertBase(str, 10, base);
  24016. e = len = xd.length;
  24017. // Remove trailing zeros.
  24018. for (; xd[--len] == 0;) xd.pop();
  24019. if (!xd[0]) {
  24020. str = isExp ? '0p+0' : '0';
  24021. } else {
  24022. if (i < 0) {
  24023. e--;
  24024. } else {
  24025. x = new Ctor(x);
  24026. x.d = xd;
  24027. x.e = e;
  24028. x = divide(x, y, sd, rm, 0, base);
  24029. xd = x.d;
  24030. e = x.e;
  24031. roundUp = inexact;
  24032. }
  24033. // The rounding digit, i.e. the digit after the digit that may be rounded up.
  24034. i = xd[sd];
  24035. k = base / 2;
  24036. roundUp = roundUp || xd[sd + 1] !== void 0;
  24037. roundUp = rm < 4
  24038. ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
  24039. : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
  24040. rm === (x.s < 0 ? 8 : 7));
  24041. xd.length = sd;
  24042. if (roundUp) {
  24043. // Rounding up may mean the previous digit has to be rounded up and so on.
  24044. for (; ++xd[--sd] > base - 1;) {
  24045. xd[sd] = 0;
  24046. if (!sd) {
  24047. ++e;
  24048. xd.unshift(1);
  24049. }
  24050. }
  24051. }
  24052. // Determine trailing zeros.
  24053. for (len = xd.length; !xd[len - 1]; --len);
  24054. // E.g. [4, 11, 15] becomes 4bf.
  24055. for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
  24056. // Add binary exponent suffix?
  24057. if (isExp) {
  24058. if (len > 1) {
  24059. if (baseOut == 16 || baseOut == 8) {
  24060. i = baseOut == 16 ? 4 : 3;
  24061. for (--len; len % i; len++) str += '0';
  24062. xd = convertBase(str, base, baseOut);
  24063. for (len = xd.length; !xd[len - 1]; --len);
  24064. // xd[0] will always be be 1
  24065. for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
  24066. } else {
  24067. str = str.charAt(0) + '.' + str.slice(1);
  24068. }
  24069. }
  24070. str = str + (e < 0 ? 'p' : 'p+') + e;
  24071. } else if (e < 0) {
  24072. for (; ++e;) str = '0' + str;
  24073. str = '0.' + str;
  24074. } else {
  24075. if (++e > len) for (e -= len; e-- ;) str += '0';
  24076. else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
  24077. }
  24078. }
  24079. str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
  24080. }
  24081. return x.s < 0 ? '-' + str : str;
  24082. }
  24083. // Does not strip trailing zeros.
  24084. function truncate(arr, len) {
  24085. if (arr.length > len) {
  24086. arr.length = len;
  24087. return true;
  24088. }
  24089. }
  24090. // Decimal methods
  24091. /*
  24092. * abs
  24093. * acos
  24094. * acosh
  24095. * add
  24096. * asin
  24097. * asinh
  24098. * atan
  24099. * atanh
  24100. * atan2
  24101. * cbrt
  24102. * ceil
  24103. * clone
  24104. * config
  24105. * cos
  24106. * cosh
  24107. * div
  24108. * exp
  24109. * floor
  24110. * hypot
  24111. * ln
  24112. * log
  24113. * log2
  24114. * log10
  24115. * max
  24116. * min
  24117. * mod
  24118. * mul
  24119. * pow
  24120. * random
  24121. * round
  24122. * set
  24123. * sign
  24124. * sin
  24125. * sinh
  24126. * sqrt
  24127. * sub
  24128. * tan
  24129. * tanh
  24130. * trunc
  24131. */
  24132. /*
  24133. * Return a new Decimal whose value is the absolute value of `x`.
  24134. *
  24135. * x {number|string|Decimal}
  24136. *
  24137. */
  24138. function abs(x) {
  24139. return new this(x).abs();
  24140. }
  24141. /*
  24142. * Return a new Decimal whose value is the arccosine in radians of `x`.
  24143. *
  24144. * x {number|string|Decimal}
  24145. *
  24146. */
  24147. function acos(x) {
  24148. return new this(x).acos();
  24149. }
  24150. /*
  24151. * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
  24152. * `precision` significant digits using rounding mode `rounding`.
  24153. *
  24154. * x {number|string|Decimal} A value in radians.
  24155. *
  24156. */
  24157. function acosh(x) {
  24158. return new this(x).acosh();
  24159. }
  24160. /*
  24161. * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
  24162. * digits using rounding mode `rounding`.
  24163. *
  24164. * x {number|string|Decimal}
  24165. * y {number|string|Decimal}
  24166. *
  24167. */
  24168. function add(x, y) {
  24169. return new this(x).plus(y);
  24170. }
  24171. /*
  24172. * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
  24173. * significant digits using rounding mode `rounding`.
  24174. *
  24175. * x {number|string|Decimal}
  24176. *
  24177. */
  24178. function asin(x) {
  24179. return new this(x).asin();
  24180. }
  24181. /*
  24182. * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
  24183. * `precision` significant digits using rounding mode `rounding`.
  24184. *
  24185. * x {number|string|Decimal} A value in radians.
  24186. *
  24187. */
  24188. function asinh(x) {
  24189. return new this(x).asinh();
  24190. }
  24191. /*
  24192. * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
  24193. * significant digits using rounding mode `rounding`.
  24194. *
  24195. * x {number|string|Decimal}
  24196. *
  24197. */
  24198. function atan(x) {
  24199. return new this(x).atan();
  24200. }
  24201. /*
  24202. * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
  24203. * `precision` significant digits using rounding mode `rounding`.
  24204. *
  24205. * x {number|string|Decimal} A value in radians.
  24206. *
  24207. */
  24208. function atanh(x) {
  24209. return new this(x).atanh();
  24210. }
  24211. /*
  24212. * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
  24213. * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
  24214. *
  24215. * Domain: [-Infinity, Infinity]
  24216. * Range: [-pi, pi]
  24217. *
  24218. * y {number|string|Decimal} The y-coordinate.
  24219. * x {number|string|Decimal} The x-coordinate.
  24220. *
  24221. * atan2(±0, -0) = ±pi
  24222. * atan2(±0, +0) = ±0
  24223. * atan2(±0, -x) = ±pi for x > 0
  24224. * atan2(±0, x) = ±0 for x > 0
  24225. * atan2(-y, ±0) = -pi/2 for y > 0
  24226. * atan2(y, ±0) = pi/2 for y > 0
  24227. * atan2(±y, -Infinity) = ±pi for finite y > 0
  24228. * atan2(±y, +Infinity) = ±0 for finite y > 0
  24229. * atan2(±Infinity, x) = ±pi/2 for finite x
  24230. * atan2(±Infinity, -Infinity) = ±3*pi/4
  24231. * atan2(±Infinity, +Infinity) = ±pi/4
  24232. * atan2(NaN, x) = NaN
  24233. * atan2(y, NaN) = NaN
  24234. *
  24235. */
  24236. function atan2(y, x) {
  24237. y = new this(y);
  24238. x = new this(x);
  24239. var r,
  24240. pr = this.precision,
  24241. rm = this.rounding,
  24242. wpr = pr + 4;
  24243. // Either NaN
  24244. if (!y.s || !x.s) {
  24245. r = new this(NaN);
  24246. // Both ±Infinity
  24247. } else if (!y.d && !x.d) {
  24248. r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
  24249. r.s = y.s;
  24250. // x is ±Infinity or y is ±0
  24251. } else if (!x.d || y.isZero()) {
  24252. r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
  24253. r.s = y.s;
  24254. // y is ±Infinity or x is ±0
  24255. } else if (!y.d || x.isZero()) {
  24256. r = getPi(this, wpr, 1).times(0.5);
  24257. r.s = y.s;
  24258. // Both non-zero and finite
  24259. } else if (x.s < 0) {
  24260. this.precision = wpr;
  24261. this.rounding = 1;
  24262. r = this.atan(divide(y, x, wpr, 1));
  24263. x = getPi(this, wpr, 1);
  24264. this.precision = pr;
  24265. this.rounding = rm;
  24266. r = y.s < 0 ? r.minus(x) : r.plus(x);
  24267. } else {
  24268. r = this.atan(divide(y, x, wpr, 1));
  24269. }
  24270. return r;
  24271. }
  24272. /*
  24273. * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
  24274. * digits using rounding mode `rounding`.
  24275. *
  24276. * x {number|string|Decimal}
  24277. *
  24278. */
  24279. function cbrt(x) {
  24280. return new this(x).cbrt();
  24281. }
  24282. /*
  24283. * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
  24284. *
  24285. * x {number|string|Decimal}
  24286. *
  24287. */
  24288. function ceil(x) {
  24289. return finalise(x = new this(x), x.e + 1, 2);
  24290. }
  24291. /*
  24292. * Configure global settings for a Decimal constructor.
  24293. *
  24294. * `obj` is an object with one or more of the following properties,
  24295. *
  24296. * precision {number}
  24297. * rounding {number}
  24298. * toExpNeg {number}
  24299. * toExpPos {number}
  24300. * maxE {number}
  24301. * minE {number}
  24302. * modulo {number}
  24303. * crypto {boolean|number}
  24304. * defaults {true}
  24305. *
  24306. * E.g. Decimal.config({ precision: 20, rounding: 4 })
  24307. *
  24308. */
  24309. function config(obj) {
  24310. if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
  24311. var i, p, v,
  24312. useDefaults = obj.defaults === true,
  24313. ps = [
  24314. 'precision', 1, MAX_DIGITS,
  24315. 'rounding', 0, 8,
  24316. 'toExpNeg', -EXP_LIMIT, 0,
  24317. 'toExpPos', 0, EXP_LIMIT,
  24318. 'maxE', 0, EXP_LIMIT,
  24319. 'minE', -EXP_LIMIT, 0,
  24320. 'modulo', 0, 9
  24321. ];
  24322. for (i = 0; i < ps.length; i += 3) {
  24323. if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
  24324. if ((v = obj[p]) !== void 0) {
  24325. if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
  24326. else throw Error(invalidArgument + p + ': ' + v);
  24327. }
  24328. }
  24329. if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
  24330. if ((v = obj[p]) !== void 0) {
  24331. if (v === true || v === false || v === 0 || v === 1) {
  24332. if (v) {
  24333. if (typeof crypto != 'undefined' && crypto &&
  24334. (crypto.getRandomValues || crypto.randomBytes)) {
  24335. this[p] = true;
  24336. } else {
  24337. throw Error(cryptoUnavailable);
  24338. }
  24339. } else {
  24340. this[p] = false;
  24341. }
  24342. } else {
  24343. throw Error(invalidArgument + p + ': ' + v);
  24344. }
  24345. }
  24346. return this;
  24347. }
  24348. /*
  24349. * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
  24350. * digits using rounding mode `rounding`.
  24351. *
  24352. * x {number|string|Decimal} A value in radians.
  24353. *
  24354. */
  24355. function cos(x) {
  24356. return new this(x).cos();
  24357. }
  24358. /*
  24359. * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
  24360. * significant digits using rounding mode `rounding`.
  24361. *
  24362. * x {number|string|Decimal} A value in radians.
  24363. *
  24364. */
  24365. function cosh(x) {
  24366. return new this(x).cosh();
  24367. }
  24368. /*
  24369. * Create and return a Decimal constructor with the same configuration properties as this Decimal
  24370. * constructor.
  24371. *
  24372. */
  24373. function clone(obj) {
  24374. var i, p, ps;
  24375. /*
  24376. * The Decimal constructor and exported function.
  24377. * Return a new Decimal instance.
  24378. *
  24379. * v {number|string|Decimal} A numeric value.
  24380. *
  24381. */
  24382. function Decimal(v) {
  24383. var e, i, t,
  24384. x = this;
  24385. // Decimal called without new.
  24386. if (!(x instanceof Decimal)) return new Decimal(v);
  24387. // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
  24388. // which points to Object.
  24389. x.constructor = Decimal;
  24390. // Duplicate.
  24391. if (v instanceof Decimal) {
  24392. x.s = v.s;
  24393. if (external) {
  24394. if (!v.d || v.e > Decimal.maxE) {
  24395. // Infinity.
  24396. x.e = NaN;
  24397. x.d = null;
  24398. } else if (v.e < Decimal.minE) {
  24399. // Zero.
  24400. x.e = 0;
  24401. x.d = [0];
  24402. } else {
  24403. x.e = v.e;
  24404. x.d = v.d.slice();
  24405. }
  24406. } else {
  24407. x.e = v.e;
  24408. x.d = v.d ? v.d.slice() : v.d;
  24409. }
  24410. return;
  24411. }
  24412. t = typeof v;
  24413. if (t === 'number') {
  24414. if (v === 0) {
  24415. x.s = 1 / v < 0 ? -1 : 1;
  24416. x.e = 0;
  24417. x.d = [0];
  24418. return;
  24419. }
  24420. if (v < 0) {
  24421. v = -v;
  24422. x.s = -1;
  24423. } else {
  24424. x.s = 1;
  24425. }
  24426. // Fast path for small integers.
  24427. if (v === ~~v && v < 1e7) {
  24428. for (e = 0, i = v; i >= 10; i /= 10) e++;
  24429. if (external) {
  24430. if (e > Decimal.maxE) {
  24431. x.e = NaN;
  24432. x.d = null;
  24433. } else if (e < Decimal.minE) {
  24434. x.e = 0;
  24435. x.d = [0];
  24436. } else {
  24437. x.e = e;
  24438. x.d = [v];
  24439. }
  24440. } else {
  24441. x.e = e;
  24442. x.d = [v];
  24443. }
  24444. return;
  24445. // Infinity, NaN.
  24446. } else if (v * 0 !== 0) {
  24447. if (!v) x.s = NaN;
  24448. x.e = NaN;
  24449. x.d = null;
  24450. return;
  24451. }
  24452. return parseDecimal(x, v.toString());
  24453. } else if (t !== 'string') {
  24454. throw Error(invalidArgument + v);
  24455. }
  24456. // Minus sign?
  24457. if ((i = v.charCodeAt(0)) === 45) {
  24458. v = v.slice(1);
  24459. x.s = -1;
  24460. } else {
  24461. // Plus sign?
  24462. if (i === 43) v = v.slice(1);
  24463. x.s = 1;
  24464. }
  24465. return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
  24466. }
  24467. Decimal.prototype = P;
  24468. Decimal.ROUND_UP = 0;
  24469. Decimal.ROUND_DOWN = 1;
  24470. Decimal.ROUND_CEIL = 2;
  24471. Decimal.ROUND_FLOOR = 3;
  24472. Decimal.ROUND_HALF_UP = 4;
  24473. Decimal.ROUND_HALF_DOWN = 5;
  24474. Decimal.ROUND_HALF_EVEN = 6;
  24475. Decimal.ROUND_HALF_CEIL = 7;
  24476. Decimal.ROUND_HALF_FLOOR = 8;
  24477. Decimal.EUCLID = 9;
  24478. Decimal.config = Decimal.set = config;
  24479. Decimal.clone = clone;
  24480. Decimal.isDecimal = isDecimalInstance;
  24481. Decimal.abs = abs;
  24482. Decimal.acos = acos;
  24483. Decimal.acosh = acosh; // ES6
  24484. Decimal.add = add;
  24485. Decimal.asin = asin;
  24486. Decimal.asinh = asinh; // ES6
  24487. Decimal.atan = atan;
  24488. Decimal.atanh = atanh; // ES6
  24489. Decimal.atan2 = atan2;
  24490. Decimal.cbrt = cbrt; // ES6
  24491. Decimal.ceil = ceil;
  24492. Decimal.cos = cos;
  24493. Decimal.cosh = cosh; // ES6
  24494. Decimal.div = div;
  24495. Decimal.exp = exp;
  24496. Decimal.floor = floor;
  24497. Decimal.hypot = hypot; // ES6
  24498. Decimal.ln = ln;
  24499. Decimal.log = log;
  24500. Decimal.log10 = log10; // ES6
  24501. Decimal.log2 = log2; // ES6
  24502. Decimal.max = max;
  24503. Decimal.min = min;
  24504. Decimal.mod = mod;
  24505. Decimal.mul = mul;
  24506. Decimal.pow = pow;
  24507. Decimal.random = random;
  24508. Decimal.round = round;
  24509. Decimal.sign = sign; // ES6
  24510. Decimal.sin = sin;
  24511. Decimal.sinh = sinh; // ES6
  24512. Decimal.sqrt = sqrt;
  24513. Decimal.sub = sub;
  24514. Decimal.tan = tan;
  24515. Decimal.tanh = tanh; // ES6
  24516. Decimal.trunc = trunc; // ES6
  24517. if (obj === void 0) obj = {};
  24518. if (obj) {
  24519. if (obj.defaults !== true) {
  24520. ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
  24521. for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
  24522. }
  24523. }
  24524. Decimal.config(obj);
  24525. return Decimal;
  24526. }
  24527. /*
  24528. * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
  24529. * digits using rounding mode `rounding`.
  24530. *
  24531. * x {number|string|Decimal}
  24532. * y {number|string|Decimal}
  24533. *
  24534. */
  24535. function div(x, y) {
  24536. return new this(x).div(y);
  24537. }
  24538. /*
  24539. * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
  24540. * significant digits using rounding mode `rounding`.
  24541. *
  24542. * x {number|string|Decimal} The power to which to raise the base of the natural log.
  24543. *
  24544. */
  24545. function exp(x) {
  24546. return new this(x).exp();
  24547. }
  24548. /*
  24549. * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
  24550. *
  24551. * x {number|string|Decimal}
  24552. *
  24553. */
  24554. function floor(x) {
  24555. return finalise(x = new this(x), x.e + 1, 3);
  24556. }
  24557. /*
  24558. * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
  24559. * rounded to `precision` significant digits using rounding mode `rounding`.
  24560. *
  24561. * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
  24562. *
  24563. * arguments {number|string|Decimal}
  24564. *
  24565. */
  24566. function hypot() {
  24567. var i, n,
  24568. t = new this(0);
  24569. external = false;
  24570. for (i = 0; i < arguments.length;) {
  24571. n = new this(arguments[i++]);
  24572. if (!n.d) {
  24573. if (n.s) {
  24574. external = true;
  24575. return new this(1 / 0);
  24576. }
  24577. t = n;
  24578. } else if (t.d) {
  24579. t = t.plus(n.times(n));
  24580. }
  24581. }
  24582. external = true;
  24583. return t.sqrt();
  24584. }
  24585. /*
  24586. * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
  24587. * otherwise return false.
  24588. *
  24589. */
  24590. function isDecimalInstance(obj) {
  24591. return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false;
  24592. }
  24593. /*
  24594. * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
  24595. * significant digits using rounding mode `rounding`.
  24596. *
  24597. * x {number|string|Decimal}
  24598. *
  24599. */
  24600. function ln(x) {
  24601. return new this(x).ln();
  24602. }
  24603. /*
  24604. * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
  24605. * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
  24606. *
  24607. * log[y](x)
  24608. *
  24609. * x {number|string|Decimal} The argument of the logarithm.
  24610. * y {number|string|Decimal} The base of the logarithm.
  24611. *
  24612. */
  24613. function log(x, y) {
  24614. return new this(x).log(y);
  24615. }
  24616. /*
  24617. * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
  24618. * significant digits using rounding mode `rounding`.
  24619. *
  24620. * x {number|string|Decimal}
  24621. *
  24622. */
  24623. function log2(x) {
  24624. return new this(x).log(2);
  24625. }
  24626. /*
  24627. * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
  24628. * significant digits using rounding mode `rounding`.
  24629. *
  24630. * x {number|string|Decimal}
  24631. *
  24632. */
  24633. function log10(x) {
  24634. return new this(x).log(10);
  24635. }
  24636. /*
  24637. * Return a new Decimal whose value is the maximum of the arguments.
  24638. *
  24639. * arguments {number|string|Decimal}
  24640. *
  24641. */
  24642. function max() {
  24643. return maxOrMin(this, arguments, 'lt');
  24644. }
  24645. /*
  24646. * Return a new Decimal whose value is the minimum of the arguments.
  24647. *
  24648. * arguments {number|string|Decimal}
  24649. *
  24650. */
  24651. function min() {
  24652. return maxOrMin(this, arguments, 'gt');
  24653. }
  24654. /*
  24655. * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
  24656. * using rounding mode `rounding`.
  24657. *
  24658. * x {number|string|Decimal}
  24659. * y {number|string|Decimal}
  24660. *
  24661. */
  24662. function mod(x, y) {
  24663. return new this(x).mod(y);
  24664. }
  24665. /*
  24666. * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
  24667. * digits using rounding mode `rounding`.
  24668. *
  24669. * x {number|string|Decimal}
  24670. * y {number|string|Decimal}
  24671. *
  24672. */
  24673. function mul(x, y) {
  24674. return new this(x).mul(y);
  24675. }
  24676. /*
  24677. * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
  24678. * significant digits using rounding mode `rounding`.
  24679. *
  24680. * x {number|string|Decimal} The base.
  24681. * y {number|string|Decimal} The exponent.
  24682. *
  24683. */
  24684. function pow(x, y) {
  24685. return new this(x).pow(y);
  24686. }
  24687. /*
  24688. * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
  24689. * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
  24690. * are produced).
  24691. *
  24692. * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
  24693. *
  24694. */
  24695. function random(sd) {
  24696. var d, e, k, n,
  24697. i = 0,
  24698. r = new this(1),
  24699. rd = [];
  24700. if (sd === void 0) sd = this.precision;
  24701. else checkInt32(sd, 1, MAX_DIGITS);
  24702. k = Math.ceil(sd / LOG_BASE);
  24703. if (!this.crypto) {
  24704. for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
  24705. // Browsers supporting crypto.getRandomValues.
  24706. } else if (crypto.getRandomValues) {
  24707. d = crypto.getRandomValues(new Uint32Array(k));
  24708. for (; i < k;) {
  24709. n = d[i];
  24710. // 0 <= n < 4294967296
  24711. // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
  24712. if (n >= 4.29e9) {
  24713. d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
  24714. } else {
  24715. // 0 <= n <= 4289999999
  24716. // 0 <= (n % 1e7) <= 9999999
  24717. rd[i++] = n % 1e7;
  24718. }
  24719. }
  24720. // Node.js supporting crypto.randomBytes.
  24721. } else if (crypto.randomBytes) {
  24722. // buffer
  24723. d = crypto.randomBytes(k *= 4);
  24724. for (; i < k;) {
  24725. // 0 <= n < 2147483648
  24726. n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
  24727. // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
  24728. if (n >= 2.14e9) {
  24729. crypto.randomBytes(4).copy(d, i);
  24730. } else {
  24731. // 0 <= n <= 2139999999
  24732. // 0 <= (n % 1e7) <= 9999999
  24733. rd.push(n % 1e7);
  24734. i += 4;
  24735. }
  24736. }
  24737. i = k / 4;
  24738. } else {
  24739. throw Error(cryptoUnavailable);
  24740. }
  24741. k = rd[--i];
  24742. sd %= LOG_BASE;
  24743. // Convert trailing digits to zeros according to sd.
  24744. if (k && sd) {
  24745. n = mathpow(10, LOG_BASE - sd);
  24746. rd[i] = (k / n | 0) * n;
  24747. }
  24748. // Remove trailing words which are zero.
  24749. for (; rd[i] === 0; i--) rd.pop();
  24750. // Zero?
  24751. if (i < 0) {
  24752. e = 0;
  24753. rd = [0];
  24754. } else {
  24755. e = -1;
  24756. // Remove leading words which are zero and adjust exponent accordingly.
  24757. for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
  24758. // Count the digits of the first word of rd to determine leading zeros.
  24759. for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
  24760. // Adjust the exponent for leading zeros of the first word of rd.
  24761. if (k < LOG_BASE) e -= LOG_BASE - k;
  24762. }
  24763. r.e = e;
  24764. r.d = rd;
  24765. return r;
  24766. }
  24767. /*
  24768. * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
  24769. *
  24770. * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
  24771. *
  24772. * x {number|string|Decimal}
  24773. *
  24774. */
  24775. function round(x) {
  24776. return finalise(x = new this(x), x.e + 1, this.rounding);
  24777. }
  24778. /*
  24779. * Return
  24780. * 1 if x > 0,
  24781. * -1 if x < 0,
  24782. * 0 if x is 0,
  24783. * -0 if x is -0,
  24784. * NaN otherwise
  24785. *
  24786. * x {number|string|Decimal}
  24787. *
  24788. */
  24789. function sign(x) {
  24790. x = new this(x);
  24791. return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
  24792. }
  24793. /*
  24794. * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
  24795. * using rounding mode `rounding`.
  24796. *
  24797. * x {number|string|Decimal} A value in radians.
  24798. *
  24799. */
  24800. function sin(x) {
  24801. return new this(x).sin();
  24802. }
  24803. /*
  24804. * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
  24805. * significant digits using rounding mode `rounding`.
  24806. *
  24807. * x {number|string|Decimal} A value in radians.
  24808. *
  24809. */
  24810. function sinh(x) {
  24811. return new this(x).sinh();
  24812. }
  24813. /*
  24814. * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
  24815. * digits using rounding mode `rounding`.
  24816. *
  24817. * x {number|string|Decimal}
  24818. *
  24819. */
  24820. function sqrt(x) {
  24821. return new this(x).sqrt();
  24822. }
  24823. /*
  24824. * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
  24825. * using rounding mode `rounding`.
  24826. *
  24827. * x {number|string|Decimal}
  24828. * y {number|string|Decimal}
  24829. *
  24830. */
  24831. function sub(x, y) {
  24832. return new this(x).sub(y);
  24833. }
  24834. /*
  24835. * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
  24836. * digits using rounding mode `rounding`.
  24837. *
  24838. * x {number|string|Decimal} A value in radians.
  24839. *
  24840. */
  24841. function tan(x) {
  24842. return new this(x).tan();
  24843. }
  24844. /*
  24845. * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
  24846. * significant digits using rounding mode `rounding`.
  24847. *
  24848. * x {number|string|Decimal} A value in radians.
  24849. *
  24850. */
  24851. function tanh(x) {
  24852. return new this(x).tanh();
  24853. }
  24854. /*
  24855. * Return a new Decimal whose value is `x` truncated to an integer.
  24856. *
  24857. * x {number|string|Decimal}
  24858. *
  24859. */
  24860. function trunc(x) {
  24861. return finalise(x = new this(x), x.e + 1, 1);
  24862. }
  24863. // Create and configure initial Decimal constructor.
  24864. Decimal = clone(DEFAULTS);
  24865. Decimal['default'] = Decimal.Decimal = Decimal;
  24866. // Create the internal constants from their string values.
  24867. LN10 = new Decimal(LN10);
  24868. PI = new Decimal(PI);
  24869. // Export.
  24870. // AMD.
  24871. if (true) {
  24872. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
  24873. return Decimal;
  24874. }).call(exports, __webpack_require__, exports, module),
  24875. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  24876. // Node and other environments that support module.exports.
  24877. } else {}
  24878. })(this);
  24879. /***/ }),
  24880. /***/ "./node_modules/line-i18n/dist/LanguageService.js":
  24881. /*!********************************************************!*\
  24882. !*** ./node_modules/line-i18n/dist/LanguageService.js ***!
  24883. \********************************************************/
  24884. /*! exports provided: LanguageService */
  24885. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  24886. "use strict";
  24887. __webpack_require__.r(__webpack_exports__);
  24888. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LanguageService", function() { return LanguageService; });
  24889. var LanguageService = /** @class */ (function () {
  24890. function LanguageService(lsKey, defaultLang) {
  24891. if (defaultLang === void 0) { defaultLang = 'pt'; }
  24892. this.lsKey = lsKey;
  24893. this.defaultLang = defaultLang;
  24894. this.listeners = [];
  24895. this.document = document;
  24896. this.setupListener();
  24897. }
  24898. LanguageService.prototype.setupListener = function () {
  24899. var _this = this;
  24900. if (this.document !== null) {
  24901. this.document.addEventListener("storage", (function (event) {
  24902. var e = event;
  24903. if (e.key === _this.lsKey) {
  24904. _this.listeners.forEach(function (l) { return l(); });
  24905. }
  24906. }));
  24907. }
  24908. };
  24909. LanguageService.prototype.getLang = function () {
  24910. var lang = localStorage.getItem(this.lsKey);
  24911. if (lang === null || lang === undefined) {
  24912. console.warn("Internal Error: User language information has not been set. Returning default...");
  24913. return this.getDefaultLang();
  24914. }
  24915. return lang;
  24916. };
  24917. LanguageService.prototype.getDefaultLang = function () {
  24918. return this.defaultLang;
  24919. };
  24920. LanguageService.prototype.registerLanguageChangeListener = function (listener) {
  24921. this.listeners.push(listener);
  24922. };
  24923. return LanguageService;
  24924. }());
  24925. /***/ }),
  24926. /***/ "./node_modules/line-i18n/dist/LanguageServiceNoLS.js":
  24927. /*!************************************************************!*\
  24928. !*** ./node_modules/line-i18n/dist/LanguageServiceNoLS.js ***!
  24929. \************************************************************/
  24930. /*! exports provided: LanguageServiceNoLS */
  24931. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  24932. "use strict";
  24933. __webpack_require__.r(__webpack_exports__);
  24934. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LanguageServiceNoLS", function() { return LanguageServiceNoLS; });
  24935. var LanguageServiceNoLS = /** @class */ (function () {
  24936. function LanguageServiceNoLS(lang) {
  24937. this.lang = lang;
  24938. this.listeners = [];
  24939. }
  24940. LanguageServiceNoLS.prototype.setupListener = function () { };
  24941. LanguageServiceNoLS.prototype.notifyChange = function () {
  24942. this.listeners.forEach(function (l) { return l(); });
  24943. };
  24944. LanguageServiceNoLS.prototype.setLang = function (lang) {
  24945. this.lang = lang;
  24946. this.notifyChange();
  24947. };
  24948. LanguageServiceNoLS.prototype.getLang = function () {
  24949. return this.lang;
  24950. };
  24951. LanguageServiceNoLS.prototype.getDefaultLang = function () {
  24952. return this.lang;
  24953. };
  24954. LanguageServiceNoLS.prototype.registerLanguageChangeListener = function (listener) {
  24955. this.listeners.push(listener);
  24956. };
  24957. return LanguageServiceNoLS;
  24958. }());
  24959. /***/ }),
  24960. /***/ "./node_modules/line-i18n/dist/LocalizedStrings.js":
  24961. /*!*********************************************************!*\
  24962. !*** ./node_modules/line-i18n/dist/LocalizedStrings.js ***!
  24963. \*********************************************************/
  24964. /*! exports provided: LocalizedStrings */
  24965. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  24966. "use strict";
  24967. __webpack_require__.r(__webpack_exports__);
  24968. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocalizedStrings", function() { return LocalizedStrings; });
  24969. /* harmony import */ var _StringTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./StringTypes */ "./node_modules/line-i18n/dist/StringTypes.js");
  24970. var LocalizedStrings = /** @class */ (function () {
  24971. function LocalizedStrings(service, i18nData, listenToChange) {
  24972. var _this = this;
  24973. if (listenToChange === void 0) { listenToChange = false; }
  24974. this.service = service;
  24975. this.i18nData = i18nData;
  24976. this.listenToChange = listenToChange;
  24977. this.document = document;
  24978. if (this.listenToChange) {
  24979. service.registerLanguageChangeListener(function () {
  24980. _this.updateTagText();
  24981. });
  24982. }
  24983. }
  24984. LocalizedStrings.prototype.getString = function (id, type) {
  24985. var i18nObj = this.i18nData[this.service.getLang()];
  24986. if (!i18nObj) {
  24987. console.warn("Internal Error. The language set at ivprog.lang is not valid: " + this.service.getLang());
  24988. return this.getDefaultString(id, type);
  24989. }
  24990. if (!i18nObj[type]) {
  24991. return this.getDefaultString(id, type);
  24992. }
  24993. else if (!i18nObj[type][id]) {
  24994. return this.getDefaultString(id, type);
  24995. }
  24996. else {
  24997. return i18nObj[type][id];
  24998. }
  24999. };
  25000. LocalizedStrings.prototype.getDefaultString = function (id, type) {
  25001. var i18nObj = this.i18nData[this.service.getDefaultLang()];
  25002. if (!i18nObj[type]) {
  25003. return "{MISSING_I18N_TYPE_IDENTIFIER: " + type + "}";
  25004. }
  25005. else if (!i18nObj[type][id]) {
  25006. return "{MISSING_I18N_IDENTIFIER: " + id + "}";
  25007. }
  25008. else {
  25009. return i18nObj[type][id];
  25010. }
  25011. };
  25012. LocalizedStrings.prototype.getOR = function () {
  25013. return this.getUI("string_join_or");
  25014. };
  25015. LocalizedStrings.prototype.getError = function (id, context) {
  25016. if (context === void 0) { context = []; }
  25017. var text = this.getString(id, _StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].ERROR);
  25018. return this.processString(text, context);
  25019. };
  25020. LocalizedStrings.prototype.getMessage = function (id, context) {
  25021. if (context === void 0) { context = []; }
  25022. var text = this.getString(id, _StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].MESSAGE);
  25023. return this.processString(text, context);
  25024. };
  25025. LocalizedStrings.prototype.getUI = function (id, context) {
  25026. if (context === void 0) { context = []; }
  25027. var text = this.getString(id, _StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].UI);
  25028. return this.processString(text, context);
  25029. };
  25030. LocalizedStrings.prototype.processString = function (text, context) {
  25031. for (var i = 0; i < context.length; i++) {
  25032. var v = context[i];
  25033. text = text.replace("$" + i, v);
  25034. }
  25035. return text;
  25036. };
  25037. LocalizedStrings.prototype.updateTagText = function (func) {
  25038. var _this = this;
  25039. if (func === void 0) { func = null; }
  25040. if (this.document !== null) {
  25041. var list = this.document.querySelectorAll("data.i18n");
  25042. list.forEach(function (node) {
  25043. if (func === null) {
  25044. node.innerHTML = _this.processTagTex(node.getAttribute("value"));
  25045. }
  25046. else {
  25047. node.innerHTML = func(node.getAttribute("value"));
  25048. }
  25049. });
  25050. }
  25051. };
  25052. LocalizedStrings.prototype.processTagTex = function (text) {
  25053. if (text === null) {
  25054. return "<Invalid i18n identifier>";
  25055. }
  25056. var opts = text.split(":");
  25057. var type = opts[0].toLowerCase();
  25058. var id = opts[1];
  25059. if (_StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].ERROR === type) {
  25060. return this.getError(id);
  25061. }
  25062. else if (_StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].MESSAGE === type) {
  25063. return this.getMessage(id);
  25064. }
  25065. else if (_StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].UI === type) {
  25066. return this.getUI(id);
  25067. }
  25068. else {
  25069. console.warn(" A string has been passed to the i18n helper function that was not in the form type:id -> " +
  25070. text);
  25071. return this.getString(id, type);
  25072. }
  25073. };
  25074. return LocalizedStrings;
  25075. }());
  25076. /***/ }),
  25077. /***/ "./node_modules/line-i18n/dist/StringTypes.js":
  25078. /*!****************************************************!*\
  25079. !*** ./node_modules/line-i18n/dist/StringTypes.js ***!
  25080. \****************************************************/
  25081. /*! exports provided: StringTypes */
  25082. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  25083. "use strict";
  25084. __webpack_require__.r(__webpack_exports__);
  25085. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringTypes", function() { return StringTypes; });
  25086. var StringTypes;
  25087. (function (StringTypes) {
  25088. StringTypes["ERROR"] = "error";
  25089. StringTypes["MESSAGE"] = "message";
  25090. StringTypes["UI"] = "ui";
  25091. })(StringTypes || (StringTypes = {}));
  25092. /***/ }),
  25093. /***/ "./node_modules/line-i18n/dist/index.js":
  25094. /*!**********************************************!*\
  25095. !*** ./node_modules/line-i18n/dist/index.js ***!
  25096. \**********************************************/
  25097. /*! exports provided: default */
  25098. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  25099. "use strict";
  25100. __webpack_require__.r(__webpack_exports__);
  25101. /* harmony import */ var _LanguageService__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./LanguageService */ "./node_modules/line-i18n/dist/LanguageService.js");
  25102. /* harmony import */ var _LocalizedStrings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./LocalizedStrings */ "./node_modules/line-i18n/dist/LocalizedStrings.js");
  25103. /* harmony import */ var _StringTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./StringTypes */ "./node_modules/line-i18n/dist/StringTypes.js");
  25104. /* harmony import */ var _LanguageServiceNoLS__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LanguageServiceNoLS */ "./node_modules/line-i18n/dist/LanguageServiceNoLS.js");
  25105. /* harmony default export */ __webpack_exports__["default"] = ({
  25106. LanguageService: _LanguageService__WEBPACK_IMPORTED_MODULE_0__["LanguageService"],
  25107. LanguageServiceNoLS: _LanguageServiceNoLS__WEBPACK_IMPORTED_MODULE_3__["LanguageServiceNoLS"],
  25108. LocalizedStrings: _LocalizedStrings__WEBPACK_IMPORTED_MODULE_1__["LocalizedStrings"],
  25109. StringTypes: _StringTypes__WEBPACK_IMPORTED_MODULE_2__["StringTypes"]
  25110. });
  25111. /***/ }),
  25112. /***/ "./node_modules/melanke-watchjs/src/watch.js":
  25113. /*!***************************************************!*\
  25114. !*** ./node_modules/melanke-watchjs/src/watch.js ***!
  25115. \***************************************************/
  25116. /*! no static exports found */
  25117. /***/ (function(module, exports, __webpack_require__) {
  25118. "use strict";
  25119. /**
  25120. * DEVELOPED BY
  25121. * GIL LOPES BUENO
  25122. * gilbueno.mail@gmail.com
  25123. *
  25124. * WORKS WITH:
  25125. * IE8*, IE 9+, FF 4+, SF 5+, WebKit, CH 7+, OP 12+, BESEN, Rhino 1.7+
  25126. * For IE8 (and other legacy browsers) WatchJS will use dirty checking
  25127. *
  25128. * FORK:
  25129. * https://github.com/melanke/Watch.JS
  25130. *
  25131. * LICENSE: MIT
  25132. */
  25133. (function (factory) {
  25134. if (true) {
  25135. // Node. Does not work with strict CommonJS, but
  25136. // only CommonJS-like enviroments that support module.exports,
  25137. // like Node.
  25138. module.exports = factory();
  25139. } else {}
  25140. }(function () {
  25141. var WatchJS = {
  25142. noMore: false, // use WatchJS.suspend(obj) instead
  25143. useDirtyCheck: false, // use only dirty checking to track changes.
  25144. preserveExistingSetters: false
  25145. },
  25146. lengthsubjects = [];
  25147. var dirtyChecklist = [];
  25148. var pendingChanges = []; // used coalesce changes from defineProperty and __defineSetter__
  25149. var supportDefineProperty = false;
  25150. try {
  25151. supportDefineProperty = Object.defineProperty && Object.defineProperty({},'x', {});
  25152. } catch(ex) { /* not supported */ }
  25153. var isFunction = function (functionToCheck) {
  25154. var getType = {};
  25155. return functionToCheck && getType.toString.call(functionToCheck) == '[object Function]';
  25156. };
  25157. var isInt = function (x) {
  25158. return x % 1 === 0;
  25159. };
  25160. var isArray = function(obj) {
  25161. return Object.prototype.toString.call(obj) === '[object Array]';
  25162. };
  25163. var isObject = function(obj) {
  25164. return {}.toString.apply(obj) === '[object Object]';
  25165. };
  25166. var getObjDiff = function(a, b){
  25167. var aplus = [],
  25168. bplus = [];
  25169. if(!(typeof a == "string") && !(typeof b == "string")){
  25170. if (isArray(a) && b) {
  25171. for (var i=0; i<a.length; i++) {
  25172. if (b[i] === undefined) aplus.push(i);
  25173. }
  25174. } else {
  25175. for(var i in a){
  25176. if (a.hasOwnProperty(i)) {
  25177. if(b && !b.hasOwnProperty(i)) {
  25178. aplus.push(i);
  25179. }
  25180. }
  25181. }
  25182. }
  25183. if (isArray(b) && a) {
  25184. for (var j=0; j<b.length; j++) {
  25185. if (a[j] === undefined) bplus.push(j);
  25186. }
  25187. } else {
  25188. for(var j in b){
  25189. if (b.hasOwnProperty(j)) {
  25190. if(a && !a.hasOwnProperty(j)) {
  25191. bplus.push(j);
  25192. }
  25193. }
  25194. }
  25195. }
  25196. }
  25197. return {
  25198. added: aplus,
  25199. removed: bplus
  25200. }
  25201. };
  25202. var clone = function(obj){
  25203. if (null == obj || "object" != typeof obj) {
  25204. return obj;
  25205. }
  25206. var copy = obj.constructor();
  25207. for (var attr in obj) {
  25208. copy[attr] = obj[attr];
  25209. }
  25210. return copy;
  25211. }
  25212. var getExistingSetter = function (obj, propName) {
  25213. if (WatchJS.preserveExistingSetters) {
  25214. var existing = Object.getOwnPropertyDescriptor(obj, propName);
  25215. return existing.set;
  25216. }
  25217. return undefined;
  25218. }
  25219. var defineGetAndSet = function (obj, propName, getter, setter) {
  25220. try {
  25221. var existingSetter = getExistingSetter(obj, propName);
  25222. Object.defineProperty(obj, propName, {
  25223. get: getter,
  25224. set: function(value) {
  25225. setter.call(this, value, true); // coalesce changes
  25226. if (existingSetter) {
  25227. existingSetter(value);
  25228. }
  25229. },
  25230. enumerable: true,
  25231. configurable: true
  25232. });
  25233. }
  25234. catch(e1) {
  25235. try{
  25236. Object.prototype.__defineGetter__.call(obj, propName, getter);
  25237. Object.prototype.__defineSetter__.call(obj, propName, function(value) {
  25238. setter.call(this,value,true); // coalesce changes
  25239. });
  25240. }
  25241. catch(e2) {
  25242. observeDirtyChanges(obj,propName,setter);
  25243. //throw new Error("watchJS error: browser not supported :/")
  25244. }
  25245. }
  25246. };
  25247. var defineProp = function (obj, propName, value) {
  25248. try {
  25249. Object.defineProperty(obj, propName, {
  25250. enumerable: false,
  25251. configurable: true,
  25252. writable: false,
  25253. value: value
  25254. });
  25255. } catch(error) {
  25256. obj[propName] = value;
  25257. }
  25258. };
  25259. var observeDirtyChanges = function(obj,propName,setter) {
  25260. dirtyChecklist[dirtyChecklist.length] = {
  25261. prop: propName,
  25262. object: obj,
  25263. orig: clone(obj[propName]),
  25264. callback: setter
  25265. }
  25266. }
  25267. var watch = function () {
  25268. if (isFunction(arguments[1])) {
  25269. watchAll.apply(this, arguments);
  25270. } else if (isArray(arguments[1])) {
  25271. watchMany.apply(this, arguments);
  25272. } else {
  25273. watchOne.apply(this, arguments);
  25274. }
  25275. };
  25276. var watchAll = function (obj, watcher, level, addNRemove) {
  25277. if ((typeof obj == "string") || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  25278. return;
  25279. }
  25280. if(isArray(obj)) {
  25281. defineWatcher(obj, "__watchall__", watcher, level); // watch all changes on the array
  25282. if (level===undefined||level > 0) {
  25283. for (var prop = 0; prop < obj.length; prop++) { // watch objects in array
  25284. watchAll(obj[prop],watcher,level, addNRemove);
  25285. }
  25286. }
  25287. }
  25288. else {
  25289. var prop,props = [];
  25290. for (prop in obj) { //for each attribute if obj is an object
  25291. if (prop == "$val" || (!supportDefineProperty && prop === 'watchers')) {
  25292. continue;
  25293. }
  25294. if (Object.prototype.hasOwnProperty.call(obj, prop)) {
  25295. props.push(prop); //put in the props
  25296. }
  25297. }
  25298. watchMany(obj, props, watcher, level, addNRemove); //watch all items of the props
  25299. }
  25300. if (addNRemove) {
  25301. pushToLengthSubjects(obj, "$$watchlengthsubjectroot", watcher, level);
  25302. }
  25303. };
  25304. var watchMany = function (obj, props, watcher, level, addNRemove) {
  25305. if ((typeof obj == "string") || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  25306. return;
  25307. }
  25308. for (var i=0; i<props.length; i++) { //watch each property
  25309. var prop = props[i];
  25310. watchOne(obj, prop, watcher, level, addNRemove);
  25311. }
  25312. };
  25313. var watchOne = function (obj, prop, watcher, level, addNRemove) {
  25314. if ((typeof obj == "string") || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  25315. return;
  25316. }
  25317. if(isFunction(obj[prop])) { //dont watch if it is a function
  25318. return;
  25319. }
  25320. if(obj[prop] != null && (level === undefined || level > 0)){
  25321. watchAll(obj[prop], watcher, level!==undefined? level-1 : level); //recursively watch all attributes of this
  25322. }
  25323. defineWatcher(obj, prop, watcher, level);
  25324. if(addNRemove && (level === undefined || level > 0)){
  25325. pushToLengthSubjects(obj, prop, watcher, level);
  25326. }
  25327. };
  25328. var unwatch = function () {
  25329. if (isFunction(arguments[1])) {
  25330. unwatchAll.apply(this, arguments);
  25331. } else if (isArray(arguments[1])) {
  25332. unwatchMany.apply(this, arguments);
  25333. } else {
  25334. unwatchOne.apply(this, arguments);
  25335. }
  25336. };
  25337. var unwatchAll = function (obj, watcher) {
  25338. if (obj instanceof String || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  25339. return;
  25340. }
  25341. if (isArray(obj)) {
  25342. var props = ['__watchall__'];
  25343. for (var prop = 0; prop < obj.length; prop++) { //for each item if obj is an array
  25344. props.push(prop); //put in the props
  25345. }
  25346. unwatchMany(obj, props, watcher); //watch all itens of the props
  25347. } else {
  25348. var unwatchPropsInObject = function (obj2) {
  25349. var props = [];
  25350. for (var prop2 in obj2) { //for each attribute if obj is an object
  25351. if (obj2.hasOwnProperty(prop2)) {
  25352. if (obj2[prop2] instanceof Object) {
  25353. unwatchPropsInObject(obj2[prop2]); //recurs into object props
  25354. } else {
  25355. props.push(prop2); //put in the props
  25356. }
  25357. }
  25358. }
  25359. unwatchMany(obj2, props, watcher); //unwatch all of the props
  25360. };
  25361. unwatchPropsInObject(obj);
  25362. }
  25363. };
  25364. var unwatchMany = function (obj, props, watcher) {
  25365. for (var prop2 in props) { //watch each attribute of "props" if is an object
  25366. if (props.hasOwnProperty(prop2)) {
  25367. unwatchOne(obj, props[prop2], watcher);
  25368. }
  25369. }
  25370. };
  25371. var timeouts = [],
  25372. timerID = null;
  25373. function clearTimerID() {
  25374. timerID = null;
  25375. for(var i=0; i< timeouts.length; i++) {
  25376. timeouts[i]();
  25377. }
  25378. timeouts.length = 0;
  25379. }
  25380. var getTimerID= function () {
  25381. if (!timerID) {
  25382. timerID = setTimeout(clearTimerID);
  25383. }
  25384. return timerID;
  25385. }
  25386. var registerTimeout = function(fn) { // register function to be called on timeout
  25387. if (timerID==null) getTimerID();
  25388. timeouts[timeouts.length] = fn;
  25389. }
  25390. // Track changes made to an array, object or an object's property
  25391. // and invoke callback with a single change object containing type, value, oldvalue and array splices
  25392. // Syntax:
  25393. // trackChange(obj, callback, recursive, addNRemove)
  25394. // trackChange(obj, prop, callback, recursive, addNRemove)
  25395. var trackChange = function() {
  25396. var fn = (isFunction(arguments[2])) ? trackProperty : trackObject ;
  25397. fn.apply(this,arguments);
  25398. }
  25399. // track changes made to an object and invoke callback with a single change object containing type, value and array splices
  25400. var trackObject= function(obj, callback, recursive, addNRemove) {
  25401. var change = null,lastTimerID = -1;
  25402. var isArr = isArray(obj);
  25403. var level,fn = function(prop, action, newValue, oldValue) {
  25404. var timerID = getTimerID();
  25405. if (lastTimerID!==timerID) { // check if timer has changed since last update
  25406. lastTimerID = timerID;
  25407. change = {
  25408. type: 'update'
  25409. }
  25410. change['value'] = obj;
  25411. change['splices'] = null;
  25412. registerTimeout(function() {
  25413. callback.call(this,change);
  25414. change = null;
  25415. });
  25416. }
  25417. // create splices for array changes
  25418. if (isArr && obj === this && change !== null) {
  25419. if (action==='pop'||action==='shift') {
  25420. newValue = [];
  25421. oldValue = [oldValue];
  25422. }
  25423. else if (action==='push'||action==='unshift') {
  25424. newValue = [newValue];
  25425. oldValue = [];
  25426. }
  25427. else if (action!=='splice') {
  25428. return; // return here - for reverse and sort operations we don't need to return splices. a simple update will do
  25429. }
  25430. if (!change.splices) change.splices = [];
  25431. change.splices[change.splices.length] = {
  25432. index: prop,
  25433. deleteCount: oldValue ? oldValue.length : 0,
  25434. addedCount: newValue ? newValue.length : 0,
  25435. added: newValue,
  25436. deleted: oldValue
  25437. };
  25438. }
  25439. }
  25440. level = (recursive==true) ? undefined : 0;
  25441. watchAll(obj,fn, level, addNRemove);
  25442. }
  25443. // track changes made to the property of an object and invoke callback with a single change object containing type, value, oldvalue and splices
  25444. var trackProperty = function(obj,prop,callback,recursive, addNRemove) {
  25445. if (obj && prop) {
  25446. watchOne(obj,prop,function(prop, action, newvalue, oldvalue) {
  25447. var change = {
  25448. type: 'update'
  25449. }
  25450. change['value'] = newvalue;
  25451. change['oldvalue'] = oldvalue;
  25452. if (recursive && isObject(newvalue)||isArray(newvalue)) {
  25453. trackObject(newvalue,callback,recursive, addNRemove);
  25454. }
  25455. callback.call(this,change);
  25456. },0)
  25457. if (recursive && isObject(obj[prop])||isArray(obj[prop])) {
  25458. trackObject(obj[prop],callback,recursive, addNRemove);
  25459. }
  25460. }
  25461. }
  25462. var defineWatcher = function (obj, prop, watcher, level) {
  25463. var newWatcher = false;
  25464. var isArr = isArray(obj);
  25465. if (!obj.watchers) {
  25466. defineProp(obj, "watchers", {});
  25467. if (isArr) {
  25468. // watch array functions
  25469. watchFunctions(obj, function(index,action,newValue, oldValue) {
  25470. addPendingChange(obj, index, action,newValue, oldValue);
  25471. if (level !== 0 && newValue && (isObject(newValue) || isArray(newValue))) {
  25472. var i,n, ln, wAll, watchList = obj.watchers[prop];
  25473. if ((wAll = obj.watchers['__watchall__'])) {
  25474. watchList = watchList ? watchList.concat(wAll) : wAll;
  25475. }
  25476. ln = watchList ? watchList.length : 0;
  25477. for (i = 0; i<ln; i++) {
  25478. if (action!=='splice') {
  25479. watchAll(newValue, watchList[i], (level===undefined)?level:level-1);
  25480. }
  25481. else {
  25482. // watch spliced values
  25483. for(n=0; n < newValue.length; n++) {
  25484. watchAll(newValue[n], watchList[i], (level===undefined)?level:level-1);
  25485. }
  25486. }
  25487. }
  25488. }
  25489. });
  25490. }
  25491. }
  25492. if (!obj.watchers[prop]) {
  25493. obj.watchers[prop] = [];
  25494. if (!isArr) newWatcher = true;
  25495. }
  25496. for (var i=0; i<obj.watchers[prop].length; i++) {
  25497. if(obj.watchers[prop][i] === watcher){
  25498. return;
  25499. }
  25500. }
  25501. obj.watchers[prop].push(watcher); //add the new watcher to the watchers array
  25502. if (newWatcher) {
  25503. var val = obj[prop];
  25504. var getter = function () {
  25505. return val;
  25506. };
  25507. var setter = function (newval, delayWatcher) {
  25508. var oldval = val;
  25509. val = newval;
  25510. if (level !== 0
  25511. && obj[prop] && (isObject(obj[prop]) || isArray(obj[prop]))
  25512. && !obj[prop].watchers) {
  25513. // watch sub properties
  25514. var i,ln = obj.watchers[prop].length;
  25515. for(i=0; i<ln; i++) {
  25516. watchAll(obj[prop], obj.watchers[prop][i], (level===undefined)?level:level-1);
  25517. }
  25518. }
  25519. //watchFunctions(obj, prop);
  25520. if (isSuspended(obj, prop)) {
  25521. resume(obj, prop);
  25522. return;
  25523. }
  25524. if (!WatchJS.noMore){ // this does not work with Object.observe
  25525. //if (JSON.stringify(oldval) !== JSON.stringify(newval)) {
  25526. if (obj[prop] instanceof Date && oldval && newval) {
  25527. oldval = oldval.valueOf();
  25528. newval = newval.valueOf();
  25529. }
  25530. if (oldval !== newval) {
  25531. if (!delayWatcher) {
  25532. callWatchers(obj, prop, "set", newval, oldval);
  25533. }
  25534. else {
  25535. addPendingChange(obj, prop, "set", newval, oldval);
  25536. }
  25537. WatchJS.noMore = false;
  25538. }
  25539. }
  25540. };
  25541. if (WatchJS.useDirtyCheck) {
  25542. observeDirtyChanges(obj,prop,setter);
  25543. }
  25544. else {
  25545. defineGetAndSet(obj, prop, getter, setter);
  25546. }
  25547. }
  25548. };
  25549. var callWatchers = function (obj, prop, action, newval, oldval) {
  25550. if (prop !== undefined) {
  25551. var ln, wl, watchList = obj.watchers[prop];
  25552. if ((wl = obj.watchers['__watchall__'])) {
  25553. watchList = watchList ? watchList.concat(wl) : wl;
  25554. }
  25555. ln = watchList ? watchList.length : 0;
  25556. for (var wr=0; wr< ln; wr++) {
  25557. watchList[wr].call(obj, prop, action, newval, oldval);
  25558. }
  25559. } else {
  25560. for (var prop in obj) {//call all
  25561. if (obj.hasOwnProperty(prop)) {
  25562. callWatchers(obj, prop, action, newval, oldval);
  25563. }
  25564. }
  25565. }
  25566. };
  25567. var methodNames = ['pop', 'push', 'reverse', 'shift', 'sort', 'slice', 'unshift', 'splice'];
  25568. var defineArrayMethodWatcher = function (obj, original, methodName, callback) {
  25569. defineProp(obj, methodName, function () {
  25570. var index = 0;
  25571. var i,newValue, oldValue, response;
  25572. // get values before splicing array
  25573. if (methodName === 'splice') {
  25574. var start = arguments[0];
  25575. var end = start + arguments[1];
  25576. oldValue = obj.slice(start,end);
  25577. newValue = [];
  25578. for(i=2;i<arguments.length;i++) {
  25579. newValue[i-2] = arguments[i];
  25580. }
  25581. index = start;
  25582. }
  25583. else {
  25584. newValue = arguments.length > 0 ? arguments[0] : undefined;
  25585. }
  25586. response = original.apply(obj, arguments);
  25587. if (methodName !== 'slice') {
  25588. if (methodName === 'pop') {
  25589. oldValue = response;
  25590. index = obj.length;
  25591. }
  25592. else if (methodName === 'push') {
  25593. index = obj.length-1;
  25594. }
  25595. else if (methodName === 'shift') {
  25596. oldValue = response;
  25597. }
  25598. else if (methodName !== 'unshift' && newValue===undefined) {
  25599. newValue = response;
  25600. }
  25601. callback.call(obj, index, methodName,newValue, oldValue)
  25602. }
  25603. return response;
  25604. });
  25605. };
  25606. var watchFunctions = function(obj, callback) {
  25607. if (!isFunction(callback) || !obj || (obj instanceof String) || (!isArray(obj))) {
  25608. return;
  25609. }
  25610. for (var i = methodNames.length, methodName; i--;) {
  25611. methodName = methodNames[i];
  25612. defineArrayMethodWatcher(obj, obj[methodName], methodName, callback);
  25613. }
  25614. };
  25615. var unwatchOne = function (obj, prop, watcher) {
  25616. if (prop) {
  25617. if (obj.watchers && obj.watchers[prop]) {
  25618. if (watcher === undefined) {
  25619. delete obj.watchers[prop]; // remove all property watchers
  25620. }
  25621. else {
  25622. for (var i = 0; i < obj.watchers[prop].length; i++) {
  25623. var w = obj.watchers[prop][i];
  25624. if (w == watcher) {
  25625. obj.watchers[prop].splice(i, 1);
  25626. }
  25627. }
  25628. }
  25629. }
  25630. } else {
  25631. delete obj.watchers;
  25632. }
  25633. removeFromLengthSubjects(obj, prop, watcher);
  25634. removeFromDirtyChecklist(obj, prop);
  25635. };
  25636. // suspend watchers until next update cycle
  25637. var suspend = function(obj, prop) {
  25638. if (obj.watchers) {
  25639. var name = '__wjs_suspend__'+(prop!==undefined ? prop : '');
  25640. obj.watchers[name] = true;
  25641. }
  25642. }
  25643. var isSuspended = function(obj, prop) {
  25644. return obj.watchers
  25645. && (obj.watchers['__wjs_suspend__'] ||
  25646. obj.watchers['__wjs_suspend__'+prop]);
  25647. }
  25648. // resumes preivously suspended watchers
  25649. var resume = function(obj, prop) {
  25650. registerTimeout(function() {
  25651. delete obj.watchers['__wjs_suspend__'];
  25652. delete obj.watchers['__wjs_suspend__'+prop];
  25653. })
  25654. }
  25655. var pendingTimerID = null;
  25656. var addPendingChange = function(obj,prop, mode, newval, oldval) {
  25657. pendingChanges[pendingChanges.length] = {
  25658. obj:obj,
  25659. prop: prop,
  25660. mode: mode,
  25661. newval: newval,
  25662. oldval: oldval
  25663. };
  25664. if (pendingTimerID===null) {
  25665. pendingTimerID = setTimeout(applyPendingChanges);
  25666. }
  25667. };
  25668. var applyPendingChanges = function() {
  25669. // apply pending changes
  25670. var change = null;
  25671. pendingTimerID = null;
  25672. for(var i=0;i < pendingChanges.length;i++) {
  25673. change = pendingChanges[i];
  25674. callWatchers(change.obj, change.prop, change.mode, change.newval, change.oldval);
  25675. }
  25676. if (change) {
  25677. pendingChanges = [];
  25678. change = null;
  25679. }
  25680. }
  25681. var loop = function(){
  25682. // check for new or deleted props
  25683. for(var i=0; i<lengthsubjects.length; i++) {
  25684. var subj = lengthsubjects[i];
  25685. if (subj.prop === "$$watchlengthsubjectroot") {
  25686. var difference = getObjDiff(subj.obj, subj.actual);
  25687. if(difference.added.length || difference.removed.length){
  25688. if(difference.added.length){
  25689. watchMany(subj.obj, difference.added, subj.watcher, subj.level - 1, true);
  25690. }
  25691. subj.watcher.call(subj.obj, "root", "differentattr", difference, subj.actual);
  25692. }
  25693. subj.actual = clone(subj.obj);
  25694. } else {
  25695. var difference = getObjDiff(subj.obj[subj.prop], subj.actual);
  25696. if(difference.added.length || difference.removed.length){
  25697. if(difference.added.length){
  25698. for (var j=0; j<subj.obj.watchers[subj.prop].length; j++) {
  25699. watchMany(subj.obj[subj.prop], difference.added, subj.obj.watchers[subj.prop][j], subj.level - 1, true);
  25700. }
  25701. }
  25702. callWatchers(subj.obj, subj.prop, "differentattr", difference, subj.actual);
  25703. }
  25704. subj.actual = clone(subj.obj[subj.prop]);
  25705. }
  25706. }
  25707. // start dirty check
  25708. var n, value;
  25709. if (dirtyChecklist.length > 0) {
  25710. for (var i = 0; i < dirtyChecklist.length; i++) {
  25711. n = dirtyChecklist[i];
  25712. value = n.object[n.prop];
  25713. if (!compareValues(n.orig, value)) {
  25714. n.orig = clone(value);
  25715. n.callback(value);
  25716. }
  25717. }
  25718. }
  25719. };
  25720. var compareValues = function(a,b) {
  25721. var i, state = true;
  25722. if (a!==b) {
  25723. if (isObject(a)) {
  25724. for(i in a) {
  25725. if (!supportDefineProperty && i==='watchers') continue;
  25726. if (a[i]!==b[i]) {
  25727. state = false;
  25728. break;
  25729. };
  25730. }
  25731. }
  25732. else {
  25733. state = false;
  25734. }
  25735. }
  25736. return state;
  25737. }
  25738. var pushToLengthSubjects = function(obj, prop, watcher, level){
  25739. var actual;
  25740. if (prop === "$$watchlengthsubjectroot") {
  25741. actual = clone(obj);
  25742. } else {
  25743. actual = clone(obj[prop]);
  25744. }
  25745. lengthsubjects.push({
  25746. obj: obj,
  25747. prop: prop,
  25748. actual: actual,
  25749. watcher: watcher,
  25750. level: level
  25751. });
  25752. };
  25753. var removeFromLengthSubjects = function(obj, prop, watcher){
  25754. for (var i=0; i<lengthsubjects.length; i++) {
  25755. var subj = lengthsubjects[i];
  25756. if (subj.obj == obj) {
  25757. if (!prop || subj.prop == prop) {
  25758. if (!watcher || subj.watcher == watcher) {
  25759. // if we splice off one item at position i
  25760. // we need to decrement i as the array is one item shorter
  25761. // so when we increment i in the loop statement we
  25762. // will land at the correct index.
  25763. // if it's not decremented, you won't delete all length subjects
  25764. lengthsubjects.splice(i--, 1);
  25765. }
  25766. }
  25767. }
  25768. }
  25769. };
  25770. var removeFromDirtyChecklist = function(obj, prop){
  25771. var notInUse;
  25772. for (var i=0; i<dirtyChecklist.length; i++) {
  25773. var n = dirtyChecklist[i];
  25774. var watchers = n.object.watchers;
  25775. notInUse = (
  25776. n.object == obj
  25777. && (!prop || n.prop == prop)
  25778. && watchers
  25779. && (!prop || !watchers[prop] || watchers[prop].length == 0 )
  25780. );
  25781. if (notInUse) {
  25782. // we use the same syntax as in removeFromLengthSubjects
  25783. dirtyChecklist.splice(i--, 1);
  25784. }
  25785. }
  25786. };
  25787. setInterval(loop, 50);
  25788. WatchJS.watch = watch;
  25789. WatchJS.unwatch = unwatch;
  25790. WatchJS.callWatchers = callWatchers;
  25791. WatchJS.suspend = suspend; // suspend watchers
  25792. WatchJS.onChange = trackChange; // track changes made to object or it's property and return a single change object
  25793. return WatchJS;
  25794. }));
  25795. /***/ }),
  25796. /***/ "./node_modules/node-libs-browser/mock/empty.js":
  25797. /*!******************************************************!*\
  25798. !*** ./node_modules/node-libs-browser/mock/empty.js ***!
  25799. \******************************************************/
  25800. /*! no static exports found */
  25801. /***/ (function(module, exports) {
  25802. /***/ }),
  25803. /***/ "./node_modules/regenerator-runtime/runtime.js":
  25804. /*!*****************************************************!*\
  25805. !*** ./node_modules/regenerator-runtime/runtime.js ***!
  25806. \*****************************************************/
  25807. /*! no static exports found */
  25808. /***/ (function(module, exports, __webpack_require__) {
  25809. /**
  25810. * Copyright (c) 2014-present, Facebook, Inc.
  25811. *
  25812. * This source code is licensed under the MIT license found in the
  25813. * LICENSE file in the root directory of this source tree.
  25814. */
  25815. var runtime = (function (exports) {
  25816. "use strict";
  25817. var Op = Object.prototype;
  25818. var hasOwn = Op.hasOwnProperty;
  25819. var undefined; // More compressible than void 0.
  25820. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  25821. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  25822. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  25823. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  25824. function wrap(innerFn, outerFn, self, tryLocsList) {
  25825. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  25826. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  25827. var generator = Object.create(protoGenerator.prototype);
  25828. var context = new Context(tryLocsList || []);
  25829. // The ._invoke method unifies the implementations of the .next,
  25830. // .throw, and .return methods.
  25831. generator._invoke = makeInvokeMethod(innerFn, self, context);
  25832. return generator;
  25833. }
  25834. exports.wrap = wrap;
  25835. // Try/catch helper to minimize deoptimizations. Returns a completion
  25836. // record like context.tryEntries[i].completion. This interface could
  25837. // have been (and was previously) designed to take a closure to be
  25838. // invoked without arguments, but in all the cases we care about we
  25839. // already have an existing method we want to call, so there's no need
  25840. // to create a new function object. We can even get away with assuming
  25841. // the method takes exactly one argument, since that happens to be true
  25842. // in every case, so we don't have to touch the arguments object. The
  25843. // only additional allocation required is the completion record, which
  25844. // has a stable shape and so hopefully should be cheap to allocate.
  25845. function tryCatch(fn, obj, arg) {
  25846. try {
  25847. return { type: "normal", arg: fn.call(obj, arg) };
  25848. } catch (err) {
  25849. return { type: "throw", arg: err };
  25850. }
  25851. }
  25852. var GenStateSuspendedStart = "suspendedStart";
  25853. var GenStateSuspendedYield = "suspendedYield";
  25854. var GenStateExecuting = "executing";
  25855. var GenStateCompleted = "completed";
  25856. // Returning this object from the innerFn has the same effect as
  25857. // breaking out of the dispatch switch statement.
  25858. var ContinueSentinel = {};
  25859. // Dummy constructor functions that we use as the .constructor and
  25860. // .constructor.prototype properties for functions that return Generator
  25861. // objects. For full spec compliance, you may wish to configure your
  25862. // minifier not to mangle the names of these two functions.
  25863. function Generator() {}
  25864. function GeneratorFunction() {}
  25865. function GeneratorFunctionPrototype() {}
  25866. // This is a polyfill for %IteratorPrototype% for environments that
  25867. // don't natively support it.
  25868. var IteratorPrototype = {};
  25869. IteratorPrototype[iteratorSymbol] = function () {
  25870. return this;
  25871. };
  25872. var getProto = Object.getPrototypeOf;
  25873. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  25874. if (NativeIteratorPrototype &&
  25875. NativeIteratorPrototype !== Op &&
  25876. hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  25877. // This environment has a native %IteratorPrototype%; use it instead
  25878. // of the polyfill.
  25879. IteratorPrototype = NativeIteratorPrototype;
  25880. }
  25881. var Gp = GeneratorFunctionPrototype.prototype =
  25882. Generator.prototype = Object.create(IteratorPrototype);
  25883. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  25884. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  25885. GeneratorFunctionPrototype[toStringTagSymbol] =
  25886. GeneratorFunction.displayName = "GeneratorFunction";
  25887. // Helper for defining the .next, .throw, and .return methods of the
  25888. // Iterator interface in terms of a single ._invoke method.
  25889. function defineIteratorMethods(prototype) {
  25890. ["next", "throw", "return"].forEach(function(method) {
  25891. prototype[method] = function(arg) {
  25892. return this._invoke(method, arg);
  25893. };
  25894. });
  25895. }
  25896. exports.isGeneratorFunction = function(genFun) {
  25897. var ctor = typeof genFun === "function" && genFun.constructor;
  25898. return ctor
  25899. ? ctor === GeneratorFunction ||
  25900. // For the native GeneratorFunction constructor, the best we can
  25901. // do is to check its .name property.
  25902. (ctor.displayName || ctor.name) === "GeneratorFunction"
  25903. : false;
  25904. };
  25905. exports.mark = function(genFun) {
  25906. if (Object.setPrototypeOf) {
  25907. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  25908. } else {
  25909. genFun.__proto__ = GeneratorFunctionPrototype;
  25910. if (!(toStringTagSymbol in genFun)) {
  25911. genFun[toStringTagSymbol] = "GeneratorFunction";
  25912. }
  25913. }
  25914. genFun.prototype = Object.create(Gp);
  25915. return genFun;
  25916. };
  25917. // Within the body of any async function, `await x` is transformed to
  25918. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  25919. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  25920. // meant to be awaited.
  25921. exports.awrap = function(arg) {
  25922. return { __await: arg };
  25923. };
  25924. function AsyncIterator(generator, PromiseImpl) {
  25925. function invoke(method, arg, resolve, reject) {
  25926. var record = tryCatch(generator[method], generator, arg);
  25927. if (record.type === "throw") {
  25928. reject(record.arg);
  25929. } else {
  25930. var result = record.arg;
  25931. var value = result.value;
  25932. if (value &&
  25933. typeof value === "object" &&
  25934. hasOwn.call(value, "__await")) {
  25935. return PromiseImpl.resolve(value.__await).then(function(value) {
  25936. invoke("next", value, resolve, reject);
  25937. }, function(err) {
  25938. invoke("throw", err, resolve, reject);
  25939. });
  25940. }
  25941. return PromiseImpl.resolve(value).then(function(unwrapped) {
  25942. // When a yielded Promise is resolved, its final value becomes
  25943. // the .value of the Promise<{value,done}> result for the
  25944. // current iteration.
  25945. result.value = unwrapped;
  25946. resolve(result);
  25947. }, function(error) {
  25948. // If a rejected Promise was yielded, throw the rejection back
  25949. // into the async generator function so it can be handled there.
  25950. return invoke("throw", error, resolve, reject);
  25951. });
  25952. }
  25953. }
  25954. var previousPromise;
  25955. function enqueue(method, arg) {
  25956. function callInvokeWithMethodAndArg() {
  25957. return new PromiseImpl(function(resolve, reject) {
  25958. invoke(method, arg, resolve, reject);
  25959. });
  25960. }
  25961. return previousPromise =
  25962. // If enqueue has been called before, then we want to wait until
  25963. // all previous Promises have been resolved before calling invoke,
  25964. // so that results are always delivered in the correct order. If
  25965. // enqueue has not been called before, then it is important to
  25966. // call invoke immediately, without waiting on a callback to fire,
  25967. // so that the async generator function has the opportunity to do
  25968. // any necessary setup in a predictable way. This predictability
  25969. // is why the Promise constructor synchronously invokes its
  25970. // executor callback, and why async functions synchronously
  25971. // execute code before the first await. Since we implement simple
  25972. // async functions in terms of async generators, it is especially
  25973. // important to get this right, even though it requires care.
  25974. previousPromise ? previousPromise.then(
  25975. callInvokeWithMethodAndArg,
  25976. // Avoid propagating failures to Promises returned by later
  25977. // invocations of the iterator.
  25978. callInvokeWithMethodAndArg
  25979. ) : callInvokeWithMethodAndArg();
  25980. }
  25981. // Define the unified helper method that is used to implement .next,
  25982. // .throw, and .return (see defineIteratorMethods).
  25983. this._invoke = enqueue;
  25984. }
  25985. defineIteratorMethods(AsyncIterator.prototype);
  25986. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  25987. return this;
  25988. };
  25989. exports.AsyncIterator = AsyncIterator;
  25990. // Note that simple async functions are implemented on top of
  25991. // AsyncIterator objects; they just return a Promise for the value of
  25992. // the final result produced by the iterator.
  25993. exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  25994. if (PromiseImpl === void 0) PromiseImpl = Promise;
  25995. var iter = new AsyncIterator(
  25996. wrap(innerFn, outerFn, self, tryLocsList),
  25997. PromiseImpl
  25998. );
  25999. return exports.isGeneratorFunction(outerFn)
  26000. ? iter // If outerFn is a generator, return the full iterator.
  26001. : iter.next().then(function(result) {
  26002. return result.done ? result.value : iter.next();
  26003. });
  26004. };
  26005. function makeInvokeMethod(innerFn, self, context) {
  26006. var state = GenStateSuspendedStart;
  26007. return function invoke(method, arg) {
  26008. if (state === GenStateExecuting) {
  26009. throw new Error("Generator is already running");
  26010. }
  26011. if (state === GenStateCompleted) {
  26012. if (method === "throw") {
  26013. throw arg;
  26014. }
  26015. // Be forgiving, per 25.3.3.3.3 of the spec:
  26016. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  26017. return doneResult();
  26018. }
  26019. context.method = method;
  26020. context.arg = arg;
  26021. while (true) {
  26022. var delegate = context.delegate;
  26023. if (delegate) {
  26024. var delegateResult = maybeInvokeDelegate(delegate, context);
  26025. if (delegateResult) {
  26026. if (delegateResult === ContinueSentinel) continue;
  26027. return delegateResult;
  26028. }
  26029. }
  26030. if (context.method === "next") {
  26031. // Setting context._sent for legacy support of Babel's
  26032. // function.sent implementation.
  26033. context.sent = context._sent = context.arg;
  26034. } else if (context.method === "throw") {
  26035. if (state === GenStateSuspendedStart) {
  26036. state = GenStateCompleted;
  26037. throw context.arg;
  26038. }
  26039. context.dispatchException(context.arg);
  26040. } else if (context.method === "return") {
  26041. context.abrupt("return", context.arg);
  26042. }
  26043. state = GenStateExecuting;
  26044. var record = tryCatch(innerFn, self, context);
  26045. if (record.type === "normal") {
  26046. // If an exception is thrown from innerFn, we leave state ===
  26047. // GenStateExecuting and loop back for another invocation.
  26048. state = context.done
  26049. ? GenStateCompleted
  26050. : GenStateSuspendedYield;
  26051. if (record.arg === ContinueSentinel) {
  26052. continue;
  26053. }
  26054. return {
  26055. value: record.arg,
  26056. done: context.done
  26057. };
  26058. } else if (record.type === "throw") {
  26059. state = GenStateCompleted;
  26060. // Dispatch the exception by looping back around to the
  26061. // context.dispatchException(context.arg) call above.
  26062. context.method = "throw";
  26063. context.arg = record.arg;
  26064. }
  26065. }
  26066. };
  26067. }
  26068. // Call delegate.iterator[context.method](context.arg) and handle the
  26069. // result, either by returning a { value, done } result from the
  26070. // delegate iterator, or by modifying context.method and context.arg,
  26071. // setting context.delegate to null, and returning the ContinueSentinel.
  26072. function maybeInvokeDelegate(delegate, context) {
  26073. var method = delegate.iterator[context.method];
  26074. if (method === undefined) {
  26075. // A .throw or .return when the delegate iterator has no .throw
  26076. // method always terminates the yield* loop.
  26077. context.delegate = null;
  26078. if (context.method === "throw") {
  26079. // Note: ["return"] must be used for ES3 parsing compatibility.
  26080. if (delegate.iterator["return"]) {
  26081. // If the delegate iterator has a return method, give it a
  26082. // chance to clean up.
  26083. context.method = "return";
  26084. context.arg = undefined;
  26085. maybeInvokeDelegate(delegate, context);
  26086. if (context.method === "throw") {
  26087. // If maybeInvokeDelegate(context) changed context.method from
  26088. // "return" to "throw", let that override the TypeError below.
  26089. return ContinueSentinel;
  26090. }
  26091. }
  26092. context.method = "throw";
  26093. context.arg = new TypeError(
  26094. "The iterator does not provide a 'throw' method");
  26095. }
  26096. return ContinueSentinel;
  26097. }
  26098. var record = tryCatch(method, delegate.iterator, context.arg);
  26099. if (record.type === "throw") {
  26100. context.method = "throw";
  26101. context.arg = record.arg;
  26102. context.delegate = null;
  26103. return ContinueSentinel;
  26104. }
  26105. var info = record.arg;
  26106. if (! info) {
  26107. context.method = "throw";
  26108. context.arg = new TypeError("iterator result is not an object");
  26109. context.delegate = null;
  26110. return ContinueSentinel;
  26111. }
  26112. if (info.done) {
  26113. // Assign the result of the finished delegate to the temporary
  26114. // variable specified by delegate.resultName (see delegateYield).
  26115. context[delegate.resultName] = info.value;
  26116. // Resume execution at the desired location (see delegateYield).
  26117. context.next = delegate.nextLoc;
  26118. // If context.method was "throw" but the delegate handled the
  26119. // exception, let the outer generator proceed normally. If
  26120. // context.method was "next", forget context.arg since it has been
  26121. // "consumed" by the delegate iterator. If context.method was
  26122. // "return", allow the original .return call to continue in the
  26123. // outer generator.
  26124. if (context.method !== "return") {
  26125. context.method = "next";
  26126. context.arg = undefined;
  26127. }
  26128. } else {
  26129. // Re-yield the result returned by the delegate method.
  26130. return info;
  26131. }
  26132. // The delegate iterator is finished, so forget it and continue with
  26133. // the outer generator.
  26134. context.delegate = null;
  26135. return ContinueSentinel;
  26136. }
  26137. // Define Generator.prototype.{next,throw,return} in terms of the
  26138. // unified ._invoke helper method.
  26139. defineIteratorMethods(Gp);
  26140. Gp[toStringTagSymbol] = "Generator";
  26141. // A Generator should always return itself as the iterator object when the
  26142. // @@iterator function is called on it. Some browsers' implementations of the
  26143. // iterator prototype chain incorrectly implement this, causing the Generator
  26144. // object to not be returned from this call. This ensures that doesn't happen.
  26145. // See https://github.com/facebook/regenerator/issues/274 for more details.
  26146. Gp[iteratorSymbol] = function() {
  26147. return this;
  26148. };
  26149. Gp.toString = function() {
  26150. return "[object Generator]";
  26151. };
  26152. function pushTryEntry(locs) {
  26153. var entry = { tryLoc: locs[0] };
  26154. if (1 in locs) {
  26155. entry.catchLoc = locs[1];
  26156. }
  26157. if (2 in locs) {
  26158. entry.finallyLoc = locs[2];
  26159. entry.afterLoc = locs[3];
  26160. }
  26161. this.tryEntries.push(entry);
  26162. }
  26163. function resetTryEntry(entry) {
  26164. var record = entry.completion || {};
  26165. record.type = "normal";
  26166. delete record.arg;
  26167. entry.completion = record;
  26168. }
  26169. function Context(tryLocsList) {
  26170. // The root entry object (effectively a try statement without a catch
  26171. // or a finally block) gives us a place to store values thrown from
  26172. // locations where there is no enclosing try statement.
  26173. this.tryEntries = [{ tryLoc: "root" }];
  26174. tryLocsList.forEach(pushTryEntry, this);
  26175. this.reset(true);
  26176. }
  26177. exports.keys = function(object) {
  26178. var keys = [];
  26179. for (var key in object) {
  26180. keys.push(key);
  26181. }
  26182. keys.reverse();
  26183. // Rather than returning an object with a next method, we keep
  26184. // things simple and return the next function itself.
  26185. return function next() {
  26186. while (keys.length) {
  26187. var key = keys.pop();
  26188. if (key in object) {
  26189. next.value = key;
  26190. next.done = false;
  26191. return next;
  26192. }
  26193. }
  26194. // To avoid creating an additional object, we just hang the .value
  26195. // and .done properties off the next function object itself. This
  26196. // also ensures that the minifier will not anonymize the function.
  26197. next.done = true;
  26198. return next;
  26199. };
  26200. };
  26201. function values(iterable) {
  26202. if (iterable) {
  26203. var iteratorMethod = iterable[iteratorSymbol];
  26204. if (iteratorMethod) {
  26205. return iteratorMethod.call(iterable);
  26206. }
  26207. if (typeof iterable.next === "function") {
  26208. return iterable;
  26209. }
  26210. if (!isNaN(iterable.length)) {
  26211. var i = -1, next = function next() {
  26212. while (++i < iterable.length) {
  26213. if (hasOwn.call(iterable, i)) {
  26214. next.value = iterable[i];
  26215. next.done = false;
  26216. return next;
  26217. }
  26218. }
  26219. next.value = undefined;
  26220. next.done = true;
  26221. return next;
  26222. };
  26223. return next.next = next;
  26224. }
  26225. }
  26226. // Return an iterator with no values.
  26227. return { next: doneResult };
  26228. }
  26229. exports.values = values;
  26230. function doneResult() {
  26231. return { value: undefined, done: true };
  26232. }
  26233. Context.prototype = {
  26234. constructor: Context,
  26235. reset: function(skipTempReset) {
  26236. this.prev = 0;
  26237. this.next = 0;
  26238. // Resetting context._sent for legacy support of Babel's
  26239. // function.sent implementation.
  26240. this.sent = this._sent = undefined;
  26241. this.done = false;
  26242. this.delegate = null;
  26243. this.method = "next";
  26244. this.arg = undefined;
  26245. this.tryEntries.forEach(resetTryEntry);
  26246. if (!skipTempReset) {
  26247. for (var name in this) {
  26248. // Not sure about the optimal order of these conditions:
  26249. if (name.charAt(0) === "t" &&
  26250. hasOwn.call(this, name) &&
  26251. !isNaN(+name.slice(1))) {
  26252. this[name] = undefined;
  26253. }
  26254. }
  26255. }
  26256. },
  26257. stop: function() {
  26258. this.done = true;
  26259. var rootEntry = this.tryEntries[0];
  26260. var rootRecord = rootEntry.completion;
  26261. if (rootRecord.type === "throw") {
  26262. throw rootRecord.arg;
  26263. }
  26264. return this.rval;
  26265. },
  26266. dispatchException: function(exception) {
  26267. if (this.done) {
  26268. throw exception;
  26269. }
  26270. var context = this;
  26271. function handle(loc, caught) {
  26272. record.type = "throw";
  26273. record.arg = exception;
  26274. context.next = loc;
  26275. if (caught) {
  26276. // If the dispatched exception was caught by a catch block,
  26277. // then let that catch block handle the exception normally.
  26278. context.method = "next";
  26279. context.arg = undefined;
  26280. }
  26281. return !! caught;
  26282. }
  26283. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  26284. var entry = this.tryEntries[i];
  26285. var record = entry.completion;
  26286. if (entry.tryLoc === "root") {
  26287. // Exception thrown outside of any try block that could handle
  26288. // it, so set the completion value of the entire function to
  26289. // throw the exception.
  26290. return handle("end");
  26291. }
  26292. if (entry.tryLoc <= this.prev) {
  26293. var hasCatch = hasOwn.call(entry, "catchLoc");
  26294. var hasFinally = hasOwn.call(entry, "finallyLoc");
  26295. if (hasCatch && hasFinally) {
  26296. if (this.prev < entry.catchLoc) {
  26297. return handle(entry.catchLoc, true);
  26298. } else if (this.prev < entry.finallyLoc) {
  26299. return handle(entry.finallyLoc);
  26300. }
  26301. } else if (hasCatch) {
  26302. if (this.prev < entry.catchLoc) {
  26303. return handle(entry.catchLoc, true);
  26304. }
  26305. } else if (hasFinally) {
  26306. if (this.prev < entry.finallyLoc) {
  26307. return handle(entry.finallyLoc);
  26308. }
  26309. } else {
  26310. throw new Error("try statement without catch or finally");
  26311. }
  26312. }
  26313. }
  26314. },
  26315. abrupt: function(type, arg) {
  26316. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  26317. var entry = this.tryEntries[i];
  26318. if (entry.tryLoc <= this.prev &&
  26319. hasOwn.call(entry, "finallyLoc") &&
  26320. this.prev < entry.finallyLoc) {
  26321. var finallyEntry = entry;
  26322. break;
  26323. }
  26324. }
  26325. if (finallyEntry &&
  26326. (type === "break" ||
  26327. type === "continue") &&
  26328. finallyEntry.tryLoc <= arg &&
  26329. arg <= finallyEntry.finallyLoc) {
  26330. // Ignore the finally entry if control is not jumping to a
  26331. // location outside the try/catch block.
  26332. finallyEntry = null;
  26333. }
  26334. var record = finallyEntry ? finallyEntry.completion : {};
  26335. record.type = type;
  26336. record.arg = arg;
  26337. if (finallyEntry) {
  26338. this.method = "next";
  26339. this.next = finallyEntry.finallyLoc;
  26340. return ContinueSentinel;
  26341. }
  26342. return this.complete(record);
  26343. },
  26344. complete: function(record, afterLoc) {
  26345. if (record.type === "throw") {
  26346. throw record.arg;
  26347. }
  26348. if (record.type === "break" ||
  26349. record.type === "continue") {
  26350. this.next = record.arg;
  26351. } else if (record.type === "return") {
  26352. this.rval = this.arg = record.arg;
  26353. this.method = "return";
  26354. this.next = "end";
  26355. } else if (record.type === "normal" && afterLoc) {
  26356. this.next = afterLoc;
  26357. }
  26358. return ContinueSentinel;
  26359. },
  26360. finish: function(finallyLoc) {
  26361. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  26362. var entry = this.tryEntries[i];
  26363. if (entry.finallyLoc === finallyLoc) {
  26364. this.complete(entry.completion, entry.afterLoc);
  26365. resetTryEntry(entry);
  26366. return ContinueSentinel;
  26367. }
  26368. }
  26369. },
  26370. "catch": function(tryLoc) {
  26371. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  26372. var entry = this.tryEntries[i];
  26373. if (entry.tryLoc === tryLoc) {
  26374. var record = entry.completion;
  26375. if (record.type === "throw") {
  26376. var thrown = record.arg;
  26377. resetTryEntry(entry);
  26378. }
  26379. return thrown;
  26380. }
  26381. }
  26382. // The context.catch method must only be called with a location
  26383. // argument that corresponds to a known catch block.
  26384. throw new Error("illegal catch attempt");
  26385. },
  26386. delegateYield: function(iterable, resultName, nextLoc) {
  26387. this.delegate = {
  26388. iterator: values(iterable),
  26389. resultName: resultName,
  26390. nextLoc: nextLoc
  26391. };
  26392. if (this.method === "next") {
  26393. // Deliberately forget the last sent value so that we don't
  26394. // accidentally pass it on to the delegate.
  26395. this.arg = undefined;
  26396. }
  26397. return ContinueSentinel;
  26398. }
  26399. };
  26400. // Regardless of whether this script is executing as a CommonJS module
  26401. // or not, return the runtime object so that we can declare the variable
  26402. // regeneratorRuntime in the outer scope, which allows this module to be
  26403. // injected easily by `bin/regenerator --include-runtime script.js`.
  26404. return exports;
  26405. }(
  26406. // If this script is executing as a CommonJS module, use module.exports
  26407. // as the regeneratorRuntime namespace. Otherwise create a new empty
  26408. // object. Either way, the resulting object will be used to initialize
  26409. // the regeneratorRuntime variable at the top of this file.
  26410. true ? module.exports : undefined
  26411. ));
  26412. try {
  26413. regeneratorRuntime = runtime;
  26414. } catch (accidentalStrictMode) {
  26415. // This module should not be running in strict mode, so the above
  26416. // assignment should always work unless something is misconfigured. Just
  26417. // in case runtime.js accidentally runs in strict mode, we can escape
  26418. // strict mode using a global Function call. This could conceivably fail
  26419. // if a Content Security Policy forbids using Function, but in that case
  26420. // the proper solution is to fix the accidental strict mode problem. If
  26421. // you've misconfigured your bundler to force strict mode and applied a
  26422. // CSP to forbid Function, and you're not willing to fix either of those
  26423. // problems, please detail your unique predicament in a GitHub issue.
  26424. Function("r", "regeneratorRuntime = r")(runtime);
  26425. }
  26426. /***/ })
  26427. }]);
  26428. //# sourceMappingURL=vendors~main.685d1cf2ece1ed4ebb99.js.map