vendors~main.dd0a03a355e98d9beb77.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161
  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. moveSel(cm, -1)
  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 moveSel(cm, dir) {
  11794. var newRanges = [], ranges = cm.listSelections(), primary = 0
  11795. for (var i = 0; i < ranges.length; i++) {
  11796. var range = ranges[i]
  11797. if (range.head == cm.getCursor()) primary = i
  11798. var pos = range.head.ch || dir > 0 ? {line: range.head.line, ch: range.head.ch + dir} : {line: range.head.line - 1}
  11799. newRanges.push({anchor: pos, head: pos})
  11800. }
  11801. cm.setSelections(newRanges, primary)
  11802. }
  11803. function contractSelection(sel) {
  11804. var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
  11805. return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
  11806. head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
  11807. }
  11808. function handleChar(cm, ch) {
  11809. var conf = getConfig(cm);
  11810. if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
  11811. var pairs = getOption(conf, "pairs");
  11812. var pos = pairs.indexOf(ch);
  11813. if (pos == -1) return CodeMirror.Pass;
  11814. var closeBefore = getOption(conf,"closeBefore");
  11815. var triples = getOption(conf, "triples");
  11816. var identical = pairs.charAt(pos + 1) == ch;
  11817. var ranges = cm.listSelections();
  11818. var opening = pos % 2 == 0;
  11819. var type;
  11820. for (var i = 0; i < ranges.length; i++) {
  11821. var range = ranges[i], cur = range.head, curType;
  11822. var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
  11823. if (opening && !range.empty()) {
  11824. curType = "surround";
  11825. } else if ((identical || !opening) && next == ch) {
  11826. if (identical && stringStartsAfter(cm, cur))
  11827. curType = "both";
  11828. else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
  11829. curType = "skipThree";
  11830. else
  11831. curType = "skip";
  11832. } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
  11833. cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) {
  11834. if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass;
  11835. curType = "addFour";
  11836. } else if (identical) {
  11837. var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur)
  11838. if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";
  11839. else return CodeMirror.Pass;
  11840. } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) {
  11841. curType = "both";
  11842. } else {
  11843. return CodeMirror.Pass;
  11844. }
  11845. if (!type) type = curType;
  11846. else if (type != curType) return CodeMirror.Pass;
  11847. }
  11848. var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
  11849. var right = pos % 2 ? ch : pairs.charAt(pos + 1);
  11850. cm.operation(function() {
  11851. if (type == "skip") {
  11852. moveSel(cm, 1)
  11853. } else if (type == "skipThree") {
  11854. moveSel(cm, 3)
  11855. } else if (type == "surround") {
  11856. var sels = cm.getSelections();
  11857. for (var i = 0; i < sels.length; i++)
  11858. sels[i] = left + sels[i] + right;
  11859. cm.replaceSelections(sels, "around");
  11860. sels = cm.listSelections().slice();
  11861. for (var i = 0; i < sels.length; i++)
  11862. sels[i] = contractSelection(sels[i]);
  11863. cm.setSelections(sels);
  11864. } else if (type == "both") {
  11865. cm.replaceSelection(left + right, null);
  11866. cm.triggerElectric(left + right);
  11867. moveSel(cm, -1)
  11868. } else if (type == "addFour") {
  11869. cm.replaceSelection(left + left + left + left, "before");
  11870. moveSel(cm, 1)
  11871. }
  11872. });
  11873. }
  11874. function charsAround(cm, pos) {
  11875. var str = cm.getRange(Pos(pos.line, pos.ch - 1),
  11876. Pos(pos.line, pos.ch + 1));
  11877. return str.length == 2 ? str : null;
  11878. }
  11879. function stringStartsAfter(cm, pos) {
  11880. var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
  11881. return /\bstring/.test(token.type) && token.start == pos.ch &&
  11882. (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos)))
  11883. }
  11884. });
  11885. /***/ }),
  11886. /***/ "./node_modules/codemirror/addon/edit/matchbrackets.js":
  11887. /*!*************************************************************!*\
  11888. !*** ./node_modules/codemirror/addon/edit/matchbrackets.js ***!
  11889. \*************************************************************/
  11890. /*! no static exports found */
  11891. /***/ (function(module, exports, __webpack_require__) {
  11892. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11893. // Distributed under an MIT license: https://codemirror.net/LICENSE
  11894. (function(mod) {
  11895. if (true) // CommonJS
  11896. mod(__webpack_require__(/*! ../../lib/codemirror */ "./node_modules/codemirror/lib/codemirror.js"));
  11897. else {}
  11898. })(function(CodeMirror) {
  11899. var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
  11900. (document.documentMode == null || document.documentMode < 8);
  11901. var Pos = CodeMirror.Pos;
  11902. var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<", "<": ">>", ">": "<<"};
  11903. function bracketRegex(config) {
  11904. return config && config.bracketRegex || /[(){}[\]]/
  11905. }
  11906. function findMatchingBracket(cm, where, config) {
  11907. var line = cm.getLineHandle(where.line), pos = where.ch - 1;
  11908. var afterCursor = config && config.afterCursor
  11909. if (afterCursor == null)
  11910. afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)
  11911. var re = bracketRegex(config)
  11912. // A cursor is defined as between two characters, but in in vim command mode
  11913. // (i.e. not insert mode), the cursor is visually represented as a
  11914. // highlighted box on top of the 2nd character. Otherwise, we allow matches
  11915. // from before or after the cursor.
  11916. var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) ||
  11917. re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)];
  11918. if (!match) return null;
  11919. var dir = match.charAt(1) == ">" ? 1 : -1;
  11920. if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;
  11921. var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
  11922. var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style, config);
  11923. if (found == null) return null;
  11924. return {from: Pos(where.line, pos), to: found && found.pos,
  11925. match: found && found.ch == match.charAt(0), forward: dir > 0};
  11926. }
  11927. // bracketRegex is used to specify which type of bracket to scan
  11928. // should be a regexp, e.g. /[[\]]/
  11929. //
  11930. // Note: If "where" is on an open bracket, then this bracket is ignored.
  11931. //
  11932. // Returns false when no bracket was found, null when it reached
  11933. // maxScanLines and gave up
  11934. function scanForBracket(cm, where, dir, style, config) {
  11935. var maxScanLen = (config && config.maxScanLineLength) || 10000;
  11936. var maxScanLines = (config && config.maxScanLines) || 1000;
  11937. var stack = [];
  11938. var re = bracketRegex(config)
  11939. var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
  11940. : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
  11941. for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
  11942. var line = cm.getLine(lineNo);
  11943. if (!line) continue;
  11944. var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
  11945. if (line.length > maxScanLen) continue;
  11946. if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
  11947. for (; pos != end; pos += dir) {
  11948. var ch = line.charAt(pos);
  11949. if (re.test(ch) && (style === undefined ||
  11950. (cm.getTokenTypeAt(Pos(lineNo, pos + 1)) || "") == (style || ""))) {
  11951. var match = matching[ch];
  11952. if (match && (match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
  11953. else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
  11954. else stack.pop();
  11955. }
  11956. }
  11957. }
  11958. return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
  11959. }
  11960. function matchBrackets(cm, autoclear, config) {
  11961. // Disable brace matching in long lines, since it'll cause hugely slow updates
  11962. var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000,
  11963. highlightNonMatching = config && config.highlightNonMatching;
  11964. var marks = [], ranges = cm.listSelections();
  11965. for (var i = 0; i < ranges.length; i++) {
  11966. var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
  11967. if (match && (match.match || highlightNonMatching !== false) && cm.getLine(match.from.line).length <= maxHighlightLen) {
  11968. var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
  11969. marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
  11970. if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
  11971. marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
  11972. }
  11973. }
  11974. if (marks.length) {
  11975. // Kludge to work around the IE bug from issue #1193, where text
  11976. // input stops going to the textarea whenever this fires.
  11977. if (ie_lt8 && cm.state.focused) cm.focus();
  11978. var clear = function() {
  11979. cm.operation(function() {
  11980. for (var i = 0; i < marks.length; i++) marks[i].clear();
  11981. });
  11982. };
  11983. if (autoclear) setTimeout(clear, 800);
  11984. else return clear;
  11985. }
  11986. }
  11987. function doMatchBrackets(cm) {
  11988. cm.operation(function() {
  11989. if (cm.state.matchBrackets.currentlyHighlighted) {
  11990. cm.state.matchBrackets.currentlyHighlighted();
  11991. cm.state.matchBrackets.currentlyHighlighted = null;
  11992. }
  11993. cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
  11994. });
  11995. }
  11996. function clearHighlighted(cm) {
  11997. if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
  11998. cm.state.matchBrackets.currentlyHighlighted();
  11999. cm.state.matchBrackets.currentlyHighlighted = null;
  12000. }
  12001. }
  12002. CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
  12003. if (old && old != CodeMirror.Init) {
  12004. cm.off("cursorActivity", doMatchBrackets);
  12005. cm.off("focus", doMatchBrackets)
  12006. cm.off("blur", clearHighlighted)
  12007. clearHighlighted(cm);
  12008. }
  12009. if (val) {
  12010. cm.state.matchBrackets = typeof val == "object" ? val : {};
  12011. cm.on("cursorActivity", doMatchBrackets);
  12012. cm.on("focus", doMatchBrackets)
  12013. cm.on("blur", clearHighlighted)
  12014. }
  12015. });
  12016. CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
  12017. CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){
  12018. // Backwards-compatibility kludge
  12019. if (oldConfig || typeof config == "boolean") {
  12020. if (!oldConfig) {
  12021. config = config ? {strict: true} : null
  12022. } else {
  12023. oldConfig.strict = config
  12024. config = oldConfig
  12025. }
  12026. }
  12027. return findMatchingBracket(this, pos, config)
  12028. });
  12029. CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
  12030. return scanForBracket(this, pos, dir, style, config);
  12031. });
  12032. });
  12033. /***/ }),
  12034. /***/ "./node_modules/codemirror/addon/selection/active-line.js":
  12035. /*!****************************************************************!*\
  12036. !*** ./node_modules/codemirror/addon/selection/active-line.js ***!
  12037. \****************************************************************/
  12038. /*! no static exports found */
  12039. /***/ (function(module, exports, __webpack_require__) {
  12040. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  12041. // Distributed under an MIT license: https://codemirror.net/LICENSE
  12042. (function(mod) {
  12043. if (true) // CommonJS
  12044. mod(__webpack_require__(/*! ../../lib/codemirror */ "./node_modules/codemirror/lib/codemirror.js"));
  12045. else {}
  12046. })(function(CodeMirror) {
  12047. "use strict";
  12048. var WRAP_CLASS = "CodeMirror-activeline";
  12049. var BACK_CLASS = "CodeMirror-activeline-background";
  12050. var GUTT_CLASS = "CodeMirror-activeline-gutter";
  12051. CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
  12052. var prev = old == CodeMirror.Init ? false : old;
  12053. if (val == prev) return
  12054. if (prev) {
  12055. cm.off("beforeSelectionChange", selectionChange);
  12056. clearActiveLines(cm);
  12057. delete cm.state.activeLines;
  12058. }
  12059. if (val) {
  12060. cm.state.activeLines = [];
  12061. updateActiveLines(cm, cm.listSelections());
  12062. cm.on("beforeSelectionChange", selectionChange);
  12063. }
  12064. });
  12065. function clearActiveLines(cm) {
  12066. for (var i = 0; i < cm.state.activeLines.length; i++) {
  12067. cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
  12068. cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
  12069. cm.removeLineClass(cm.state.activeLines[i], "gutter", GUTT_CLASS);
  12070. }
  12071. }
  12072. function sameArray(a, b) {
  12073. if (a.length != b.length) return false;
  12074. for (var i = 0; i < a.length; i++)
  12075. if (a[i] != b[i]) return false;
  12076. return true;
  12077. }
  12078. function updateActiveLines(cm, ranges) {
  12079. var active = [];
  12080. for (var i = 0; i < ranges.length; i++) {
  12081. var range = ranges[i];
  12082. var option = cm.getOption("styleActiveLine");
  12083. if (typeof option == "object" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())
  12084. continue
  12085. var line = cm.getLineHandleVisualStart(range.head.line);
  12086. if (active[active.length - 1] != line) active.push(line);
  12087. }
  12088. if (sameArray(cm.state.activeLines, active)) return;
  12089. cm.operation(function() {
  12090. clearActiveLines(cm);
  12091. for (var i = 0; i < active.length; i++) {
  12092. cm.addLineClass(active[i], "wrap", WRAP_CLASS);
  12093. cm.addLineClass(active[i], "background", BACK_CLASS);
  12094. cm.addLineClass(active[i], "gutter", GUTT_CLASS);
  12095. }
  12096. cm.state.activeLines = active;
  12097. });
  12098. }
  12099. function selectionChange(cm, sel) {
  12100. updateActiveLines(cm, sel.ranges);
  12101. }
  12102. });
  12103. /***/ }),
  12104. /***/ "./node_modules/codemirror/lib/codemirror.js":
  12105. /*!***************************************************!*\
  12106. !*** ./node_modules/codemirror/lib/codemirror.js ***!
  12107. \***************************************************/
  12108. /*! no static exports found */
  12109. /***/ (function(module, exports, __webpack_require__) {
  12110. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  12111. // Distributed under an MIT license: https://codemirror.net/LICENSE
  12112. // This is CodeMirror (https://codemirror.net), a code editor
  12113. // implemented in JavaScript on top of the browser's DOM.
  12114. //
  12115. // You can find some technical background for some of the code below
  12116. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  12117. (function (global, factory) {
  12118. true ? module.exports = factory() :
  12119. undefined;
  12120. }(this, (function () { 'use strict';
  12121. // Kludges for bugs and behavior differences that can't be feature
  12122. // detected are enabled based on userAgent etc sniffing.
  12123. var userAgent = navigator.userAgent;
  12124. var platform = navigator.platform;
  12125. var gecko = /gecko\/\d/i.test(userAgent);
  12126. var ie_upto10 = /MSIE \d/.test(userAgent);
  12127. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  12128. var edge = /Edge\/(\d+)/.exec(userAgent);
  12129. var ie = ie_upto10 || ie_11up || edge;
  12130. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  12131. var webkit = !edge && /WebKit\//.test(userAgent);
  12132. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  12133. var chrome = !edge && /Chrome\//.test(userAgent);
  12134. var presto = /Opera\//.test(userAgent);
  12135. var safari = /Apple Computer/.test(navigator.vendor);
  12136. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  12137. var phantom = /PhantomJS/.test(userAgent);
  12138. var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
  12139. var android = /Android/.test(userAgent);
  12140. // This is woefully incomplete. Suggestions for alternative methods welcome.
  12141. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  12142. var mac = ios || /Mac/.test(platform);
  12143. var chromeOS = /\bCrOS\b/.test(userAgent);
  12144. var windows = /win/i.test(platform);
  12145. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  12146. if (presto_version) { presto_version = Number(presto_version[1]); }
  12147. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  12148. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  12149. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  12150. var captureRightClick = gecko || (ie && ie_version >= 9);
  12151. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  12152. var rmClass = function(node, cls) {
  12153. var current = node.className;
  12154. var match = classTest(cls).exec(current);
  12155. if (match) {
  12156. var after = current.slice(match.index + match[0].length);
  12157. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  12158. }
  12159. };
  12160. function removeChildren(e) {
  12161. for (var count = e.childNodes.length; count > 0; --count)
  12162. { e.removeChild(e.firstChild); }
  12163. return e
  12164. }
  12165. function removeChildrenAndAdd(parent, e) {
  12166. return removeChildren(parent).appendChild(e)
  12167. }
  12168. function elt(tag, content, className, style) {
  12169. var e = document.createElement(tag);
  12170. if (className) { e.className = className; }
  12171. if (style) { e.style.cssText = style; }
  12172. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  12173. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  12174. return e
  12175. }
  12176. // wrapper for elt, which removes the elt from the accessibility tree
  12177. function eltP(tag, content, className, style) {
  12178. var e = elt(tag, content, className, style);
  12179. e.setAttribute("role", "presentation");
  12180. return e
  12181. }
  12182. var range;
  12183. if (document.createRange) { range = function(node, start, end, endNode) {
  12184. var r = document.createRange();
  12185. r.setEnd(endNode || node, end);
  12186. r.setStart(node, start);
  12187. return r
  12188. }; }
  12189. else { range = function(node, start, end) {
  12190. var r = document.body.createTextRange();
  12191. try { r.moveToElementText(node.parentNode); }
  12192. catch(e) { return r }
  12193. r.collapse(true);
  12194. r.moveEnd("character", end);
  12195. r.moveStart("character", start);
  12196. return r
  12197. }; }
  12198. function contains(parent, child) {
  12199. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  12200. { child = child.parentNode; }
  12201. if (parent.contains)
  12202. { return parent.contains(child) }
  12203. do {
  12204. if (child.nodeType == 11) { child = child.host; }
  12205. if (child == parent) { return true }
  12206. } while (child = child.parentNode)
  12207. }
  12208. function activeElt() {
  12209. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  12210. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  12211. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  12212. var activeElement;
  12213. try {
  12214. activeElement = document.activeElement;
  12215. } catch(e) {
  12216. activeElement = document.body || null;
  12217. }
  12218. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  12219. { activeElement = activeElement.shadowRoot.activeElement; }
  12220. return activeElement
  12221. }
  12222. function addClass(node, cls) {
  12223. var current = node.className;
  12224. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  12225. }
  12226. function joinClasses(a, b) {
  12227. var as = a.split(" ");
  12228. for (var i = 0; i < as.length; i++)
  12229. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  12230. return b
  12231. }
  12232. var selectInput = function(node) { node.select(); };
  12233. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  12234. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  12235. else if (ie) // Suppress mysterious IE10 errors
  12236. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  12237. function bind(f) {
  12238. var args = Array.prototype.slice.call(arguments, 1);
  12239. return function(){return f.apply(null, args)}
  12240. }
  12241. function copyObj(obj, target, overwrite) {
  12242. if (!target) { target = {}; }
  12243. for (var prop in obj)
  12244. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  12245. { target[prop] = obj[prop]; } }
  12246. return target
  12247. }
  12248. // Counts the column offset in a string, taking tabs into account.
  12249. // Used mostly to find indentation.
  12250. function countColumn(string, end, tabSize, startIndex, startValue) {
  12251. if (end == null) {
  12252. end = string.search(/[^\s\u00a0]/);
  12253. if (end == -1) { end = string.length; }
  12254. }
  12255. for (var i = startIndex || 0, n = startValue || 0;;) {
  12256. var nextTab = string.indexOf("\t", i);
  12257. if (nextTab < 0 || nextTab >= end)
  12258. { return n + (end - i) }
  12259. n += nextTab - i;
  12260. n += tabSize - (n % tabSize);
  12261. i = nextTab + 1;
  12262. }
  12263. }
  12264. var Delayed = function() {
  12265. this.id = null;
  12266. this.f = null;
  12267. this.time = 0;
  12268. this.handler = bind(this.onTimeout, this);
  12269. };
  12270. Delayed.prototype.onTimeout = function (self) {
  12271. self.id = 0;
  12272. if (self.time <= +new Date) {
  12273. self.f();
  12274. } else {
  12275. setTimeout(self.handler, self.time - +new Date);
  12276. }
  12277. };
  12278. Delayed.prototype.set = function (ms, f) {
  12279. this.f = f;
  12280. var time = +new Date + ms;
  12281. if (!this.id || time < this.time) {
  12282. clearTimeout(this.id);
  12283. this.id = setTimeout(this.handler, ms);
  12284. this.time = time;
  12285. }
  12286. };
  12287. function indexOf(array, elt) {
  12288. for (var i = 0; i < array.length; ++i)
  12289. { if (array[i] == elt) { return i } }
  12290. return -1
  12291. }
  12292. // Number of pixels added to scroller and sizer to hide scrollbar
  12293. var scrollerGap = 50;
  12294. // Returned or thrown by various protocols to signal 'I'm not
  12295. // handling this'.
  12296. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  12297. // Reused option objects for setSelection & friends
  12298. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  12299. // The inverse of countColumn -- find the offset that corresponds to
  12300. // a particular column.
  12301. function findColumn(string, goal, tabSize) {
  12302. for (var pos = 0, col = 0;;) {
  12303. var nextTab = string.indexOf("\t", pos);
  12304. if (nextTab == -1) { nextTab = string.length; }
  12305. var skipped = nextTab - pos;
  12306. if (nextTab == string.length || col + skipped >= goal)
  12307. { return pos + Math.min(skipped, goal - col) }
  12308. col += nextTab - pos;
  12309. col += tabSize - (col % tabSize);
  12310. pos = nextTab + 1;
  12311. if (col >= goal) { return pos }
  12312. }
  12313. }
  12314. var spaceStrs = [""];
  12315. function spaceStr(n) {
  12316. while (spaceStrs.length <= n)
  12317. { spaceStrs.push(lst(spaceStrs) + " "); }
  12318. return spaceStrs[n]
  12319. }
  12320. function lst(arr) { return arr[arr.length-1] }
  12321. function map(array, f) {
  12322. var out = [];
  12323. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  12324. return out
  12325. }
  12326. function insertSorted(array, value, score) {
  12327. var pos = 0, priority = score(value);
  12328. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  12329. array.splice(pos, 0, value);
  12330. }
  12331. function nothing() {}
  12332. function createObj(base, props) {
  12333. var inst;
  12334. if (Object.create) {
  12335. inst = Object.create(base);
  12336. } else {
  12337. nothing.prototype = base;
  12338. inst = new nothing();
  12339. }
  12340. if (props) { copyObj(props, inst); }
  12341. return inst
  12342. }
  12343. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  12344. function isWordCharBasic(ch) {
  12345. return /\w/.test(ch) || ch > "\x80" &&
  12346. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  12347. }
  12348. function isWordChar(ch, helper) {
  12349. if (!helper) { return isWordCharBasic(ch) }
  12350. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  12351. return helper.test(ch)
  12352. }
  12353. function isEmpty(obj) {
  12354. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  12355. return true
  12356. }
  12357. // Extending unicode characters. A series of a non-extending char +
  12358. // any number of extending chars is treated as a single unit as far
  12359. // as editing and measuring is concerned. This is not fully correct,
  12360. // since some scripts/fonts/browsers also treat other configurations
  12361. // of code points as a group.
  12362. 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]/;
  12363. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  12364. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  12365. function skipExtendingChars(str, pos, dir) {
  12366. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  12367. return pos
  12368. }
  12369. // Returns the value from the range [`from`; `to`] that satisfies
  12370. // `pred` and is closest to `from`. Assumes that at least `to`
  12371. // satisfies `pred`. Supports `from` being greater than `to`.
  12372. function findFirst(pred, from, to) {
  12373. // At any point we are certain `to` satisfies `pred`, don't know
  12374. // whether `from` does.
  12375. var dir = from > to ? -1 : 1;
  12376. for (;;) {
  12377. if (from == to) { return from }
  12378. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  12379. if (mid == from) { return pred(mid) ? from : to }
  12380. if (pred(mid)) { to = mid; }
  12381. else { from = mid + dir; }
  12382. }
  12383. }
  12384. // BIDI HELPERS
  12385. function iterateBidiSections(order, from, to, f) {
  12386. if (!order) { return f(from, to, "ltr", 0) }
  12387. var found = false;
  12388. for (var i = 0; i < order.length; ++i) {
  12389. var part = order[i];
  12390. if (part.from < to && part.to > from || from == to && part.to == from) {
  12391. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  12392. found = true;
  12393. }
  12394. }
  12395. if (!found) { f(from, to, "ltr"); }
  12396. }
  12397. var bidiOther = null;
  12398. function getBidiPartAt(order, ch, sticky) {
  12399. var found;
  12400. bidiOther = null;
  12401. for (var i = 0; i < order.length; ++i) {
  12402. var cur = order[i];
  12403. if (cur.from < ch && cur.to > ch) { return i }
  12404. if (cur.to == ch) {
  12405. if (cur.from != cur.to && sticky == "before") { found = i; }
  12406. else { bidiOther = i; }
  12407. }
  12408. if (cur.from == ch) {
  12409. if (cur.from != cur.to && sticky != "before") { found = i; }
  12410. else { bidiOther = i; }
  12411. }
  12412. }
  12413. return found != null ? found : bidiOther
  12414. }
  12415. // Bidirectional ordering algorithm
  12416. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  12417. // that this (partially) implements.
  12418. // One-char codes used for character types:
  12419. // L (L): Left-to-Right
  12420. // R (R): Right-to-Left
  12421. // r (AL): Right-to-Left Arabic
  12422. // 1 (EN): European Number
  12423. // + (ES): European Number Separator
  12424. // % (ET): European Number Terminator
  12425. // n (AN): Arabic Number
  12426. // , (CS): Common Number Separator
  12427. // m (NSM): Non-Spacing Mark
  12428. // b (BN): Boundary Neutral
  12429. // s (B): Paragraph Separator
  12430. // t (S): Segment Separator
  12431. // w (WS): Whitespace
  12432. // N (ON): Other Neutrals
  12433. // Returns null if characters are ordered as they appear
  12434. // (left-to-right), or an array of sections ({from, to, level}
  12435. // objects) in the order in which they occur visually.
  12436. var bidiOrdering = (function() {
  12437. // Character types for codepoints 0 to 0xff
  12438. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  12439. // Character types for codepoints 0x600 to 0x6f9
  12440. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  12441. function charType(code) {
  12442. if (code <= 0xf7) { return lowTypes.charAt(code) }
  12443. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  12444. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  12445. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  12446. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  12447. else if (code == 0x200c) { return "b" }
  12448. else { return "L" }
  12449. }
  12450. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  12451. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  12452. function BidiSpan(level, from, to) {
  12453. this.level = level;
  12454. this.from = from; this.to = to;
  12455. }
  12456. return function(str, direction) {
  12457. var outerType = direction == "ltr" ? "L" : "R";
  12458. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  12459. var len = str.length, types = [];
  12460. for (var i = 0; i < len; ++i)
  12461. { types.push(charType(str.charCodeAt(i))); }
  12462. // W1. Examine each non-spacing mark (NSM) in the level run, and
  12463. // change the type of the NSM to the type of the previous
  12464. // character. If the NSM is at the start of the level run, it will
  12465. // get the type of sor.
  12466. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  12467. var type = types[i$1];
  12468. if (type == "m") { types[i$1] = prev; }
  12469. else { prev = type; }
  12470. }
  12471. // W2. Search backwards from each instance of a European number
  12472. // until the first strong type (R, L, AL, or sor) is found. If an
  12473. // AL is found, change the type of the European number to Arabic
  12474. // number.
  12475. // W3. Change all ALs to R.
  12476. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  12477. var type$1 = types[i$2];
  12478. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  12479. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  12480. }
  12481. // W4. A single European separator between two European numbers
  12482. // changes to a European number. A single common separator between
  12483. // two numbers of the same type changes to that type.
  12484. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  12485. var type$2 = types[i$3];
  12486. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  12487. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  12488. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  12489. prev$1 = type$2;
  12490. }
  12491. // W5. A sequence of European terminators adjacent to European
  12492. // numbers changes to all European numbers.
  12493. // W6. Otherwise, separators and terminators change to Other
  12494. // Neutral.
  12495. for (var i$4 = 0; i$4 < len; ++i$4) {
  12496. var type$3 = types[i$4];
  12497. if (type$3 == ",") { types[i$4] = "N"; }
  12498. else if (type$3 == "%") {
  12499. var end = (void 0);
  12500. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  12501. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  12502. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  12503. i$4 = end - 1;
  12504. }
  12505. }
  12506. // W7. Search backwards from each instance of a European number
  12507. // until the first strong type (R, L, or sor) is found. If an L is
  12508. // found, then change the type of the European number to L.
  12509. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  12510. var type$4 = types[i$5];
  12511. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  12512. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  12513. }
  12514. // N1. A sequence of neutrals takes the direction of the
  12515. // surrounding strong text if the text on both sides has the same
  12516. // direction. European and Arabic numbers act as if they were R in
  12517. // terms of their influence on neutrals. Start-of-level-run (sor)
  12518. // and end-of-level-run (eor) are used at level run boundaries.
  12519. // N2. Any remaining neutrals take the embedding direction.
  12520. for (var i$6 = 0; i$6 < len; ++i$6) {
  12521. if (isNeutral.test(types[i$6])) {
  12522. var end$1 = (void 0);
  12523. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  12524. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  12525. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  12526. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  12527. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  12528. i$6 = end$1 - 1;
  12529. }
  12530. }
  12531. // Here we depart from the documented algorithm, in order to avoid
  12532. // building up an actual levels array. Since there are only three
  12533. // levels (0, 1, 2) in an implementation that doesn't take
  12534. // explicit embedding into account, we can build up the order on
  12535. // the fly, without following the level-based algorithm.
  12536. var order = [], m;
  12537. for (var i$7 = 0; i$7 < len;) {
  12538. if (countsAsLeft.test(types[i$7])) {
  12539. var start = i$7;
  12540. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  12541. order.push(new BidiSpan(0, start, i$7));
  12542. } else {
  12543. var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  12544. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  12545. for (var j$2 = pos; j$2 < i$7;) {
  12546. if (countsAsNum.test(types[j$2])) {
  12547. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  12548. var nstart = j$2;
  12549. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  12550. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  12551. at += isRTL;
  12552. pos = j$2;
  12553. } else { ++j$2; }
  12554. }
  12555. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  12556. }
  12557. }
  12558. if (direction == "ltr") {
  12559. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  12560. order[0].from = m[0].length;
  12561. order.unshift(new BidiSpan(0, 0, m[0].length));
  12562. }
  12563. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  12564. lst(order).to -= m[0].length;
  12565. order.push(new BidiSpan(0, len - m[0].length, len));
  12566. }
  12567. }
  12568. return direction == "rtl" ? order.reverse() : order
  12569. }
  12570. })();
  12571. // Get the bidi ordering for the given line (and cache it). Returns
  12572. // false for lines that are fully left-to-right, and an array of
  12573. // BidiSpan objects otherwise.
  12574. function getOrder(line, direction) {
  12575. var order = line.order;
  12576. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  12577. return order
  12578. }
  12579. // EVENT HANDLING
  12580. // Lightweight event framework. on/off also work on DOM nodes,
  12581. // registering native DOM handlers.
  12582. var noHandlers = [];
  12583. var on = function(emitter, type, f) {
  12584. if (emitter.addEventListener) {
  12585. emitter.addEventListener(type, f, false);
  12586. } else if (emitter.attachEvent) {
  12587. emitter.attachEvent("on" + type, f);
  12588. } else {
  12589. var map = emitter._handlers || (emitter._handlers = {});
  12590. map[type] = (map[type] || noHandlers).concat(f);
  12591. }
  12592. };
  12593. function getHandlers(emitter, type) {
  12594. return emitter._handlers && emitter._handlers[type] || noHandlers
  12595. }
  12596. function off(emitter, type, f) {
  12597. if (emitter.removeEventListener) {
  12598. emitter.removeEventListener(type, f, false);
  12599. } else if (emitter.detachEvent) {
  12600. emitter.detachEvent("on" + type, f);
  12601. } else {
  12602. var map = emitter._handlers, arr = map && map[type];
  12603. if (arr) {
  12604. var index = indexOf(arr, f);
  12605. if (index > -1)
  12606. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  12607. }
  12608. }
  12609. }
  12610. function signal(emitter, type /*, values...*/) {
  12611. var handlers = getHandlers(emitter, type);
  12612. if (!handlers.length) { return }
  12613. var args = Array.prototype.slice.call(arguments, 2);
  12614. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  12615. }
  12616. // The DOM events that CodeMirror handles can be overridden by
  12617. // registering a (non-DOM) handler on the editor for the event name,
  12618. // and preventDefault-ing the event in that handler.
  12619. function signalDOMEvent(cm, e, override) {
  12620. if (typeof e == "string")
  12621. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  12622. signal(cm, override || e.type, cm, e);
  12623. return e_defaultPrevented(e) || e.codemirrorIgnore
  12624. }
  12625. function signalCursorActivity(cm) {
  12626. var arr = cm._handlers && cm._handlers.cursorActivity;
  12627. if (!arr) { return }
  12628. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  12629. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  12630. { set.push(arr[i]); } }
  12631. }
  12632. function hasHandler(emitter, type) {
  12633. return getHandlers(emitter, type).length > 0
  12634. }
  12635. // Add on and off methods to a constructor's prototype, to make
  12636. // registering events on such objects more convenient.
  12637. function eventMixin(ctor) {
  12638. ctor.prototype.on = function(type, f) {on(this, type, f);};
  12639. ctor.prototype.off = function(type, f) {off(this, type, f);};
  12640. }
  12641. // Due to the fact that we still support jurassic IE versions, some
  12642. // compatibility wrappers are needed.
  12643. function e_preventDefault(e) {
  12644. if (e.preventDefault) { e.preventDefault(); }
  12645. else { e.returnValue = false; }
  12646. }
  12647. function e_stopPropagation(e) {
  12648. if (e.stopPropagation) { e.stopPropagation(); }
  12649. else { e.cancelBubble = true; }
  12650. }
  12651. function e_defaultPrevented(e) {
  12652. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  12653. }
  12654. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  12655. function e_target(e) {return e.target || e.srcElement}
  12656. function e_button(e) {
  12657. var b = e.which;
  12658. if (b == null) {
  12659. if (e.button & 1) { b = 1; }
  12660. else if (e.button & 2) { b = 3; }
  12661. else if (e.button & 4) { b = 2; }
  12662. }
  12663. if (mac && e.ctrlKey && b == 1) { b = 3; }
  12664. return b
  12665. }
  12666. // Detect drag-and-drop
  12667. var dragAndDrop = function() {
  12668. // There is *some* kind of drag-and-drop support in IE6-8, but I
  12669. // couldn't get it to work yet.
  12670. if (ie && ie_version < 9) { return false }
  12671. var div = elt('div');
  12672. return "draggable" in div || "dragDrop" in div
  12673. }();
  12674. var zwspSupported;
  12675. function zeroWidthElement(measure) {
  12676. if (zwspSupported == null) {
  12677. var test = elt("span", "\u200b");
  12678. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  12679. if (measure.firstChild.offsetHeight != 0)
  12680. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  12681. }
  12682. var node = zwspSupported ? elt("span", "\u200b") :
  12683. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  12684. node.setAttribute("cm-text", "");
  12685. return node
  12686. }
  12687. // Feature-detect IE's crummy client rect reporting for bidi text
  12688. var badBidiRects;
  12689. function hasBadBidiRects(measure) {
  12690. if (badBidiRects != null) { return badBidiRects }
  12691. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  12692. var r0 = range(txt, 0, 1).getBoundingClientRect();
  12693. var r1 = range(txt, 1, 2).getBoundingClientRect();
  12694. removeChildren(measure);
  12695. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  12696. return badBidiRects = (r1.right - r0.right < 3)
  12697. }
  12698. // See if "".split is the broken IE version, if so, provide an
  12699. // alternative way to split lines.
  12700. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  12701. var pos = 0, result = [], l = string.length;
  12702. while (pos <= l) {
  12703. var nl = string.indexOf("\n", pos);
  12704. if (nl == -1) { nl = string.length; }
  12705. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  12706. var rt = line.indexOf("\r");
  12707. if (rt != -1) {
  12708. result.push(line.slice(0, rt));
  12709. pos += rt + 1;
  12710. } else {
  12711. result.push(line);
  12712. pos = nl + 1;
  12713. }
  12714. }
  12715. return result
  12716. } : function (string) { return string.split(/\r\n?|\n/); };
  12717. var hasSelection = window.getSelection ? function (te) {
  12718. try { return te.selectionStart != te.selectionEnd }
  12719. catch(e) { return false }
  12720. } : function (te) {
  12721. var range;
  12722. try {range = te.ownerDocument.selection.createRange();}
  12723. catch(e) {}
  12724. if (!range || range.parentElement() != te) { return false }
  12725. return range.compareEndPoints("StartToEnd", range) != 0
  12726. };
  12727. var hasCopyEvent = (function () {
  12728. var e = elt("div");
  12729. if ("oncopy" in e) { return true }
  12730. e.setAttribute("oncopy", "return;");
  12731. return typeof e.oncopy == "function"
  12732. })();
  12733. var badZoomedRects = null;
  12734. function hasBadZoomedRects(measure) {
  12735. if (badZoomedRects != null) { return badZoomedRects }
  12736. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  12737. var normal = node.getBoundingClientRect();
  12738. var fromRange = range(node, 0, 1).getBoundingClientRect();
  12739. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  12740. }
  12741. // Known modes, by name and by MIME
  12742. var modes = {}, mimeModes = {};
  12743. // Extra arguments are stored as the mode's dependencies, which is
  12744. // used by (legacy) mechanisms like loadmode.js to automatically
  12745. // load a mode. (Preferred mechanism is the require/define calls.)
  12746. function defineMode(name, mode) {
  12747. if (arguments.length > 2)
  12748. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  12749. modes[name] = mode;
  12750. }
  12751. function defineMIME(mime, spec) {
  12752. mimeModes[mime] = spec;
  12753. }
  12754. // Given a MIME type, a {name, ...options} config object, or a name
  12755. // string, return a mode config object.
  12756. function resolveMode(spec) {
  12757. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  12758. spec = mimeModes[spec];
  12759. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  12760. var found = mimeModes[spec.name];
  12761. if (typeof found == "string") { found = {name: found}; }
  12762. spec = createObj(found, spec);
  12763. spec.name = found.name;
  12764. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  12765. return resolveMode("application/xml")
  12766. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  12767. return resolveMode("application/json")
  12768. }
  12769. if (typeof spec == "string") { return {name: spec} }
  12770. else { return spec || {name: "null"} }
  12771. }
  12772. // Given a mode spec (anything that resolveMode accepts), find and
  12773. // initialize an actual mode object.
  12774. function getMode(options, spec) {
  12775. spec = resolveMode(spec);
  12776. var mfactory = modes[spec.name];
  12777. if (!mfactory) { return getMode(options, "text/plain") }
  12778. var modeObj = mfactory(options, spec);
  12779. if (modeExtensions.hasOwnProperty(spec.name)) {
  12780. var exts = modeExtensions[spec.name];
  12781. for (var prop in exts) {
  12782. if (!exts.hasOwnProperty(prop)) { continue }
  12783. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  12784. modeObj[prop] = exts[prop];
  12785. }
  12786. }
  12787. modeObj.name = spec.name;
  12788. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  12789. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  12790. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  12791. return modeObj
  12792. }
  12793. // This can be used to attach properties to mode objects from
  12794. // outside the actual mode definition.
  12795. var modeExtensions = {};
  12796. function extendMode(mode, properties) {
  12797. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  12798. copyObj(properties, exts);
  12799. }
  12800. function copyState(mode, state) {
  12801. if (state === true) { return state }
  12802. if (mode.copyState) { return mode.copyState(state) }
  12803. var nstate = {};
  12804. for (var n in state) {
  12805. var val = state[n];
  12806. if (val instanceof Array) { val = val.concat([]); }
  12807. nstate[n] = val;
  12808. }
  12809. return nstate
  12810. }
  12811. // Given a mode and a state (for that mode), find the inner mode and
  12812. // state at the position that the state refers to.
  12813. function innerMode(mode, state) {
  12814. var info;
  12815. while (mode.innerMode) {
  12816. info = mode.innerMode(state);
  12817. if (!info || info.mode == mode) { break }
  12818. state = info.state;
  12819. mode = info.mode;
  12820. }
  12821. return info || {mode: mode, state: state}
  12822. }
  12823. function startState(mode, a1, a2) {
  12824. return mode.startState ? mode.startState(a1, a2) : true
  12825. }
  12826. // STRING STREAM
  12827. // Fed to the mode parsers, provides helper functions to make
  12828. // parsers more succinct.
  12829. var StringStream = function(string, tabSize, lineOracle) {
  12830. this.pos = this.start = 0;
  12831. this.string = string;
  12832. this.tabSize = tabSize || 8;
  12833. this.lastColumnPos = this.lastColumnValue = 0;
  12834. this.lineStart = 0;
  12835. this.lineOracle = lineOracle;
  12836. };
  12837. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  12838. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  12839. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  12840. StringStream.prototype.next = function () {
  12841. if (this.pos < this.string.length)
  12842. { return this.string.charAt(this.pos++) }
  12843. };
  12844. StringStream.prototype.eat = function (match) {
  12845. var ch = this.string.charAt(this.pos);
  12846. var ok;
  12847. if (typeof match == "string") { ok = ch == match; }
  12848. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  12849. if (ok) {++this.pos; return ch}
  12850. };
  12851. StringStream.prototype.eatWhile = function (match) {
  12852. var start = this.pos;
  12853. while (this.eat(match)){}
  12854. return this.pos > start
  12855. };
  12856. StringStream.prototype.eatSpace = function () {
  12857. var start = this.pos;
  12858. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  12859. return this.pos > start
  12860. };
  12861. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  12862. StringStream.prototype.skipTo = function (ch) {
  12863. var found = this.string.indexOf(ch, this.pos);
  12864. if (found > -1) {this.pos = found; return true}
  12865. };
  12866. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  12867. StringStream.prototype.column = function () {
  12868. if (this.lastColumnPos < this.start) {
  12869. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  12870. this.lastColumnPos = this.start;
  12871. }
  12872. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  12873. };
  12874. StringStream.prototype.indentation = function () {
  12875. return countColumn(this.string, null, this.tabSize) -
  12876. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  12877. };
  12878. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  12879. if (typeof pattern == "string") {
  12880. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  12881. var substr = this.string.substr(this.pos, pattern.length);
  12882. if (cased(substr) == cased(pattern)) {
  12883. if (consume !== false) { this.pos += pattern.length; }
  12884. return true
  12885. }
  12886. } else {
  12887. var match = this.string.slice(this.pos).match(pattern);
  12888. if (match && match.index > 0) { return null }
  12889. if (match && consume !== false) { this.pos += match[0].length; }
  12890. return match
  12891. }
  12892. };
  12893. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  12894. StringStream.prototype.hideFirstChars = function (n, inner) {
  12895. this.lineStart += n;
  12896. try { return inner() }
  12897. finally { this.lineStart -= n; }
  12898. };
  12899. StringStream.prototype.lookAhead = function (n) {
  12900. var oracle = this.lineOracle;
  12901. return oracle && oracle.lookAhead(n)
  12902. };
  12903. StringStream.prototype.baseToken = function () {
  12904. var oracle = this.lineOracle;
  12905. return oracle && oracle.baseToken(this.pos)
  12906. };
  12907. // Find the line object corresponding to the given line number.
  12908. function getLine(doc, n) {
  12909. n -= doc.first;
  12910. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  12911. var chunk = doc;
  12912. while (!chunk.lines) {
  12913. for (var i = 0;; ++i) {
  12914. var child = chunk.children[i], sz = child.chunkSize();
  12915. if (n < sz) { chunk = child; break }
  12916. n -= sz;
  12917. }
  12918. }
  12919. return chunk.lines[n]
  12920. }
  12921. // Get the part of a document between two positions, as an array of
  12922. // strings.
  12923. function getBetween(doc, start, end) {
  12924. var out = [], n = start.line;
  12925. doc.iter(start.line, end.line + 1, function (line) {
  12926. var text = line.text;
  12927. if (n == end.line) { text = text.slice(0, end.ch); }
  12928. if (n == start.line) { text = text.slice(start.ch); }
  12929. out.push(text);
  12930. ++n;
  12931. });
  12932. return out
  12933. }
  12934. // Get the lines between from and to, as array of strings.
  12935. function getLines(doc, from, to) {
  12936. var out = [];
  12937. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  12938. return out
  12939. }
  12940. // Update the height of a line, propagating the height change
  12941. // upwards to parent nodes.
  12942. function updateLineHeight(line, height) {
  12943. var diff = height - line.height;
  12944. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  12945. }
  12946. // Given a line object, find its line number by walking up through
  12947. // its parent links.
  12948. function lineNo(line) {
  12949. if (line.parent == null) { return null }
  12950. var cur = line.parent, no = indexOf(cur.lines, line);
  12951. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  12952. for (var i = 0;; ++i) {
  12953. if (chunk.children[i] == cur) { break }
  12954. no += chunk.children[i].chunkSize();
  12955. }
  12956. }
  12957. return no + cur.first
  12958. }
  12959. // Find the line at the given vertical position, using the height
  12960. // information in the document tree.
  12961. function lineAtHeight(chunk, h) {
  12962. var n = chunk.first;
  12963. outer: do {
  12964. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  12965. var child = chunk.children[i$1], ch = child.height;
  12966. if (h < ch) { chunk = child; continue outer }
  12967. h -= ch;
  12968. n += child.chunkSize();
  12969. }
  12970. return n
  12971. } while (!chunk.lines)
  12972. var i = 0;
  12973. for (; i < chunk.lines.length; ++i) {
  12974. var line = chunk.lines[i], lh = line.height;
  12975. if (h < lh) { break }
  12976. h -= lh;
  12977. }
  12978. return n + i
  12979. }
  12980. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  12981. function lineNumberFor(options, i) {
  12982. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  12983. }
  12984. // A Pos instance represents a position within the text.
  12985. function Pos(line, ch, sticky) {
  12986. if ( sticky === void 0 ) sticky = null;
  12987. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  12988. this.line = line;
  12989. this.ch = ch;
  12990. this.sticky = sticky;
  12991. }
  12992. // Compare two positions, return 0 if they are the same, a negative
  12993. // number when a is less, and a positive number otherwise.
  12994. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  12995. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  12996. function copyPos(x) {return Pos(x.line, x.ch)}
  12997. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  12998. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  12999. // Most of the external API clips given positions to make sure they
  13000. // actually exist within the document.
  13001. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  13002. function clipPos(doc, pos) {
  13003. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  13004. var last = doc.first + doc.size - 1;
  13005. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  13006. return clipToLen(pos, getLine(doc, pos.line).text.length)
  13007. }
  13008. function clipToLen(pos, linelen) {
  13009. var ch = pos.ch;
  13010. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  13011. else if (ch < 0) { return Pos(pos.line, 0) }
  13012. else { return pos }
  13013. }
  13014. function clipPosArray(doc, array) {
  13015. var out = [];
  13016. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  13017. return out
  13018. }
  13019. var SavedContext = function(state, lookAhead) {
  13020. this.state = state;
  13021. this.lookAhead = lookAhead;
  13022. };
  13023. var Context = function(doc, state, line, lookAhead) {
  13024. this.state = state;
  13025. this.doc = doc;
  13026. this.line = line;
  13027. this.maxLookAhead = lookAhead || 0;
  13028. this.baseTokens = null;
  13029. this.baseTokenPos = 1;
  13030. };
  13031. Context.prototype.lookAhead = function (n) {
  13032. var line = this.doc.getLine(this.line + n);
  13033. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  13034. return line
  13035. };
  13036. Context.prototype.baseToken = function (n) {
  13037. if (!this.baseTokens) { return null }
  13038. while (this.baseTokens[this.baseTokenPos] <= n)
  13039. { this.baseTokenPos += 2; }
  13040. var type = this.baseTokens[this.baseTokenPos + 1];
  13041. return {type: type && type.replace(/( |^)overlay .*/, ""),
  13042. size: this.baseTokens[this.baseTokenPos] - n}
  13043. };
  13044. Context.prototype.nextLine = function () {
  13045. this.line++;
  13046. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  13047. };
  13048. Context.fromSaved = function (doc, saved, line) {
  13049. if (saved instanceof SavedContext)
  13050. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  13051. else
  13052. { return new Context(doc, copyState(doc.mode, saved), line) }
  13053. };
  13054. Context.prototype.save = function (copy) {
  13055. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  13056. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  13057. };
  13058. // Compute a style array (an array starting with a mode generation
  13059. // -- for invalidation -- followed by pairs of end positions and
  13060. // style strings), which is used to highlight the tokens on the
  13061. // line.
  13062. function highlightLine(cm, line, context, forceToEnd) {
  13063. // A styles array always starts with a number identifying the
  13064. // mode/overlays that it is based on (for easy invalidation).
  13065. var st = [cm.state.modeGen], lineClasses = {};
  13066. // Compute the base array of styles
  13067. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  13068. lineClasses, forceToEnd);
  13069. var state = context.state;
  13070. // Run overlays, adjust style array.
  13071. var loop = function ( o ) {
  13072. context.baseTokens = st;
  13073. var overlay = cm.state.overlays[o], i = 1, at = 0;
  13074. context.state = true;
  13075. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  13076. var start = i;
  13077. // Ensure there's a token end at the current position, and that i points at it
  13078. while (at < end) {
  13079. var i_end = st[i];
  13080. if (i_end > end)
  13081. { st.splice(i, 1, end, st[i+1], i_end); }
  13082. i += 2;
  13083. at = Math.min(end, i_end);
  13084. }
  13085. if (!style) { return }
  13086. if (overlay.opaque) {
  13087. st.splice(start, i - start, end, "overlay " + style);
  13088. i = start + 2;
  13089. } else {
  13090. for (; start < i; start += 2) {
  13091. var cur = st[start+1];
  13092. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  13093. }
  13094. }
  13095. }, lineClasses);
  13096. context.state = state;
  13097. context.baseTokens = null;
  13098. context.baseTokenPos = 1;
  13099. };
  13100. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  13101. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  13102. }
  13103. function getLineStyles(cm, line, updateFrontier) {
  13104. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  13105. var context = getContextBefore(cm, lineNo(line));
  13106. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  13107. var result = highlightLine(cm, line, context);
  13108. if (resetState) { context.state = resetState; }
  13109. line.stateAfter = context.save(!resetState);
  13110. line.styles = result.styles;
  13111. if (result.classes) { line.styleClasses = result.classes; }
  13112. else if (line.styleClasses) { line.styleClasses = null; }
  13113. if (updateFrontier === cm.doc.highlightFrontier)
  13114. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  13115. }
  13116. return line.styles
  13117. }
  13118. function getContextBefore(cm, n, precise) {
  13119. var doc = cm.doc, display = cm.display;
  13120. if (!doc.mode.startState) { return new Context(doc, true, n) }
  13121. var start = findStartLine(cm, n, precise);
  13122. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  13123. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  13124. doc.iter(start, n, function (line) {
  13125. processLine(cm, line.text, context);
  13126. var pos = context.line;
  13127. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  13128. context.nextLine();
  13129. });
  13130. if (precise) { doc.modeFrontier = context.line; }
  13131. return context
  13132. }
  13133. // Lightweight form of highlight -- proceed over this line and
  13134. // update state, but don't save a style array. Used for lines that
  13135. // aren't currently visible.
  13136. function processLine(cm, text, context, startAt) {
  13137. var mode = cm.doc.mode;
  13138. var stream = new StringStream(text, cm.options.tabSize, context);
  13139. stream.start = stream.pos = startAt || 0;
  13140. if (text == "") { callBlankLine(mode, context.state); }
  13141. while (!stream.eol()) {
  13142. readToken(mode, stream, context.state);
  13143. stream.start = stream.pos;
  13144. }
  13145. }
  13146. function callBlankLine(mode, state) {
  13147. if (mode.blankLine) { return mode.blankLine(state) }
  13148. if (!mode.innerMode) { return }
  13149. var inner = innerMode(mode, state);
  13150. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  13151. }
  13152. function readToken(mode, stream, state, inner) {
  13153. for (var i = 0; i < 10; i++) {
  13154. if (inner) { inner[0] = innerMode(mode, state).mode; }
  13155. var style = mode.token(stream, state);
  13156. if (stream.pos > stream.start) { return style }
  13157. }
  13158. throw new Error("Mode " + mode.name + " failed to advance stream.")
  13159. }
  13160. var Token = function(stream, type, state) {
  13161. this.start = stream.start; this.end = stream.pos;
  13162. this.string = stream.current();
  13163. this.type = type || null;
  13164. this.state = state;
  13165. };
  13166. // Utility for getTokenAt and getLineTokens
  13167. function takeToken(cm, pos, precise, asArray) {
  13168. var doc = cm.doc, mode = doc.mode, style;
  13169. pos = clipPos(doc, pos);
  13170. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  13171. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  13172. if (asArray) { tokens = []; }
  13173. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  13174. stream.start = stream.pos;
  13175. style = readToken(mode, stream, context.state);
  13176. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  13177. }
  13178. return asArray ? tokens : new Token(stream, style, context.state)
  13179. }
  13180. function extractLineClasses(type, output) {
  13181. if (type) { for (;;) {
  13182. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  13183. if (!lineClass) { break }
  13184. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  13185. var prop = lineClass[1] ? "bgClass" : "textClass";
  13186. if (output[prop] == null)
  13187. { output[prop] = lineClass[2]; }
  13188. else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  13189. { output[prop] += " " + lineClass[2]; }
  13190. } }
  13191. return type
  13192. }
  13193. // Run the given mode's parser over a line, calling f for each token.
  13194. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  13195. var flattenSpans = mode.flattenSpans;
  13196. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  13197. var curStart = 0, curStyle = null;
  13198. var stream = new StringStream(text, cm.options.tabSize, context), style;
  13199. var inner = cm.options.addModeClass && [null];
  13200. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  13201. while (!stream.eol()) {
  13202. if (stream.pos > cm.options.maxHighlightLength) {
  13203. flattenSpans = false;
  13204. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  13205. stream.pos = text.length;
  13206. style = null;
  13207. } else {
  13208. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  13209. }
  13210. if (inner) {
  13211. var mName = inner[0].name;
  13212. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  13213. }
  13214. if (!flattenSpans || curStyle != style) {
  13215. while (curStart < stream.start) {
  13216. curStart = Math.min(stream.start, curStart + 5000);
  13217. f(curStart, curStyle);
  13218. }
  13219. curStyle = style;
  13220. }
  13221. stream.start = stream.pos;
  13222. }
  13223. while (curStart < stream.pos) {
  13224. // Webkit seems to refuse to render text nodes longer than 57444
  13225. // characters, and returns inaccurate measurements in nodes
  13226. // starting around 5000 chars.
  13227. var pos = Math.min(stream.pos, curStart + 5000);
  13228. f(pos, curStyle);
  13229. curStart = pos;
  13230. }
  13231. }
  13232. // Finds the line to start with when starting a parse. Tries to
  13233. // find a line with a stateAfter, so that it can start with a
  13234. // valid state. If that fails, it returns the line with the
  13235. // smallest indentation, which tends to need the least context to
  13236. // parse correctly.
  13237. function findStartLine(cm, n, precise) {
  13238. var minindent, minline, doc = cm.doc;
  13239. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  13240. for (var search = n; search > lim; --search) {
  13241. if (search <= doc.first) { return doc.first }
  13242. var line = getLine(doc, search - 1), after = line.stateAfter;
  13243. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  13244. { return search }
  13245. var indented = countColumn(line.text, null, cm.options.tabSize);
  13246. if (minline == null || minindent > indented) {
  13247. minline = search - 1;
  13248. minindent = indented;
  13249. }
  13250. }
  13251. return minline
  13252. }
  13253. function retreatFrontier(doc, n) {
  13254. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  13255. if (doc.highlightFrontier < n - 10) { return }
  13256. var start = doc.first;
  13257. for (var line = n - 1; line > start; line--) {
  13258. var saved = getLine(doc, line).stateAfter;
  13259. // change is on 3
  13260. // state on line 1 looked ahead 2 -- so saw 3
  13261. // test 1 + 2 < 3 should cover this
  13262. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  13263. start = line + 1;
  13264. break
  13265. }
  13266. }
  13267. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  13268. }
  13269. // Optimize some code when these features are not used.
  13270. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  13271. function seeReadOnlySpans() {
  13272. sawReadOnlySpans = true;
  13273. }
  13274. function seeCollapsedSpans() {
  13275. sawCollapsedSpans = true;
  13276. }
  13277. // TEXTMARKER SPANS
  13278. function MarkedSpan(marker, from, to) {
  13279. this.marker = marker;
  13280. this.from = from; this.to = to;
  13281. }
  13282. // Search an array of spans for a span matching the given marker.
  13283. function getMarkedSpanFor(spans, marker) {
  13284. if (spans) { for (var i = 0; i < spans.length; ++i) {
  13285. var span = spans[i];
  13286. if (span.marker == marker) { return span }
  13287. } }
  13288. }
  13289. // Remove a span from an array, returning undefined if no spans are
  13290. // left (we don't store arrays for lines without spans).
  13291. function removeMarkedSpan(spans, span) {
  13292. var r;
  13293. for (var i = 0; i < spans.length; ++i)
  13294. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  13295. return r
  13296. }
  13297. // Add a span to a line.
  13298. function addMarkedSpan(line, span, op) {
  13299. var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
  13300. if (inThisOp && inThisOp.has(line.markedSpans)) {
  13301. line.markedSpans.push(span);
  13302. } else {
  13303. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  13304. if (inThisOp) { inThisOp.add(line.markedSpans); }
  13305. }
  13306. span.marker.attachLine(line);
  13307. }
  13308. // Used for the algorithm that adjusts markers for a change in the
  13309. // document. These functions cut an array of spans at a given
  13310. // character position, returning an array of remaining chunks (or
  13311. // undefined if nothing remains).
  13312. function markedSpansBefore(old, startCh, isInsert) {
  13313. var nw;
  13314. if (old) { for (var i = 0; i < old.length; ++i) {
  13315. var span = old[i], marker = span.marker;
  13316. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  13317. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  13318. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  13319. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  13320. }
  13321. } }
  13322. return nw
  13323. }
  13324. function markedSpansAfter(old, endCh, isInsert) {
  13325. var nw;
  13326. if (old) { for (var i = 0; i < old.length; ++i) {
  13327. var span = old[i], marker = span.marker;
  13328. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  13329. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  13330. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  13331. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  13332. span.to == null ? null : span.to - endCh));
  13333. }
  13334. } }
  13335. return nw
  13336. }
  13337. // Given a change object, compute the new set of marker spans that
  13338. // cover the line in which the change took place. Removes spans
  13339. // entirely within the change, reconnects spans belonging to the
  13340. // same marker that appear on both sides of the change, and cuts off
  13341. // spans partially within the change. Returns an array of span
  13342. // arrays with one element for each line in (after) the change.
  13343. function stretchSpansOverChange(doc, change) {
  13344. if (change.full) { return null }
  13345. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  13346. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  13347. if (!oldFirst && !oldLast) { return null }
  13348. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  13349. // Get the spans that 'stick out' on both sides
  13350. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  13351. var last = markedSpansAfter(oldLast, endCh, isInsert);
  13352. // Next, merge those two ends
  13353. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  13354. if (first) {
  13355. // Fix up .to properties of first
  13356. for (var i = 0; i < first.length; ++i) {
  13357. var span = first[i];
  13358. if (span.to == null) {
  13359. var found = getMarkedSpanFor(last, span.marker);
  13360. if (!found) { span.to = startCh; }
  13361. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  13362. }
  13363. }
  13364. }
  13365. if (last) {
  13366. // Fix up .from in last (or move them into first in case of sameLine)
  13367. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  13368. var span$1 = last[i$1];
  13369. if (span$1.to != null) { span$1.to += offset; }
  13370. if (span$1.from == null) {
  13371. var found$1 = getMarkedSpanFor(first, span$1.marker);
  13372. if (!found$1) {
  13373. span$1.from = offset;
  13374. if (sameLine) { (first || (first = [])).push(span$1); }
  13375. }
  13376. } else {
  13377. span$1.from += offset;
  13378. if (sameLine) { (first || (first = [])).push(span$1); }
  13379. }
  13380. }
  13381. }
  13382. // Make sure we didn't create any zero-length spans
  13383. if (first) { first = clearEmptySpans(first); }
  13384. if (last && last != first) { last = clearEmptySpans(last); }
  13385. var newMarkers = [first];
  13386. if (!sameLine) {
  13387. // Fill gap with whole-line-spans
  13388. var gap = change.text.length - 2, gapMarkers;
  13389. if (gap > 0 && first)
  13390. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  13391. { if (first[i$2].to == null)
  13392. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  13393. for (var i$3 = 0; i$3 < gap; ++i$3)
  13394. { newMarkers.push(gapMarkers); }
  13395. newMarkers.push(last);
  13396. }
  13397. return newMarkers
  13398. }
  13399. // Remove spans that are empty and don't have a clearWhenEmpty
  13400. // option of false.
  13401. function clearEmptySpans(spans) {
  13402. for (var i = 0; i < spans.length; ++i) {
  13403. var span = spans[i];
  13404. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  13405. { spans.splice(i--, 1); }
  13406. }
  13407. if (!spans.length) { return null }
  13408. return spans
  13409. }
  13410. // Used to 'clip' out readOnly ranges when making a change.
  13411. function removeReadOnlyRanges(doc, from, to) {
  13412. var markers = null;
  13413. doc.iter(from.line, to.line + 1, function (line) {
  13414. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  13415. var mark = line.markedSpans[i].marker;
  13416. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  13417. { (markers || (markers = [])).push(mark); }
  13418. } }
  13419. });
  13420. if (!markers) { return null }
  13421. var parts = [{from: from, to: to}];
  13422. for (var i = 0; i < markers.length; ++i) {
  13423. var mk = markers[i], m = mk.find(0);
  13424. for (var j = 0; j < parts.length; ++j) {
  13425. var p = parts[j];
  13426. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  13427. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  13428. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  13429. { newParts.push({from: p.from, to: m.from}); }
  13430. if (dto > 0 || !mk.inclusiveRight && !dto)
  13431. { newParts.push({from: m.to, to: p.to}); }
  13432. parts.splice.apply(parts, newParts);
  13433. j += newParts.length - 3;
  13434. }
  13435. }
  13436. return parts
  13437. }
  13438. // Connect or disconnect spans from a line.
  13439. function detachMarkedSpans(line) {
  13440. var spans = line.markedSpans;
  13441. if (!spans) { return }
  13442. for (var i = 0; i < spans.length; ++i)
  13443. { spans[i].marker.detachLine(line); }
  13444. line.markedSpans = null;
  13445. }
  13446. function attachMarkedSpans(line, spans) {
  13447. if (!spans) { return }
  13448. for (var i = 0; i < spans.length; ++i)
  13449. { spans[i].marker.attachLine(line); }
  13450. line.markedSpans = spans;
  13451. }
  13452. // Helpers used when computing which overlapping collapsed span
  13453. // counts as the larger one.
  13454. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  13455. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  13456. // Returns a number indicating which of two overlapping collapsed
  13457. // spans is larger (and thus includes the other). Falls back to
  13458. // comparing ids when the spans cover exactly the same range.
  13459. function compareCollapsedMarkers(a, b) {
  13460. var lenDiff = a.lines.length - b.lines.length;
  13461. if (lenDiff != 0) { return lenDiff }
  13462. var aPos = a.find(), bPos = b.find();
  13463. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  13464. if (fromCmp) { return -fromCmp }
  13465. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  13466. if (toCmp) { return toCmp }
  13467. return b.id - a.id
  13468. }
  13469. // Find out whether a line ends or starts in a collapsed span. If
  13470. // so, return the marker for that span.
  13471. function collapsedSpanAtSide(line, start) {
  13472. var sps = sawCollapsedSpans && line.markedSpans, found;
  13473. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  13474. sp = sps[i];
  13475. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  13476. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  13477. { found = sp.marker; }
  13478. } }
  13479. return found
  13480. }
  13481. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  13482. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  13483. function collapsedSpanAround(line, ch) {
  13484. var sps = sawCollapsedSpans && line.markedSpans, found;
  13485. if (sps) { for (var i = 0; i < sps.length; ++i) {
  13486. var sp = sps[i];
  13487. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  13488. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  13489. } }
  13490. return found
  13491. }
  13492. // Test whether there exists a collapsed span that partially
  13493. // overlaps (covers the start or end, but not both) of a new span.
  13494. // Such overlap is not allowed.
  13495. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  13496. var line = getLine(doc, lineNo);
  13497. var sps = sawCollapsedSpans && line.markedSpans;
  13498. if (sps) { for (var i = 0; i < sps.length; ++i) {
  13499. var sp = sps[i];
  13500. if (!sp.marker.collapsed) { continue }
  13501. var found = sp.marker.find(0);
  13502. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  13503. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  13504. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  13505. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  13506. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  13507. { return true }
  13508. } }
  13509. }
  13510. // A visual line is a line as drawn on the screen. Folding, for
  13511. // example, can cause multiple logical lines to appear on the same
  13512. // visual line. This finds the start of the visual line that the
  13513. // given line is part of (usually that is the line itself).
  13514. function visualLine(line) {
  13515. var merged;
  13516. while (merged = collapsedSpanAtStart(line))
  13517. { line = merged.find(-1, true).line; }
  13518. return line
  13519. }
  13520. function visualLineEnd(line) {
  13521. var merged;
  13522. while (merged = collapsedSpanAtEnd(line))
  13523. { line = merged.find(1, true).line; }
  13524. return line
  13525. }
  13526. // Returns an array of logical lines that continue the visual line
  13527. // started by the argument, or undefined if there are no such lines.
  13528. function visualLineContinued(line) {
  13529. var merged, lines;
  13530. while (merged = collapsedSpanAtEnd(line)) {
  13531. line = merged.find(1, true).line
  13532. ;(lines || (lines = [])).push(line);
  13533. }
  13534. return lines
  13535. }
  13536. // Get the line number of the start of the visual line that the
  13537. // given line number is part of.
  13538. function visualLineNo(doc, lineN) {
  13539. var line = getLine(doc, lineN), vis = visualLine(line);
  13540. if (line == vis) { return lineN }
  13541. return lineNo(vis)
  13542. }
  13543. // Get the line number of the start of the next visual line after
  13544. // the given line.
  13545. function visualLineEndNo(doc, lineN) {
  13546. if (lineN > doc.lastLine()) { return lineN }
  13547. var line = getLine(doc, lineN), merged;
  13548. if (!lineIsHidden(doc, line)) { return lineN }
  13549. while (merged = collapsedSpanAtEnd(line))
  13550. { line = merged.find(1, true).line; }
  13551. return lineNo(line) + 1
  13552. }
  13553. // Compute whether a line is hidden. Lines count as hidden when they
  13554. // are part of a visual line that starts with another line, or when
  13555. // they are entirely covered by collapsed, non-widget span.
  13556. function lineIsHidden(doc, line) {
  13557. var sps = sawCollapsedSpans && line.markedSpans;
  13558. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  13559. sp = sps[i];
  13560. if (!sp.marker.collapsed) { continue }
  13561. if (sp.from == null) { return true }
  13562. if (sp.marker.widgetNode) { continue }
  13563. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  13564. { return true }
  13565. } }
  13566. }
  13567. function lineIsHiddenInner(doc, line, span) {
  13568. if (span.to == null) {
  13569. var end = span.marker.find(1, true);
  13570. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  13571. }
  13572. if (span.marker.inclusiveRight && span.to == line.text.length)
  13573. { return true }
  13574. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  13575. sp = line.markedSpans[i];
  13576. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  13577. (sp.to == null || sp.to != span.from) &&
  13578. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  13579. lineIsHiddenInner(doc, line, sp)) { return true }
  13580. }
  13581. }
  13582. // Find the height above the given line.
  13583. function heightAtLine(lineObj) {
  13584. lineObj = visualLine(lineObj);
  13585. var h = 0, chunk = lineObj.parent;
  13586. for (var i = 0; i < chunk.lines.length; ++i) {
  13587. var line = chunk.lines[i];
  13588. if (line == lineObj) { break }
  13589. else { h += line.height; }
  13590. }
  13591. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  13592. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  13593. var cur = p.children[i$1];
  13594. if (cur == chunk) { break }
  13595. else { h += cur.height; }
  13596. }
  13597. }
  13598. return h
  13599. }
  13600. // Compute the character length of a line, taking into account
  13601. // collapsed ranges (see markText) that might hide parts, and join
  13602. // other lines onto it.
  13603. function lineLength(line) {
  13604. if (line.height == 0) { return 0 }
  13605. var len = line.text.length, merged, cur = line;
  13606. while (merged = collapsedSpanAtStart(cur)) {
  13607. var found = merged.find(0, true);
  13608. cur = found.from.line;
  13609. len += found.from.ch - found.to.ch;
  13610. }
  13611. cur = line;
  13612. while (merged = collapsedSpanAtEnd(cur)) {
  13613. var found$1 = merged.find(0, true);
  13614. len -= cur.text.length - found$1.from.ch;
  13615. cur = found$1.to.line;
  13616. len += cur.text.length - found$1.to.ch;
  13617. }
  13618. return len
  13619. }
  13620. // Find the longest line in the document.
  13621. function findMaxLine(cm) {
  13622. var d = cm.display, doc = cm.doc;
  13623. d.maxLine = getLine(doc, doc.first);
  13624. d.maxLineLength = lineLength(d.maxLine);
  13625. d.maxLineChanged = true;
  13626. doc.iter(function (line) {
  13627. var len = lineLength(line);
  13628. if (len > d.maxLineLength) {
  13629. d.maxLineLength = len;
  13630. d.maxLine = line;
  13631. }
  13632. });
  13633. }
  13634. // LINE DATA STRUCTURE
  13635. // Line objects. These hold state related to a line, including
  13636. // highlighting info (the styles array).
  13637. var Line = function(text, markedSpans, estimateHeight) {
  13638. this.text = text;
  13639. attachMarkedSpans(this, markedSpans);
  13640. this.height = estimateHeight ? estimateHeight(this) : 1;
  13641. };
  13642. Line.prototype.lineNo = function () { return lineNo(this) };
  13643. eventMixin(Line);
  13644. // Change the content (text, markers) of a line. Automatically
  13645. // invalidates cached information and tries to re-estimate the
  13646. // line's height.
  13647. function updateLine(line, text, markedSpans, estimateHeight) {
  13648. line.text = text;
  13649. if (line.stateAfter) { line.stateAfter = null; }
  13650. if (line.styles) { line.styles = null; }
  13651. if (line.order != null) { line.order = null; }
  13652. detachMarkedSpans(line);
  13653. attachMarkedSpans(line, markedSpans);
  13654. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  13655. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  13656. }
  13657. // Detach a line from the document tree and its markers.
  13658. function cleanUpLine(line) {
  13659. line.parent = null;
  13660. detachMarkedSpans(line);
  13661. }
  13662. // Convert a style as returned by a mode (either null, or a string
  13663. // containing one or more styles) to a CSS style. This is cached,
  13664. // and also looks for line-wide styles.
  13665. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  13666. function interpretTokenStyle(style, options) {
  13667. if (!style || /^\s*$/.test(style)) { return null }
  13668. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  13669. return cache[style] ||
  13670. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  13671. }
  13672. // Render the DOM representation of the text of a line. Also builds
  13673. // up a 'line map', which points at the DOM nodes that represent
  13674. // specific stretches of text, and is used by the measuring code.
  13675. // The returned object contains the DOM node, this map, and
  13676. // information about line-wide styles that were set by the mode.
  13677. function buildLineContent(cm, lineView) {
  13678. // The padding-right forces the element to have a 'border', which
  13679. // is needed on Webkit to be able to get line-level bounding
  13680. // rectangles for it (in measureChar).
  13681. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  13682. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  13683. col: 0, pos: 0, cm: cm,
  13684. trailingSpace: false,
  13685. splitSpaces: cm.getOption("lineWrapping")};
  13686. lineView.measure = {};
  13687. // Iterate over the logical lines that make up this visual line.
  13688. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  13689. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  13690. builder.pos = 0;
  13691. builder.addToken = buildToken;
  13692. // Optionally wire in some hacks into the token-rendering
  13693. // algorithm, to deal with browser quirks.
  13694. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  13695. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  13696. builder.map = [];
  13697. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  13698. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  13699. if (line.styleClasses) {
  13700. if (line.styleClasses.bgClass)
  13701. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  13702. if (line.styleClasses.textClass)
  13703. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  13704. }
  13705. // Ensure at least a single node is present, for measuring.
  13706. if (builder.map.length == 0)
  13707. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  13708. // Store the map and a cache object for the current logical line
  13709. if (i == 0) {
  13710. lineView.measure.map = builder.map;
  13711. lineView.measure.cache = {};
  13712. } else {
  13713. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  13714. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  13715. }
  13716. }
  13717. // See issue #2901
  13718. if (webkit) {
  13719. var last = builder.content.lastChild;
  13720. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  13721. { builder.content.className = "cm-tab-wrap-hack"; }
  13722. }
  13723. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  13724. if (builder.pre.className)
  13725. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  13726. return builder
  13727. }
  13728. function defaultSpecialCharPlaceholder(ch) {
  13729. var token = elt("span", "\u2022", "cm-invalidchar");
  13730. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  13731. token.setAttribute("aria-label", token.title);
  13732. return token
  13733. }
  13734. // Build up the DOM representation for a single token, and add it to
  13735. // the line map. Takes care to render special characters separately.
  13736. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  13737. if (!text) { return }
  13738. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  13739. var special = builder.cm.state.specialChars, mustWrap = false;
  13740. var content;
  13741. if (!special.test(text)) {
  13742. builder.col += text.length;
  13743. content = document.createTextNode(displayText);
  13744. builder.map.push(builder.pos, builder.pos + text.length, content);
  13745. if (ie && ie_version < 9) { mustWrap = true; }
  13746. builder.pos += text.length;
  13747. } else {
  13748. content = document.createDocumentFragment();
  13749. var pos = 0;
  13750. while (true) {
  13751. special.lastIndex = pos;
  13752. var m = special.exec(text);
  13753. var skipped = m ? m.index - pos : text.length - pos;
  13754. if (skipped) {
  13755. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  13756. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  13757. else { content.appendChild(txt); }
  13758. builder.map.push(builder.pos, builder.pos + skipped, txt);
  13759. builder.col += skipped;
  13760. builder.pos += skipped;
  13761. }
  13762. if (!m) { break }
  13763. pos += skipped + 1;
  13764. var txt$1 = (void 0);
  13765. if (m[0] == "\t") {
  13766. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  13767. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  13768. txt$1.setAttribute("role", "presentation");
  13769. txt$1.setAttribute("cm-text", "\t");
  13770. builder.col += tabWidth;
  13771. } else if (m[0] == "\r" || m[0] == "\n") {
  13772. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  13773. txt$1.setAttribute("cm-text", m[0]);
  13774. builder.col += 1;
  13775. } else {
  13776. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  13777. txt$1.setAttribute("cm-text", m[0]);
  13778. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  13779. else { content.appendChild(txt$1); }
  13780. builder.col += 1;
  13781. }
  13782. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  13783. builder.pos++;
  13784. }
  13785. }
  13786. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  13787. if (style || startStyle || endStyle || mustWrap || css || attributes) {
  13788. var fullStyle = style || "";
  13789. if (startStyle) { fullStyle += startStyle; }
  13790. if (endStyle) { fullStyle += endStyle; }
  13791. var token = elt("span", [content], fullStyle, css);
  13792. if (attributes) {
  13793. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  13794. { token.setAttribute(attr, attributes[attr]); } }
  13795. }
  13796. return builder.content.appendChild(token)
  13797. }
  13798. builder.content.appendChild(content);
  13799. }
  13800. // Change some spaces to NBSP to prevent the browser from collapsing
  13801. // trailing spaces at the end of a line when rendering text (issue #1362).
  13802. function splitSpaces(text, trailingBefore) {
  13803. if (text.length > 1 && !/ /.test(text)) { return text }
  13804. var spaceBefore = trailingBefore, result = "";
  13805. for (var i = 0; i < text.length; i++) {
  13806. var ch = text.charAt(i);
  13807. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  13808. { ch = "\u00a0"; }
  13809. result += ch;
  13810. spaceBefore = ch == " ";
  13811. }
  13812. return result
  13813. }
  13814. // Work around nonsense dimensions being reported for stretches of
  13815. // right-to-left text.
  13816. function buildTokenBadBidi(inner, order) {
  13817. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  13818. style = style ? style + " cm-force-border" : "cm-force-border";
  13819. var start = builder.pos, end = start + text.length;
  13820. for (;;) {
  13821. // Find the part that overlaps with the start of this text
  13822. var part = (void 0);
  13823. for (var i = 0; i < order.length; i++) {
  13824. part = order[i];
  13825. if (part.to > start && part.from <= start) { break }
  13826. }
  13827. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  13828. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  13829. startStyle = null;
  13830. text = text.slice(part.to - start);
  13831. start = part.to;
  13832. }
  13833. }
  13834. }
  13835. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  13836. var widget = !ignoreWidget && marker.widgetNode;
  13837. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  13838. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  13839. if (!widget)
  13840. { widget = builder.content.appendChild(document.createElement("span")); }
  13841. widget.setAttribute("cm-marker", marker.id);
  13842. }
  13843. if (widget) {
  13844. builder.cm.display.input.setUneditable(widget);
  13845. builder.content.appendChild(widget);
  13846. }
  13847. builder.pos += size;
  13848. builder.trailingSpace = false;
  13849. }
  13850. // Outputs a number of spans to make up a line, taking highlighting
  13851. // and marked text into account.
  13852. function insertLineContent(line, builder, styles) {
  13853. var spans = line.markedSpans, allText = line.text, at = 0;
  13854. if (!spans) {
  13855. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  13856. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  13857. return
  13858. }
  13859. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  13860. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  13861. for (;;) {
  13862. if (nextChange == pos) { // Update current marker set
  13863. spanStyle = spanEndStyle = spanStartStyle = css = "";
  13864. attributes = null;
  13865. collapsed = null; nextChange = Infinity;
  13866. var foundBookmarks = [], endStyles = (void 0);
  13867. for (var j = 0; j < spans.length; ++j) {
  13868. var sp = spans[j], m = sp.marker;
  13869. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  13870. foundBookmarks.push(m);
  13871. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  13872. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  13873. nextChange = sp.to;
  13874. spanEndStyle = "";
  13875. }
  13876. if (m.className) { spanStyle += " " + m.className; }
  13877. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  13878. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  13879. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  13880. // support for the old title property
  13881. // https://github.com/codemirror/CodeMirror/pull/5673
  13882. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  13883. if (m.attributes) {
  13884. for (var attr in m.attributes)
  13885. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  13886. }
  13887. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  13888. { collapsed = sp; }
  13889. } else if (sp.from > pos && nextChange > sp.from) {
  13890. nextChange = sp.from;
  13891. }
  13892. }
  13893. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  13894. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  13895. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  13896. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  13897. if (collapsed && (collapsed.from || 0) == pos) {
  13898. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  13899. collapsed.marker, collapsed.from == null);
  13900. if (collapsed.to == null) { return }
  13901. if (collapsed.to == pos) { collapsed = false; }
  13902. }
  13903. }
  13904. if (pos >= len) { break }
  13905. var upto = Math.min(len, nextChange);
  13906. while (true) {
  13907. if (text) {
  13908. var end = pos + text.length;
  13909. if (!collapsed) {
  13910. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  13911. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  13912. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  13913. }
  13914. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  13915. pos = end;
  13916. spanStartStyle = "";
  13917. }
  13918. text = allText.slice(at, at = styles[i++]);
  13919. style = interpretTokenStyle(styles[i++], builder.cm.options);
  13920. }
  13921. }
  13922. }
  13923. // These objects are used to represent the visible (currently drawn)
  13924. // part of the document. A LineView may correspond to multiple
  13925. // logical lines, if those are connected by collapsed ranges.
  13926. function LineView(doc, line, lineN) {
  13927. // The starting line
  13928. this.line = line;
  13929. // Continuing lines, if any
  13930. this.rest = visualLineContinued(line);
  13931. // Number of logical lines in this visual line
  13932. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  13933. this.node = this.text = null;
  13934. this.hidden = lineIsHidden(doc, line);
  13935. }
  13936. // Create a range of LineView objects for the given lines.
  13937. function buildViewArray(cm, from, to) {
  13938. var array = [], nextPos;
  13939. for (var pos = from; pos < to; pos = nextPos) {
  13940. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  13941. nextPos = pos + view.size;
  13942. array.push(view);
  13943. }
  13944. return array
  13945. }
  13946. var operationGroup = null;
  13947. function pushOperation(op) {
  13948. if (operationGroup) {
  13949. operationGroup.ops.push(op);
  13950. } else {
  13951. op.ownsGroup = operationGroup = {
  13952. ops: [op],
  13953. delayedCallbacks: []
  13954. };
  13955. }
  13956. }
  13957. function fireCallbacksForOps(group) {
  13958. // Calls delayed callbacks and cursorActivity handlers until no
  13959. // new ones appear
  13960. var callbacks = group.delayedCallbacks, i = 0;
  13961. do {
  13962. for (; i < callbacks.length; i++)
  13963. { callbacks[i].call(null); }
  13964. for (var j = 0; j < group.ops.length; j++) {
  13965. var op = group.ops[j];
  13966. if (op.cursorActivityHandlers)
  13967. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  13968. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  13969. }
  13970. } while (i < callbacks.length)
  13971. }
  13972. function finishOperation(op, endCb) {
  13973. var group = op.ownsGroup;
  13974. if (!group) { return }
  13975. try { fireCallbacksForOps(group); }
  13976. finally {
  13977. operationGroup = null;
  13978. endCb(group);
  13979. }
  13980. }
  13981. var orphanDelayedCallbacks = null;
  13982. // Often, we want to signal events at a point where we are in the
  13983. // middle of some work, but don't want the handler to start calling
  13984. // other methods on the editor, which might be in an inconsistent
  13985. // state or simply not expect any other events to happen.
  13986. // signalLater looks whether there are any handlers, and schedules
  13987. // them to be executed when the last operation ends, or, if no
  13988. // operation is active, when a timeout fires.
  13989. function signalLater(emitter, type /*, values...*/) {
  13990. var arr = getHandlers(emitter, type);
  13991. if (!arr.length) { return }
  13992. var args = Array.prototype.slice.call(arguments, 2), list;
  13993. if (operationGroup) {
  13994. list = operationGroup.delayedCallbacks;
  13995. } else if (orphanDelayedCallbacks) {
  13996. list = orphanDelayedCallbacks;
  13997. } else {
  13998. list = orphanDelayedCallbacks = [];
  13999. setTimeout(fireOrphanDelayed, 0);
  14000. }
  14001. var loop = function ( i ) {
  14002. list.push(function () { return arr[i].apply(null, args); });
  14003. };
  14004. for (var i = 0; i < arr.length; ++i)
  14005. loop( i );
  14006. }
  14007. function fireOrphanDelayed() {
  14008. var delayed = orphanDelayedCallbacks;
  14009. orphanDelayedCallbacks = null;
  14010. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  14011. }
  14012. // When an aspect of a line changes, a string is added to
  14013. // lineView.changes. This updates the relevant part of the line's
  14014. // DOM structure.
  14015. function updateLineForChanges(cm, lineView, lineN, dims) {
  14016. for (var j = 0; j < lineView.changes.length; j++) {
  14017. var type = lineView.changes[j];
  14018. if (type == "text") { updateLineText(cm, lineView); }
  14019. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  14020. else if (type == "class") { updateLineClasses(cm, lineView); }
  14021. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  14022. }
  14023. lineView.changes = null;
  14024. }
  14025. // Lines with gutter elements, widgets or a background class need to
  14026. // be wrapped, and have the extra elements added to the wrapper div
  14027. function ensureLineWrapped(lineView) {
  14028. if (lineView.node == lineView.text) {
  14029. lineView.node = elt("div", null, null, "position: relative");
  14030. if (lineView.text.parentNode)
  14031. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  14032. lineView.node.appendChild(lineView.text);
  14033. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  14034. }
  14035. return lineView.node
  14036. }
  14037. function updateLineBackground(cm, lineView) {
  14038. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  14039. if (cls) { cls += " CodeMirror-linebackground"; }
  14040. if (lineView.background) {
  14041. if (cls) { lineView.background.className = cls; }
  14042. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  14043. } else if (cls) {
  14044. var wrap = ensureLineWrapped(lineView);
  14045. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  14046. cm.display.input.setUneditable(lineView.background);
  14047. }
  14048. }
  14049. // Wrapper around buildLineContent which will reuse the structure
  14050. // in display.externalMeasured when possible.
  14051. function getLineContent(cm, lineView) {
  14052. var ext = cm.display.externalMeasured;
  14053. if (ext && ext.line == lineView.line) {
  14054. cm.display.externalMeasured = null;
  14055. lineView.measure = ext.measure;
  14056. return ext.built
  14057. }
  14058. return buildLineContent(cm, lineView)
  14059. }
  14060. // Redraw the line's text. Interacts with the background and text
  14061. // classes because the mode may output tokens that influence these
  14062. // classes.
  14063. function updateLineText(cm, lineView) {
  14064. var cls = lineView.text.className;
  14065. var built = getLineContent(cm, lineView);
  14066. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  14067. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  14068. lineView.text = built.pre;
  14069. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  14070. lineView.bgClass = built.bgClass;
  14071. lineView.textClass = built.textClass;
  14072. updateLineClasses(cm, lineView);
  14073. } else if (cls) {
  14074. lineView.text.className = cls;
  14075. }
  14076. }
  14077. function updateLineClasses(cm, lineView) {
  14078. updateLineBackground(cm, lineView);
  14079. if (lineView.line.wrapClass)
  14080. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  14081. else if (lineView.node != lineView.text)
  14082. { lineView.node.className = ""; }
  14083. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  14084. lineView.text.className = textClass || "";
  14085. }
  14086. function updateLineGutter(cm, lineView, lineN, dims) {
  14087. if (lineView.gutter) {
  14088. lineView.node.removeChild(lineView.gutter);
  14089. lineView.gutter = null;
  14090. }
  14091. if (lineView.gutterBackground) {
  14092. lineView.node.removeChild(lineView.gutterBackground);
  14093. lineView.gutterBackground = null;
  14094. }
  14095. if (lineView.line.gutterClass) {
  14096. var wrap = ensureLineWrapped(lineView);
  14097. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  14098. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  14099. cm.display.input.setUneditable(lineView.gutterBackground);
  14100. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  14101. }
  14102. var markers = lineView.line.gutterMarkers;
  14103. if (cm.options.lineNumbers || markers) {
  14104. var wrap$1 = ensureLineWrapped(lineView);
  14105. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  14106. gutterWrap.setAttribute("aria-hidden", "true");
  14107. cm.display.input.setUneditable(gutterWrap);
  14108. wrap$1.insertBefore(gutterWrap, lineView.text);
  14109. if (lineView.line.gutterClass)
  14110. { gutterWrap.className += " " + lineView.line.gutterClass; }
  14111. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  14112. { lineView.lineNumber = gutterWrap.appendChild(
  14113. elt("div", lineNumberFor(cm.options, lineN),
  14114. "CodeMirror-linenumber CodeMirror-gutter-elt",
  14115. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  14116. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  14117. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  14118. if (found)
  14119. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  14120. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  14121. } }
  14122. }
  14123. }
  14124. function updateLineWidgets(cm, lineView, dims) {
  14125. if (lineView.alignable) { lineView.alignable = null; }
  14126. var isWidget = classTest("CodeMirror-linewidget");
  14127. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  14128. next = node.nextSibling;
  14129. if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  14130. }
  14131. insertLineWidgets(cm, lineView, dims);
  14132. }
  14133. // Build a line's DOM representation from scratch
  14134. function buildLineElement(cm, lineView, lineN, dims) {
  14135. var built = getLineContent(cm, lineView);
  14136. lineView.text = lineView.node = built.pre;
  14137. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  14138. if (built.textClass) { lineView.textClass = built.textClass; }
  14139. updateLineClasses(cm, lineView);
  14140. updateLineGutter(cm, lineView, lineN, dims);
  14141. insertLineWidgets(cm, lineView, dims);
  14142. return lineView.node
  14143. }
  14144. // A lineView may contain multiple logical lines (when merged by
  14145. // collapsed spans). The widgets for all of them need to be drawn.
  14146. function insertLineWidgets(cm, lineView, dims) {
  14147. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  14148. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  14149. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  14150. }
  14151. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  14152. if (!line.widgets) { return }
  14153. var wrap = ensureLineWrapped(lineView);
  14154. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  14155. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  14156. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  14157. positionLineWidget(widget, node, lineView, dims);
  14158. cm.display.input.setUneditable(node);
  14159. if (allowAbove && widget.above)
  14160. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  14161. else
  14162. { wrap.appendChild(node); }
  14163. signalLater(widget, "redraw");
  14164. }
  14165. }
  14166. function positionLineWidget(widget, node, lineView, dims) {
  14167. if (widget.noHScroll) {
  14168. (lineView.alignable || (lineView.alignable = [])).push(node);
  14169. var width = dims.wrapperWidth;
  14170. node.style.left = dims.fixedPos + "px";
  14171. if (!widget.coverGutter) {
  14172. width -= dims.gutterTotalWidth;
  14173. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  14174. }
  14175. node.style.width = width + "px";
  14176. }
  14177. if (widget.coverGutter) {
  14178. node.style.zIndex = 5;
  14179. node.style.position = "relative";
  14180. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  14181. }
  14182. }
  14183. function widgetHeight(widget) {
  14184. if (widget.height != null) { return widget.height }
  14185. var cm = widget.doc.cm;
  14186. if (!cm) { return 0 }
  14187. if (!contains(document.body, widget.node)) {
  14188. var parentStyle = "position: relative;";
  14189. if (widget.coverGutter)
  14190. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  14191. if (widget.noHScroll)
  14192. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  14193. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  14194. }
  14195. return widget.height = widget.node.parentNode.offsetHeight
  14196. }
  14197. // Return true when the given mouse event happened in a widget
  14198. function eventInWidget(display, e) {
  14199. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  14200. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  14201. (n.parentNode == display.sizer && n != display.mover))
  14202. { return true }
  14203. }
  14204. }
  14205. // POSITION MEASUREMENT
  14206. function paddingTop(display) {return display.lineSpace.offsetTop}
  14207. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  14208. function paddingH(display) {
  14209. if (display.cachedPaddingH) { return display.cachedPaddingH }
  14210. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  14211. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  14212. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  14213. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  14214. return data
  14215. }
  14216. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  14217. function displayWidth(cm) {
  14218. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  14219. }
  14220. function displayHeight(cm) {
  14221. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  14222. }
  14223. // Ensure the lineView.wrapping.heights array is populated. This is
  14224. // an array of bottom offsets for the lines that make up a drawn
  14225. // line. When lineWrapping is on, there might be more than one
  14226. // height.
  14227. function ensureLineHeights(cm, lineView, rect) {
  14228. var wrapping = cm.options.lineWrapping;
  14229. var curWidth = wrapping && displayWidth(cm);
  14230. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  14231. var heights = lineView.measure.heights = [];
  14232. if (wrapping) {
  14233. lineView.measure.width = curWidth;
  14234. var rects = lineView.text.firstChild.getClientRects();
  14235. for (var i = 0; i < rects.length - 1; i++) {
  14236. var cur = rects[i], next = rects[i + 1];
  14237. if (Math.abs(cur.bottom - next.bottom) > 2)
  14238. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  14239. }
  14240. }
  14241. heights.push(rect.bottom - rect.top);
  14242. }
  14243. }
  14244. // Find a line map (mapping character offsets to text nodes) and a
  14245. // measurement cache for the given line number. (A line view might
  14246. // contain multiple lines when collapsed ranges are present.)
  14247. function mapFromLineView(lineView, line, lineN) {
  14248. if (lineView.line == line)
  14249. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  14250. if (lineView.rest) {
  14251. for (var i = 0; i < lineView.rest.length; i++)
  14252. { if (lineView.rest[i] == line)
  14253. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  14254. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  14255. { if (lineNo(lineView.rest[i$1]) > lineN)
  14256. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  14257. }
  14258. }
  14259. // Render a line into the hidden node display.externalMeasured. Used
  14260. // when measurement is needed for a line that's not in the viewport.
  14261. function updateExternalMeasurement(cm, line) {
  14262. line = visualLine(line);
  14263. var lineN = lineNo(line);
  14264. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  14265. view.lineN = lineN;
  14266. var built = view.built = buildLineContent(cm, view);
  14267. view.text = built.pre;
  14268. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  14269. return view
  14270. }
  14271. // Get a {top, bottom, left, right} box (in line-local coordinates)
  14272. // for a given character.
  14273. function measureChar(cm, line, ch, bias) {
  14274. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  14275. }
  14276. // Find a line view that corresponds to the given line number.
  14277. function findViewForLine(cm, lineN) {
  14278. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  14279. { return cm.display.view[findViewIndex(cm, lineN)] }
  14280. var ext = cm.display.externalMeasured;
  14281. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  14282. { return ext }
  14283. }
  14284. // Measurement can be split in two steps, the set-up work that
  14285. // applies to the whole line, and the measurement of the actual
  14286. // character. Functions like coordsChar, that need to do a lot of
  14287. // measurements in a row, can thus ensure that the set-up work is
  14288. // only done once.
  14289. function prepareMeasureForLine(cm, line) {
  14290. var lineN = lineNo(line);
  14291. var view = findViewForLine(cm, lineN);
  14292. if (view && !view.text) {
  14293. view = null;
  14294. } else if (view && view.changes) {
  14295. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  14296. cm.curOp.forceUpdate = true;
  14297. }
  14298. if (!view)
  14299. { view = updateExternalMeasurement(cm, line); }
  14300. var info = mapFromLineView(view, line, lineN);
  14301. return {
  14302. line: line, view: view, rect: null,
  14303. map: info.map, cache: info.cache, before: info.before,
  14304. hasHeights: false
  14305. }
  14306. }
  14307. // Given a prepared measurement object, measures the position of an
  14308. // actual character (or fetches it from the cache).
  14309. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  14310. if (prepared.before) { ch = -1; }
  14311. var key = ch + (bias || ""), found;
  14312. if (prepared.cache.hasOwnProperty(key)) {
  14313. found = prepared.cache[key];
  14314. } else {
  14315. if (!prepared.rect)
  14316. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  14317. if (!prepared.hasHeights) {
  14318. ensureLineHeights(cm, prepared.view, prepared.rect);
  14319. prepared.hasHeights = true;
  14320. }
  14321. found = measureCharInner(cm, prepared, ch, bias);
  14322. if (!found.bogus) { prepared.cache[key] = found; }
  14323. }
  14324. return {left: found.left, right: found.right,
  14325. top: varHeight ? found.rtop : found.top,
  14326. bottom: varHeight ? found.rbottom : found.bottom}
  14327. }
  14328. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  14329. function nodeAndOffsetInLineMap(map, ch, bias) {
  14330. var node, start, end, collapse, mStart, mEnd;
  14331. // First, search the line map for the text node corresponding to,
  14332. // or closest to, the target character.
  14333. for (var i = 0; i < map.length; i += 3) {
  14334. mStart = map[i];
  14335. mEnd = map[i + 1];
  14336. if (ch < mStart) {
  14337. start = 0; end = 1;
  14338. collapse = "left";
  14339. } else if (ch < mEnd) {
  14340. start = ch - mStart;
  14341. end = start + 1;
  14342. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  14343. end = mEnd - mStart;
  14344. start = end - 1;
  14345. if (ch >= mEnd) { collapse = "right"; }
  14346. }
  14347. if (start != null) {
  14348. node = map[i + 2];
  14349. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  14350. { collapse = bias; }
  14351. if (bias == "left" && start == 0)
  14352. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  14353. node = map[(i -= 3) + 2];
  14354. collapse = "left";
  14355. } }
  14356. if (bias == "right" && start == mEnd - mStart)
  14357. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  14358. node = map[(i += 3) + 2];
  14359. collapse = "right";
  14360. } }
  14361. break
  14362. }
  14363. }
  14364. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  14365. }
  14366. function getUsefulRect(rects, bias) {
  14367. var rect = nullRect;
  14368. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  14369. if ((rect = rects[i]).left != rect.right) { break }
  14370. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  14371. if ((rect = rects[i$1]).left != rect.right) { break }
  14372. } }
  14373. return rect
  14374. }
  14375. function measureCharInner(cm, prepared, ch, bias) {
  14376. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  14377. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  14378. var rect;
  14379. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  14380. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  14381. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  14382. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  14383. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  14384. { rect = node.parentNode.getBoundingClientRect(); }
  14385. else
  14386. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  14387. if (rect.left || rect.right || start == 0) { break }
  14388. end = start;
  14389. start = start - 1;
  14390. collapse = "right";
  14391. }
  14392. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  14393. } else { // If it is a widget, simply get the box for the whole widget.
  14394. if (start > 0) { collapse = bias = "right"; }
  14395. var rects;
  14396. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  14397. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  14398. else
  14399. { rect = node.getBoundingClientRect(); }
  14400. }
  14401. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  14402. var rSpan = node.parentNode.getClientRects()[0];
  14403. if (rSpan)
  14404. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  14405. else
  14406. { rect = nullRect; }
  14407. }
  14408. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  14409. var mid = (rtop + rbot) / 2;
  14410. var heights = prepared.view.measure.heights;
  14411. var i = 0;
  14412. for (; i < heights.length - 1; i++)
  14413. { if (mid < heights[i]) { break } }
  14414. var top = i ? heights[i - 1] : 0, bot = heights[i];
  14415. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  14416. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  14417. top: top, bottom: bot};
  14418. if (!rect.left && !rect.right) { result.bogus = true; }
  14419. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  14420. return result
  14421. }
  14422. // Work around problem with bounding client rects on ranges being
  14423. // returned incorrectly when zoomed on IE10 and below.
  14424. function maybeUpdateRectForZooming(measure, rect) {
  14425. if (!window.screen || screen.logicalXDPI == null ||
  14426. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  14427. { return rect }
  14428. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  14429. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  14430. return {left: rect.left * scaleX, right: rect.right * scaleX,
  14431. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  14432. }
  14433. function clearLineMeasurementCacheFor(lineView) {
  14434. if (lineView.measure) {
  14435. lineView.measure.cache = {};
  14436. lineView.measure.heights = null;
  14437. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  14438. { lineView.measure.caches[i] = {}; } }
  14439. }
  14440. }
  14441. function clearLineMeasurementCache(cm) {
  14442. cm.display.externalMeasure = null;
  14443. removeChildren(cm.display.lineMeasure);
  14444. for (var i = 0; i < cm.display.view.length; i++)
  14445. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  14446. }
  14447. function clearCaches(cm) {
  14448. clearLineMeasurementCache(cm);
  14449. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  14450. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  14451. cm.display.lineNumChars = null;
  14452. }
  14453. function pageScrollX() {
  14454. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  14455. // which causes page_Offset and bounding client rects to use
  14456. // different reference viewports and invalidate our calculations.
  14457. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  14458. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  14459. }
  14460. function pageScrollY() {
  14461. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  14462. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  14463. }
  14464. function widgetTopHeight(lineObj) {
  14465. var height = 0;
  14466. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  14467. { height += widgetHeight(lineObj.widgets[i]); } } }
  14468. return height
  14469. }
  14470. // Converts a {top, bottom, left, right} box from line-local
  14471. // coordinates into another coordinate system. Context may be one of
  14472. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  14473. // or "page".
  14474. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  14475. if (!includeWidgets) {
  14476. var height = widgetTopHeight(lineObj);
  14477. rect.top += height; rect.bottom += height;
  14478. }
  14479. if (context == "line") { return rect }
  14480. if (!context) { context = "local"; }
  14481. var yOff = heightAtLine(lineObj);
  14482. if (context == "local") { yOff += paddingTop(cm.display); }
  14483. else { yOff -= cm.display.viewOffset; }
  14484. if (context == "page" || context == "window") {
  14485. var lOff = cm.display.lineSpace.getBoundingClientRect();
  14486. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  14487. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  14488. rect.left += xOff; rect.right += xOff;
  14489. }
  14490. rect.top += yOff; rect.bottom += yOff;
  14491. return rect
  14492. }
  14493. // Coverts a box from "div" coords to another coordinate system.
  14494. // Context may be "window", "page", "div", or "local"./null.
  14495. function fromCoordSystem(cm, coords, context) {
  14496. if (context == "div") { return coords }
  14497. var left = coords.left, top = coords.top;
  14498. // First move into "page" coordinate system
  14499. if (context == "page") {
  14500. left -= pageScrollX();
  14501. top -= pageScrollY();
  14502. } else if (context == "local" || !context) {
  14503. var localBox = cm.display.sizer.getBoundingClientRect();
  14504. left += localBox.left;
  14505. top += localBox.top;
  14506. }
  14507. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  14508. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  14509. }
  14510. function charCoords(cm, pos, context, lineObj, bias) {
  14511. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  14512. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  14513. }
  14514. // Returns a box for a given cursor position, which may have an
  14515. // 'other' property containing the position of the secondary cursor
  14516. // on a bidi boundary.
  14517. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  14518. // and after `char - 1` in writing order of `char - 1`
  14519. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  14520. // and before `char` in writing order of `char`
  14521. // Examples (upper-case letters are RTL, lower-case are LTR):
  14522. // Pos(0, 1, ...)
  14523. // before after
  14524. // ab a|b a|b
  14525. // aB a|B aB|
  14526. // Ab |Ab A|b
  14527. // AB B|A B|A
  14528. // Every position after the last character on a line is considered to stick
  14529. // to the last character on the line.
  14530. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  14531. lineObj = lineObj || getLine(cm.doc, pos.line);
  14532. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  14533. function get(ch, right) {
  14534. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  14535. if (right) { m.left = m.right; } else { m.right = m.left; }
  14536. return intoCoordSystem(cm, lineObj, m, context)
  14537. }
  14538. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  14539. if (ch >= lineObj.text.length) {
  14540. ch = lineObj.text.length;
  14541. sticky = "before";
  14542. } else if (ch <= 0) {
  14543. ch = 0;
  14544. sticky = "after";
  14545. }
  14546. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  14547. function getBidi(ch, partPos, invert) {
  14548. var part = order[partPos], right = part.level == 1;
  14549. return get(invert ? ch - 1 : ch, right != invert)
  14550. }
  14551. var partPos = getBidiPartAt(order, ch, sticky);
  14552. var other = bidiOther;
  14553. var val = getBidi(ch, partPos, sticky == "before");
  14554. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  14555. return val
  14556. }
  14557. // Used to cheaply estimate the coordinates for a position. Used for
  14558. // intermediate scroll updates.
  14559. function estimateCoords(cm, pos) {
  14560. var left = 0;
  14561. pos = clipPos(cm.doc, pos);
  14562. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  14563. var lineObj = getLine(cm.doc, pos.line);
  14564. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  14565. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  14566. }
  14567. // Positions returned by coordsChar contain some extra information.
  14568. // xRel is the relative x position of the input coordinates compared
  14569. // to the found position (so xRel > 0 means the coordinates are to
  14570. // the right of the character position, for example). When outside
  14571. // is true, that means the coordinates lie outside the line's
  14572. // vertical range.
  14573. function PosWithInfo(line, ch, sticky, outside, xRel) {
  14574. var pos = Pos(line, ch, sticky);
  14575. pos.xRel = xRel;
  14576. if (outside) { pos.outside = outside; }
  14577. return pos
  14578. }
  14579. // Compute the character position closest to the given coordinates.
  14580. // Input must be lineSpace-local ("div" coordinate system).
  14581. function coordsChar(cm, x, y) {
  14582. var doc = cm.doc;
  14583. y += cm.display.viewOffset;
  14584. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  14585. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  14586. if (lineN > last)
  14587. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  14588. if (x < 0) { x = 0; }
  14589. var lineObj = getLine(doc, lineN);
  14590. for (;;) {
  14591. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  14592. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  14593. if (!collapsed) { return found }
  14594. var rangeEnd = collapsed.find(1);
  14595. if (rangeEnd.line == lineN) { return rangeEnd }
  14596. lineObj = getLine(doc, lineN = rangeEnd.line);
  14597. }
  14598. }
  14599. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  14600. y -= widgetTopHeight(lineObj);
  14601. var end = lineObj.text.length;
  14602. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  14603. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  14604. return {begin: begin, end: end}
  14605. }
  14606. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  14607. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  14608. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  14609. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  14610. }
  14611. // Returns true if the given side of a box is after the given
  14612. // coordinates, in top-to-bottom, left-to-right order.
  14613. function boxIsAfter(box, x, y, left) {
  14614. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  14615. }
  14616. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  14617. // Move y into line-local coordinate space
  14618. y -= heightAtLine(lineObj);
  14619. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  14620. // When directly calling `measureCharPrepared`, we have to adjust
  14621. // for the widgets at this line.
  14622. var widgetHeight = widgetTopHeight(lineObj);
  14623. var begin = 0, end = lineObj.text.length, ltr = true;
  14624. var order = getOrder(lineObj, cm.doc.direction);
  14625. // If the line isn't plain left-to-right text, first figure out
  14626. // which bidi section the coordinates fall into.
  14627. if (order) {
  14628. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  14629. (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  14630. ltr = part.level != 1;
  14631. // The awkward -1 offsets are needed because findFirst (called
  14632. // on these below) will treat its first bound as inclusive,
  14633. // second as exclusive, but we want to actually address the
  14634. // characters in the part's range
  14635. begin = ltr ? part.from : part.to - 1;
  14636. end = ltr ? part.to : part.from - 1;
  14637. }
  14638. // A binary search to find the first character whose bounding box
  14639. // starts after the coordinates. If we run across any whose box wrap
  14640. // the coordinates, store that.
  14641. var chAround = null, boxAround = null;
  14642. var ch = findFirst(function (ch) {
  14643. var box = measureCharPrepared(cm, preparedMeasure, ch);
  14644. box.top += widgetHeight; box.bottom += widgetHeight;
  14645. if (!boxIsAfter(box, x, y, false)) { return false }
  14646. if (box.top <= y && box.left <= x) {
  14647. chAround = ch;
  14648. boxAround = box;
  14649. }
  14650. return true
  14651. }, begin, end);
  14652. var baseX, sticky, outside = false;
  14653. // If a box around the coordinates was found, use that
  14654. if (boxAround) {
  14655. // Distinguish coordinates nearer to the left or right side of the box
  14656. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  14657. ch = chAround + (atStart ? 0 : 1);
  14658. sticky = atStart ? "after" : "before";
  14659. baseX = atLeft ? boxAround.left : boxAround.right;
  14660. } else {
  14661. // (Adjust for extended bound, if necessary.)
  14662. if (!ltr && (ch == end || ch == begin)) { ch++; }
  14663. // To determine which side to associate with, get the box to the
  14664. // left of the character and compare it's vertical position to the
  14665. // coordinates
  14666. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  14667. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  14668. "after" : "before";
  14669. // Now get accurate coordinates for this place, in order to get a
  14670. // base X position
  14671. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  14672. baseX = coords.left;
  14673. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  14674. }
  14675. ch = skipExtendingChars(lineObj.text, ch, 1);
  14676. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  14677. }
  14678. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  14679. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  14680. // situation, we can take this ordering to correspond to the visual
  14681. // ordering. This finds the first part whose end is after the given
  14682. // coordinates.
  14683. var index = findFirst(function (i) {
  14684. var part = order[i], ltr = part.level != 1;
  14685. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  14686. "line", lineObj, preparedMeasure), x, y, true)
  14687. }, 0, order.length - 1);
  14688. var part = order[index];
  14689. // If this isn't the first part, the part's start is also after
  14690. // the coordinates, and the coordinates aren't on the same line as
  14691. // that start, move one part back.
  14692. if (index > 0) {
  14693. var ltr = part.level != 1;
  14694. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  14695. "line", lineObj, preparedMeasure);
  14696. if (boxIsAfter(start, x, y, true) && start.top > y)
  14697. { part = order[index - 1]; }
  14698. }
  14699. return part
  14700. }
  14701. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  14702. // In a wrapped line, rtl text on wrapping boundaries can do things
  14703. // that don't correspond to the ordering in our `order` array at
  14704. // all, so a binary search doesn't work, and we want to return a
  14705. // part that only spans one line so that the binary search in
  14706. // coordsCharInner is safe. As such, we first find the extent of the
  14707. // wrapped line, and then do a flat search in which we discard any
  14708. // spans that aren't on the line.
  14709. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  14710. var begin = ref.begin;
  14711. var end = ref.end;
  14712. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  14713. var part = null, closestDist = null;
  14714. for (var i = 0; i < order.length; i++) {
  14715. var p = order[i];
  14716. if (p.from >= end || p.to <= begin) { continue }
  14717. var ltr = p.level != 1;
  14718. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  14719. // Weigh against spans ending before this, so that they are only
  14720. // picked if nothing ends after
  14721. var dist = endX < x ? x - endX + 1e9 : endX - x;
  14722. if (!part || closestDist > dist) {
  14723. part = p;
  14724. closestDist = dist;
  14725. }
  14726. }
  14727. if (!part) { part = order[order.length - 1]; }
  14728. // Clip the part to the wrapped line.
  14729. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  14730. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  14731. return part
  14732. }
  14733. var measureText;
  14734. // Compute the default text height.
  14735. function textHeight(display) {
  14736. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  14737. if (measureText == null) {
  14738. measureText = elt("pre", null, "CodeMirror-line-like");
  14739. // Measure a bunch of lines, for browsers that compute
  14740. // fractional heights.
  14741. for (var i = 0; i < 49; ++i) {
  14742. measureText.appendChild(document.createTextNode("x"));
  14743. measureText.appendChild(elt("br"));
  14744. }
  14745. measureText.appendChild(document.createTextNode("x"));
  14746. }
  14747. removeChildrenAndAdd(display.measure, measureText);
  14748. var height = measureText.offsetHeight / 50;
  14749. if (height > 3) { display.cachedTextHeight = height; }
  14750. removeChildren(display.measure);
  14751. return height || 1
  14752. }
  14753. // Compute the default character width.
  14754. function charWidth(display) {
  14755. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  14756. var anchor = elt("span", "xxxxxxxxxx");
  14757. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  14758. removeChildrenAndAdd(display.measure, pre);
  14759. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  14760. if (width > 2) { display.cachedCharWidth = width; }
  14761. return width || 10
  14762. }
  14763. // Do a bulk-read of the DOM positions and sizes needed to draw the
  14764. // view, so that we don't interleave reading and writing to the DOM.
  14765. function getDimensions(cm) {
  14766. var d = cm.display, left = {}, width = {};
  14767. var gutterLeft = d.gutters.clientLeft;
  14768. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  14769. var id = cm.display.gutterSpecs[i].className;
  14770. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  14771. width[id] = n.clientWidth;
  14772. }
  14773. return {fixedPos: compensateForHScroll(d),
  14774. gutterTotalWidth: d.gutters.offsetWidth,
  14775. gutterLeft: left,
  14776. gutterWidth: width,
  14777. wrapperWidth: d.wrapper.clientWidth}
  14778. }
  14779. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  14780. // but using getBoundingClientRect to get a sub-pixel-accurate
  14781. // result.
  14782. function compensateForHScroll(display) {
  14783. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  14784. }
  14785. // Returns a function that estimates the height of a line, to use as
  14786. // first approximation until the line becomes visible (and is thus
  14787. // properly measurable).
  14788. function estimateHeight(cm) {
  14789. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  14790. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  14791. return function (line) {
  14792. if (lineIsHidden(cm.doc, line)) { return 0 }
  14793. var widgetsHeight = 0;
  14794. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  14795. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  14796. } }
  14797. if (wrapping)
  14798. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  14799. else
  14800. { return widgetsHeight + th }
  14801. }
  14802. }
  14803. function estimateLineHeights(cm) {
  14804. var doc = cm.doc, est = estimateHeight(cm);
  14805. doc.iter(function (line) {
  14806. var estHeight = est(line);
  14807. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  14808. });
  14809. }
  14810. // Given a mouse event, find the corresponding position. If liberal
  14811. // is false, it checks whether a gutter or scrollbar was clicked,
  14812. // and returns null if it was. forRect is used by rectangular
  14813. // selections, and tries to estimate a character position even for
  14814. // coordinates beyond the right of the text.
  14815. function posFromMouse(cm, e, liberal, forRect) {
  14816. var display = cm.display;
  14817. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  14818. var x, y, space = display.lineSpace.getBoundingClientRect();
  14819. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  14820. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  14821. catch (e$1) { return null }
  14822. var coords = coordsChar(cm, x, y), line;
  14823. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  14824. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  14825. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  14826. }
  14827. return coords
  14828. }
  14829. // Find the view element corresponding to a given line. Return null
  14830. // when the line isn't visible.
  14831. function findViewIndex(cm, n) {
  14832. if (n >= cm.display.viewTo) { return null }
  14833. n -= cm.display.viewFrom;
  14834. if (n < 0) { return null }
  14835. var view = cm.display.view;
  14836. for (var i = 0; i < view.length; i++) {
  14837. n -= view[i].size;
  14838. if (n < 0) { return i }
  14839. }
  14840. }
  14841. // Updates the display.view data structure for a given change to the
  14842. // document. From and to are in pre-change coordinates. Lendiff is
  14843. // the amount of lines added or subtracted by the change. This is
  14844. // used for changes that span multiple lines, or change the way
  14845. // lines are divided into visual lines. regLineChange (below)
  14846. // registers single-line changes.
  14847. function regChange(cm, from, to, lendiff) {
  14848. if (from == null) { from = cm.doc.first; }
  14849. if (to == null) { to = cm.doc.first + cm.doc.size; }
  14850. if (!lendiff) { lendiff = 0; }
  14851. var display = cm.display;
  14852. if (lendiff && to < display.viewTo &&
  14853. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  14854. { display.updateLineNumbers = from; }
  14855. cm.curOp.viewChanged = true;
  14856. if (from >= display.viewTo) { // Change after
  14857. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  14858. { resetView(cm); }
  14859. } else if (to <= display.viewFrom) { // Change before
  14860. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  14861. resetView(cm);
  14862. } else {
  14863. display.viewFrom += lendiff;
  14864. display.viewTo += lendiff;
  14865. }
  14866. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  14867. resetView(cm);
  14868. } else if (from <= display.viewFrom) { // Top overlap
  14869. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  14870. if (cut) {
  14871. display.view = display.view.slice(cut.index);
  14872. display.viewFrom = cut.lineN;
  14873. display.viewTo += lendiff;
  14874. } else {
  14875. resetView(cm);
  14876. }
  14877. } else if (to >= display.viewTo) { // Bottom overlap
  14878. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  14879. if (cut$1) {
  14880. display.view = display.view.slice(0, cut$1.index);
  14881. display.viewTo = cut$1.lineN;
  14882. } else {
  14883. resetView(cm);
  14884. }
  14885. } else { // Gap in the middle
  14886. var cutTop = viewCuttingPoint(cm, from, from, -1);
  14887. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  14888. if (cutTop && cutBot) {
  14889. display.view = display.view.slice(0, cutTop.index)
  14890. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  14891. .concat(display.view.slice(cutBot.index));
  14892. display.viewTo += lendiff;
  14893. } else {
  14894. resetView(cm);
  14895. }
  14896. }
  14897. var ext = display.externalMeasured;
  14898. if (ext) {
  14899. if (to < ext.lineN)
  14900. { ext.lineN += lendiff; }
  14901. else if (from < ext.lineN + ext.size)
  14902. { display.externalMeasured = null; }
  14903. }
  14904. }
  14905. // Register a change to a single line. Type must be one of "text",
  14906. // "gutter", "class", "widget"
  14907. function regLineChange(cm, line, type) {
  14908. cm.curOp.viewChanged = true;
  14909. var display = cm.display, ext = cm.display.externalMeasured;
  14910. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  14911. { display.externalMeasured = null; }
  14912. if (line < display.viewFrom || line >= display.viewTo) { return }
  14913. var lineView = display.view[findViewIndex(cm, line)];
  14914. if (lineView.node == null) { return }
  14915. var arr = lineView.changes || (lineView.changes = []);
  14916. if (indexOf(arr, type) == -1) { arr.push(type); }
  14917. }
  14918. // Clear the view.
  14919. function resetView(cm) {
  14920. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  14921. cm.display.view = [];
  14922. cm.display.viewOffset = 0;
  14923. }
  14924. function viewCuttingPoint(cm, oldN, newN, dir) {
  14925. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  14926. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  14927. { return {index: index, lineN: newN} }
  14928. var n = cm.display.viewFrom;
  14929. for (var i = 0; i < index; i++)
  14930. { n += view[i].size; }
  14931. if (n != oldN) {
  14932. if (dir > 0) {
  14933. if (index == view.length - 1) { return null }
  14934. diff = (n + view[index].size) - oldN;
  14935. index++;
  14936. } else {
  14937. diff = n - oldN;
  14938. }
  14939. oldN += diff; newN += diff;
  14940. }
  14941. while (visualLineNo(cm.doc, newN) != newN) {
  14942. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  14943. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  14944. index += dir;
  14945. }
  14946. return {index: index, lineN: newN}
  14947. }
  14948. // Force the view to cover a given range, adding empty view element
  14949. // or clipping off existing ones as needed.
  14950. function adjustView(cm, from, to) {
  14951. var display = cm.display, view = display.view;
  14952. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  14953. display.view = buildViewArray(cm, from, to);
  14954. display.viewFrom = from;
  14955. } else {
  14956. if (display.viewFrom > from)
  14957. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  14958. else if (display.viewFrom < from)
  14959. { display.view = display.view.slice(findViewIndex(cm, from)); }
  14960. display.viewFrom = from;
  14961. if (display.viewTo < to)
  14962. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  14963. else if (display.viewTo > to)
  14964. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  14965. }
  14966. display.viewTo = to;
  14967. }
  14968. // Count the number of lines in the view whose DOM representation is
  14969. // out of date (or nonexistent).
  14970. function countDirtyView(cm) {
  14971. var view = cm.display.view, dirty = 0;
  14972. for (var i = 0; i < view.length; i++) {
  14973. var lineView = view[i];
  14974. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  14975. }
  14976. return dirty
  14977. }
  14978. function updateSelection(cm) {
  14979. cm.display.input.showSelection(cm.display.input.prepareSelection());
  14980. }
  14981. function prepareSelection(cm, primary) {
  14982. if ( primary === void 0 ) primary = true;
  14983. var doc = cm.doc, result = {};
  14984. var curFragment = result.cursors = document.createDocumentFragment();
  14985. var selFragment = result.selection = document.createDocumentFragment();
  14986. var customCursor = cm.options.$customCursor;
  14987. if (customCursor) { primary = true; }
  14988. for (var i = 0; i < doc.sel.ranges.length; i++) {
  14989. if (!primary && i == doc.sel.primIndex) { continue }
  14990. var range = doc.sel.ranges[i];
  14991. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  14992. var collapsed = range.empty();
  14993. if (customCursor) {
  14994. var head = customCursor(cm, range);
  14995. if (head) { drawSelectionCursor(cm, head, curFragment); }
  14996. } else if (collapsed || cm.options.showCursorWhenSelecting) {
  14997. drawSelectionCursor(cm, range.head, curFragment);
  14998. }
  14999. if (!collapsed)
  15000. { drawSelectionRange(cm, range, selFragment); }
  15001. }
  15002. return result
  15003. }
  15004. // Draws a cursor for the given range
  15005. function drawSelectionCursor(cm, head, output) {
  15006. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  15007. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  15008. cursor.style.left = pos.left + "px";
  15009. cursor.style.top = pos.top + "px";
  15010. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  15011. if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
  15012. var charPos = charCoords(cm, head, "div", null, null);
  15013. var width = charPos.right - charPos.left;
  15014. cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
  15015. }
  15016. if (pos.other) {
  15017. // Secondary cursor, shown when on a 'jump' in bi-directional text
  15018. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  15019. otherCursor.style.display = "";
  15020. otherCursor.style.left = pos.other.left + "px";
  15021. otherCursor.style.top = pos.other.top + "px";
  15022. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  15023. }
  15024. }
  15025. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  15026. // Draws the given range as a highlighted selection
  15027. function drawSelectionRange(cm, range, output) {
  15028. var display = cm.display, doc = cm.doc;
  15029. var fragment = document.createDocumentFragment();
  15030. var padding = paddingH(cm.display), leftSide = padding.left;
  15031. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  15032. var docLTR = doc.direction == "ltr";
  15033. function add(left, top, width, bottom) {
  15034. if (top < 0) { top = 0; }
  15035. top = Math.round(top);
  15036. bottom = Math.round(bottom);
  15037. 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")));
  15038. }
  15039. function drawForLine(line, fromArg, toArg) {
  15040. var lineObj = getLine(doc, line);
  15041. var lineLen = lineObj.text.length;
  15042. var start, end;
  15043. function coords(ch, bias) {
  15044. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  15045. }
  15046. function wrapX(pos, dir, side) {
  15047. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  15048. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  15049. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  15050. return coords(ch, prop)[prop]
  15051. }
  15052. var order = getOrder(lineObj, doc.direction);
  15053. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  15054. var ltr = dir == "ltr";
  15055. var fromPos = coords(from, ltr ? "left" : "right");
  15056. var toPos = coords(to - 1, ltr ? "right" : "left");
  15057. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  15058. var first = i == 0, last = !order || i == order.length - 1;
  15059. if (toPos.top - fromPos.top <= 3) { // Single line
  15060. var openLeft = (docLTR ? openStart : openEnd) && first;
  15061. var openRight = (docLTR ? openEnd : openStart) && last;
  15062. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  15063. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  15064. add(left, fromPos.top, right - left, fromPos.bottom);
  15065. } else { // Multiple lines
  15066. var topLeft, topRight, botLeft, botRight;
  15067. if (ltr) {
  15068. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  15069. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  15070. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  15071. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  15072. } else {
  15073. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  15074. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  15075. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  15076. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  15077. }
  15078. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  15079. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  15080. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  15081. }
  15082. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  15083. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  15084. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  15085. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  15086. });
  15087. return {start: start, end: end}
  15088. }
  15089. var sFrom = range.from(), sTo = range.to();
  15090. if (sFrom.line == sTo.line) {
  15091. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  15092. } else {
  15093. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  15094. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  15095. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  15096. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  15097. if (singleVLine) {
  15098. if (leftEnd.top < rightStart.top - 2) {
  15099. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  15100. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  15101. } else {
  15102. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  15103. }
  15104. }
  15105. if (leftEnd.bottom < rightStart.top)
  15106. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  15107. }
  15108. output.appendChild(fragment);
  15109. }
  15110. // Cursor-blinking
  15111. function restartBlink(cm) {
  15112. if (!cm.state.focused) { return }
  15113. var display = cm.display;
  15114. clearInterval(display.blinker);
  15115. var on = true;
  15116. display.cursorDiv.style.visibility = "";
  15117. if (cm.options.cursorBlinkRate > 0)
  15118. { display.blinker = setInterval(function () {
  15119. if (!cm.hasFocus()) { onBlur(cm); }
  15120. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  15121. }, cm.options.cursorBlinkRate); }
  15122. else if (cm.options.cursorBlinkRate < 0)
  15123. { display.cursorDiv.style.visibility = "hidden"; }
  15124. }
  15125. function ensureFocus(cm) {
  15126. if (!cm.hasFocus()) {
  15127. cm.display.input.focus();
  15128. if (!cm.state.focused) { onFocus(cm); }
  15129. }
  15130. }
  15131. function delayBlurEvent(cm) {
  15132. cm.state.delayingBlurEvent = true;
  15133. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  15134. cm.state.delayingBlurEvent = false;
  15135. if (cm.state.focused) { onBlur(cm); }
  15136. } }, 100);
  15137. }
  15138. function onFocus(cm, e) {
  15139. if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
  15140. if (cm.options.readOnly == "nocursor") { return }
  15141. if (!cm.state.focused) {
  15142. signal(cm, "focus", cm, e);
  15143. cm.state.focused = true;
  15144. addClass(cm.display.wrapper, "CodeMirror-focused");
  15145. // This test prevents this from firing when a context
  15146. // menu is closed (since the input reset would kill the
  15147. // select-all detection hack)
  15148. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  15149. cm.display.input.reset();
  15150. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  15151. }
  15152. cm.display.input.receivedFocus();
  15153. }
  15154. restartBlink(cm);
  15155. }
  15156. function onBlur(cm, e) {
  15157. if (cm.state.delayingBlurEvent) { return }
  15158. if (cm.state.focused) {
  15159. signal(cm, "blur", cm, e);
  15160. cm.state.focused = false;
  15161. rmClass(cm.display.wrapper, "CodeMirror-focused");
  15162. }
  15163. clearInterval(cm.display.blinker);
  15164. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  15165. }
  15166. // Read the actual heights of the rendered lines, and update their
  15167. // stored heights to match.
  15168. function updateHeightsInViewport(cm) {
  15169. var display = cm.display;
  15170. var prevBottom = display.lineDiv.offsetTop;
  15171. var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
  15172. var oldHeight = display.lineDiv.getBoundingClientRect().top;
  15173. var mustScroll = 0;
  15174. for (var i = 0; i < display.view.length; i++) {
  15175. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  15176. var height = (void 0), width = 0;
  15177. if (cur.hidden) { continue }
  15178. oldHeight += cur.line.height;
  15179. if (ie && ie_version < 8) {
  15180. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  15181. height = bot - prevBottom;
  15182. prevBottom = bot;
  15183. } else {
  15184. var box = cur.node.getBoundingClientRect();
  15185. height = box.bottom - box.top;
  15186. // Check that lines don't extend past the right of the current
  15187. // editor width
  15188. if (!wrapping && cur.text.firstChild)
  15189. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  15190. }
  15191. var diff = cur.line.height - height;
  15192. if (diff > .005 || diff < -.005) {
  15193. if (oldHeight < viewTop) { mustScroll -= diff; }
  15194. updateLineHeight(cur.line, height);
  15195. updateWidgetHeight(cur.line);
  15196. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  15197. { updateWidgetHeight(cur.rest[j]); } }
  15198. }
  15199. if (width > cm.display.sizerWidth) {
  15200. var chWidth = Math.ceil(width / charWidth(cm.display));
  15201. if (chWidth > cm.display.maxLineLength) {
  15202. cm.display.maxLineLength = chWidth;
  15203. cm.display.maxLine = cur.line;
  15204. cm.display.maxLineChanged = true;
  15205. }
  15206. }
  15207. }
  15208. if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
  15209. }
  15210. // Read and store the height of line widgets associated with the
  15211. // given line.
  15212. function updateWidgetHeight(line) {
  15213. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  15214. var w = line.widgets[i], parent = w.node.parentNode;
  15215. if (parent) { w.height = parent.offsetHeight; }
  15216. } }
  15217. }
  15218. // Compute the lines that are visible in a given viewport (defaults
  15219. // the the current scroll position). viewport may contain top,
  15220. // height, and ensure (see op.scrollToPos) properties.
  15221. function visibleLines(display, doc, viewport) {
  15222. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  15223. top = Math.floor(top - paddingTop(display));
  15224. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  15225. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  15226. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  15227. // forces those lines into the viewport (if possible).
  15228. if (viewport && viewport.ensure) {
  15229. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  15230. if (ensureFrom < from) {
  15231. from = ensureFrom;
  15232. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  15233. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  15234. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  15235. to = ensureTo;
  15236. }
  15237. }
  15238. return {from: from, to: Math.max(to, from + 1)}
  15239. }
  15240. // SCROLLING THINGS INTO VIEW
  15241. // If an editor sits on the top or bottom of the window, partially
  15242. // scrolled out of view, this ensures that the cursor is visible.
  15243. function maybeScrollWindow(cm, rect) {
  15244. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  15245. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  15246. if (rect.top + box.top < 0) { doScroll = true; }
  15247. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  15248. if (doScroll != null && !phantom) {
  15249. 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;"));
  15250. cm.display.lineSpace.appendChild(scrollNode);
  15251. scrollNode.scrollIntoView(doScroll);
  15252. cm.display.lineSpace.removeChild(scrollNode);
  15253. }
  15254. }
  15255. // Scroll a given position into view (immediately), verifying that
  15256. // it actually became visible (as line heights are accurately
  15257. // measured, the position of something may 'drift' during drawing).
  15258. function scrollPosIntoView(cm, pos, end, margin) {
  15259. if (margin == null) { margin = 0; }
  15260. var rect;
  15261. if (!cm.options.lineWrapping && pos == end) {
  15262. // Set pos and end to the cursor positions around the character pos sticks to
  15263. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  15264. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  15265. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  15266. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  15267. }
  15268. for (var limit = 0; limit < 5; limit++) {
  15269. var changed = false;
  15270. var coords = cursorCoords(cm, pos);
  15271. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  15272. rect = {left: Math.min(coords.left, endCoords.left),
  15273. top: Math.min(coords.top, endCoords.top) - margin,
  15274. right: Math.max(coords.left, endCoords.left),
  15275. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  15276. var scrollPos = calculateScrollPos(cm, rect);
  15277. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  15278. if (scrollPos.scrollTop != null) {
  15279. updateScrollTop(cm, scrollPos.scrollTop);
  15280. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  15281. }
  15282. if (scrollPos.scrollLeft != null) {
  15283. setScrollLeft(cm, scrollPos.scrollLeft);
  15284. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  15285. }
  15286. if (!changed) { break }
  15287. }
  15288. return rect
  15289. }
  15290. // Scroll a given set of coordinates into view (immediately).
  15291. function scrollIntoView(cm, rect) {
  15292. var scrollPos = calculateScrollPos(cm, rect);
  15293. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  15294. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  15295. }
  15296. // Calculate a new scroll position needed to scroll the given
  15297. // rectangle into view. Returns an object with scrollTop and
  15298. // scrollLeft properties. When these are undefined, the
  15299. // vertical/horizontal position does not need to be adjusted.
  15300. function calculateScrollPos(cm, rect) {
  15301. var display = cm.display, snapMargin = textHeight(cm.display);
  15302. if (rect.top < 0) { rect.top = 0; }
  15303. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  15304. var screen = displayHeight(cm), result = {};
  15305. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  15306. var docBottom = cm.doc.height + paddingVert(display);
  15307. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  15308. if (rect.top < screentop) {
  15309. result.scrollTop = atTop ? 0 : rect.top;
  15310. } else if (rect.bottom > screentop + screen) {
  15311. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  15312. if (newTop != screentop) { result.scrollTop = newTop; }
  15313. }
  15314. var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
  15315. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
  15316. var screenw = displayWidth(cm) - display.gutters.offsetWidth;
  15317. var tooWide = rect.right - rect.left > screenw;
  15318. if (tooWide) { rect.right = rect.left + screenw; }
  15319. if (rect.left < 10)
  15320. { result.scrollLeft = 0; }
  15321. else if (rect.left < screenleft)
  15322. { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
  15323. else if (rect.right > screenw + screenleft - 3)
  15324. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  15325. return result
  15326. }
  15327. // Store a relative adjustment to the scroll position in the current
  15328. // operation (to be applied when the operation finishes).
  15329. function addToScrollTop(cm, top) {
  15330. if (top == null) { return }
  15331. resolveScrollToPos(cm);
  15332. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  15333. }
  15334. // Make sure that at the end of the operation the current cursor is
  15335. // shown.
  15336. function ensureCursorVisible(cm) {
  15337. resolveScrollToPos(cm);
  15338. var cur = cm.getCursor();
  15339. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  15340. }
  15341. function scrollToCoords(cm, x, y) {
  15342. if (x != null || y != null) { resolveScrollToPos(cm); }
  15343. if (x != null) { cm.curOp.scrollLeft = x; }
  15344. if (y != null) { cm.curOp.scrollTop = y; }
  15345. }
  15346. function scrollToRange(cm, range) {
  15347. resolveScrollToPos(cm);
  15348. cm.curOp.scrollToPos = range;
  15349. }
  15350. // When an operation has its scrollToPos property set, and another
  15351. // scroll action is applied before the end of the operation, this
  15352. // 'simulates' scrolling that position into view in a cheap way, so
  15353. // that the effect of intermediate scroll commands is not ignored.
  15354. function resolveScrollToPos(cm) {
  15355. var range = cm.curOp.scrollToPos;
  15356. if (range) {
  15357. cm.curOp.scrollToPos = null;
  15358. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  15359. scrollToCoordsRange(cm, from, to, range.margin);
  15360. }
  15361. }
  15362. function scrollToCoordsRange(cm, from, to, margin) {
  15363. var sPos = calculateScrollPos(cm, {
  15364. left: Math.min(from.left, to.left),
  15365. top: Math.min(from.top, to.top) - margin,
  15366. right: Math.max(from.right, to.right),
  15367. bottom: Math.max(from.bottom, to.bottom) + margin
  15368. });
  15369. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  15370. }
  15371. // Sync the scrollable area and scrollbars, ensure the viewport
  15372. // covers the visible area.
  15373. function updateScrollTop(cm, val) {
  15374. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  15375. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  15376. setScrollTop(cm, val, true);
  15377. if (gecko) { updateDisplaySimple(cm); }
  15378. startWorker(cm, 100);
  15379. }
  15380. function setScrollTop(cm, val, forceScroll) {
  15381. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  15382. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  15383. cm.doc.scrollTop = val;
  15384. cm.display.scrollbars.setScrollTop(val);
  15385. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  15386. }
  15387. // Sync scroller and scrollbar, ensure the gutter elements are
  15388. // aligned.
  15389. function setScrollLeft(cm, val, isScroller, forceScroll) {
  15390. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  15391. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  15392. cm.doc.scrollLeft = val;
  15393. alignHorizontally(cm);
  15394. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  15395. cm.display.scrollbars.setScrollLeft(val);
  15396. }
  15397. // SCROLLBARS
  15398. // Prepare DOM reads needed to update the scrollbars. Done in one
  15399. // shot to minimize update/measure roundtrips.
  15400. function measureForScrollbars(cm) {
  15401. var d = cm.display, gutterW = d.gutters.offsetWidth;
  15402. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  15403. return {
  15404. clientHeight: d.scroller.clientHeight,
  15405. viewHeight: d.wrapper.clientHeight,
  15406. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  15407. viewWidth: d.wrapper.clientWidth,
  15408. barLeft: cm.options.fixedGutter ? gutterW : 0,
  15409. docHeight: docH,
  15410. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  15411. nativeBarWidth: d.nativeBarWidth,
  15412. gutterWidth: gutterW
  15413. }
  15414. }
  15415. var NativeScrollbars = function(place, scroll, cm) {
  15416. this.cm = cm;
  15417. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  15418. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  15419. vert.tabIndex = horiz.tabIndex = -1;
  15420. place(vert); place(horiz);
  15421. on(vert, "scroll", function () {
  15422. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  15423. });
  15424. on(horiz, "scroll", function () {
  15425. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  15426. });
  15427. this.checkedZeroWidth = false;
  15428. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  15429. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  15430. };
  15431. NativeScrollbars.prototype.update = function (measure) {
  15432. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  15433. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  15434. var sWidth = measure.nativeBarWidth;
  15435. if (needsV) {
  15436. this.vert.style.display = "block";
  15437. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  15438. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  15439. // A bug in IE8 can cause this value to be negative, so guard it.
  15440. this.vert.firstChild.style.height =
  15441. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  15442. } else {
  15443. this.vert.scrollTop = 0;
  15444. this.vert.style.display = "";
  15445. this.vert.firstChild.style.height = "0";
  15446. }
  15447. if (needsH) {
  15448. this.horiz.style.display = "block";
  15449. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  15450. this.horiz.style.left = measure.barLeft + "px";
  15451. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  15452. this.horiz.firstChild.style.width =
  15453. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  15454. } else {
  15455. this.horiz.style.display = "";
  15456. this.horiz.firstChild.style.width = "0";
  15457. }
  15458. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  15459. if (sWidth == 0) { this.zeroWidthHack(); }
  15460. this.checkedZeroWidth = true;
  15461. }
  15462. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  15463. };
  15464. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  15465. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  15466. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  15467. };
  15468. NativeScrollbars.prototype.setScrollTop = function (pos) {
  15469. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  15470. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  15471. };
  15472. NativeScrollbars.prototype.zeroWidthHack = function () {
  15473. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  15474. this.horiz.style.height = this.vert.style.width = w;
  15475. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  15476. this.disableHoriz = new Delayed;
  15477. this.disableVert = new Delayed;
  15478. };
  15479. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  15480. bar.style.pointerEvents = "auto";
  15481. function maybeDisable() {
  15482. // To find out whether the scrollbar is still visible, we
  15483. // check whether the element under the pixel in the bottom
  15484. // right corner of the scrollbar box is the scrollbar box
  15485. // itself (when the bar is still visible) or its filler child
  15486. // (when the bar is hidden). If it is still visible, we keep
  15487. // it enabled, if it's hidden, we disable pointer events.
  15488. var box = bar.getBoundingClientRect();
  15489. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  15490. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  15491. if (elt != bar) { bar.style.pointerEvents = "none"; }
  15492. else { delay.set(1000, maybeDisable); }
  15493. }
  15494. delay.set(1000, maybeDisable);
  15495. };
  15496. NativeScrollbars.prototype.clear = function () {
  15497. var parent = this.horiz.parentNode;
  15498. parent.removeChild(this.horiz);
  15499. parent.removeChild(this.vert);
  15500. };
  15501. var NullScrollbars = function () {};
  15502. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  15503. NullScrollbars.prototype.setScrollLeft = function () {};
  15504. NullScrollbars.prototype.setScrollTop = function () {};
  15505. NullScrollbars.prototype.clear = function () {};
  15506. function updateScrollbars(cm, measure) {
  15507. if (!measure) { measure = measureForScrollbars(cm); }
  15508. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  15509. updateScrollbarsInner(cm, measure);
  15510. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  15511. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  15512. { updateHeightsInViewport(cm); }
  15513. updateScrollbarsInner(cm, measureForScrollbars(cm));
  15514. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  15515. }
  15516. }
  15517. // Re-synchronize the fake scrollbars with the actual size of the
  15518. // content.
  15519. function updateScrollbarsInner(cm, measure) {
  15520. var d = cm.display;
  15521. var sizes = d.scrollbars.update(measure);
  15522. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  15523. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  15524. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  15525. if (sizes.right && sizes.bottom) {
  15526. d.scrollbarFiller.style.display = "block";
  15527. d.scrollbarFiller.style.height = sizes.bottom + "px";
  15528. d.scrollbarFiller.style.width = sizes.right + "px";
  15529. } else { d.scrollbarFiller.style.display = ""; }
  15530. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  15531. d.gutterFiller.style.display = "block";
  15532. d.gutterFiller.style.height = sizes.bottom + "px";
  15533. d.gutterFiller.style.width = measure.gutterWidth + "px";
  15534. } else { d.gutterFiller.style.display = ""; }
  15535. }
  15536. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  15537. function initScrollbars(cm) {
  15538. if (cm.display.scrollbars) {
  15539. cm.display.scrollbars.clear();
  15540. if (cm.display.scrollbars.addClass)
  15541. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  15542. }
  15543. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  15544. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  15545. // Prevent clicks in the scrollbars from killing focus
  15546. on(node, "mousedown", function () {
  15547. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  15548. });
  15549. node.setAttribute("cm-not-content", "true");
  15550. }, function (pos, axis) {
  15551. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  15552. else { updateScrollTop(cm, pos); }
  15553. }, cm);
  15554. if (cm.display.scrollbars.addClass)
  15555. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  15556. }
  15557. // Operations are used to wrap a series of changes to the editor
  15558. // state in such a way that each change won't have to update the
  15559. // cursor and display (which would be awkward, slow, and
  15560. // error-prone). Instead, display updates are batched and then all
  15561. // combined and executed at once.
  15562. var nextOpId = 0;
  15563. // Start a new operation.
  15564. function startOperation(cm) {
  15565. cm.curOp = {
  15566. cm: cm,
  15567. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  15568. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  15569. forceUpdate: false, // Used to force a redraw
  15570. updateInput: 0, // Whether to reset the input textarea
  15571. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  15572. changeObjs: null, // Accumulated changes, for firing change events
  15573. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  15574. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  15575. selectionChanged: false, // Whether the selection needs to be redrawn
  15576. updateMaxLine: false, // Set when the widest line needs to be determined anew
  15577. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  15578. scrollToPos: null, // Used to scroll to a specific position
  15579. focus: false,
  15580. id: ++nextOpId, // Unique ID
  15581. markArrays: null // Used by addMarkedSpan
  15582. };
  15583. pushOperation(cm.curOp);
  15584. }
  15585. // Finish an operation, updating the display and signalling delayed events
  15586. function endOperation(cm) {
  15587. var op = cm.curOp;
  15588. if (op) { finishOperation(op, function (group) {
  15589. for (var i = 0; i < group.ops.length; i++)
  15590. { group.ops[i].cm.curOp = null; }
  15591. endOperations(group);
  15592. }); }
  15593. }
  15594. // The DOM updates done when an operation finishes are batched so
  15595. // that the minimum number of relayouts are required.
  15596. function endOperations(group) {
  15597. var ops = group.ops;
  15598. for (var i = 0; i < ops.length; i++) // Read DOM
  15599. { endOperation_R1(ops[i]); }
  15600. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  15601. { endOperation_W1(ops[i$1]); }
  15602. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  15603. { endOperation_R2(ops[i$2]); }
  15604. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  15605. { endOperation_W2(ops[i$3]); }
  15606. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  15607. { endOperation_finish(ops[i$4]); }
  15608. }
  15609. function endOperation_R1(op) {
  15610. var cm = op.cm, display = cm.display;
  15611. maybeClipScrollbars(cm);
  15612. if (op.updateMaxLine) { findMaxLine(cm); }
  15613. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  15614. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  15615. op.scrollToPos.to.line >= display.viewTo) ||
  15616. display.maxLineChanged && cm.options.lineWrapping;
  15617. op.update = op.mustUpdate &&
  15618. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  15619. }
  15620. function endOperation_W1(op) {
  15621. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  15622. }
  15623. function endOperation_R2(op) {
  15624. var cm = op.cm, display = cm.display;
  15625. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  15626. op.barMeasure = measureForScrollbars(cm);
  15627. // If the max line changed since it was last measured, measure it,
  15628. // and ensure the document's width matches it.
  15629. // updateDisplay_W2 will use these properties to do the actual resizing
  15630. if (display.maxLineChanged && !cm.options.lineWrapping) {
  15631. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  15632. cm.display.sizerWidth = op.adjustWidthTo;
  15633. op.barMeasure.scrollWidth =
  15634. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  15635. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  15636. }
  15637. if (op.updatedDisplay || op.selectionChanged)
  15638. { op.preparedSelection = display.input.prepareSelection(); }
  15639. }
  15640. function endOperation_W2(op) {
  15641. var cm = op.cm;
  15642. if (op.adjustWidthTo != null) {
  15643. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  15644. if (op.maxScrollLeft < cm.doc.scrollLeft)
  15645. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  15646. cm.display.maxLineChanged = false;
  15647. }
  15648. var takeFocus = op.focus && op.focus == activeElt();
  15649. if (op.preparedSelection)
  15650. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  15651. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  15652. { updateScrollbars(cm, op.barMeasure); }
  15653. if (op.updatedDisplay)
  15654. { setDocumentHeight(cm, op.barMeasure); }
  15655. if (op.selectionChanged) { restartBlink(cm); }
  15656. if (cm.state.focused && op.updateInput)
  15657. { cm.display.input.reset(op.typing); }
  15658. if (takeFocus) { ensureFocus(op.cm); }
  15659. }
  15660. function endOperation_finish(op) {
  15661. var cm = op.cm, display = cm.display, doc = cm.doc;
  15662. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  15663. // Abort mouse wheel delta measurement, when scrolling explicitly
  15664. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  15665. { display.wheelStartX = display.wheelStartY = null; }
  15666. // Propagate the scroll position to the actual DOM scroller
  15667. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  15668. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  15669. // If we need to scroll a specific position into view, do so.
  15670. if (op.scrollToPos) {
  15671. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  15672. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  15673. maybeScrollWindow(cm, rect);
  15674. }
  15675. // Fire events for markers that are hidden/unidden by editing or
  15676. // undoing
  15677. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  15678. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  15679. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  15680. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  15681. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  15682. if (display.wrapper.offsetHeight)
  15683. { doc.scrollTop = cm.display.scroller.scrollTop; }
  15684. // Fire change events, and delayed event handlers
  15685. if (op.changeObjs)
  15686. { signal(cm, "changes", cm, op.changeObjs); }
  15687. if (op.update)
  15688. { op.update.finish(); }
  15689. }
  15690. // Run the given function in an operation
  15691. function runInOp(cm, f) {
  15692. if (cm.curOp) { return f() }
  15693. startOperation(cm);
  15694. try { return f() }
  15695. finally { endOperation(cm); }
  15696. }
  15697. // Wraps a function in an operation. Returns the wrapped function.
  15698. function operation(cm, f) {
  15699. return function() {
  15700. if (cm.curOp) { return f.apply(cm, arguments) }
  15701. startOperation(cm);
  15702. try { return f.apply(cm, arguments) }
  15703. finally { endOperation(cm); }
  15704. }
  15705. }
  15706. // Used to add methods to editor and doc instances, wrapping them in
  15707. // operations.
  15708. function methodOp(f) {
  15709. return function() {
  15710. if (this.curOp) { return f.apply(this, arguments) }
  15711. startOperation(this);
  15712. try { return f.apply(this, arguments) }
  15713. finally { endOperation(this); }
  15714. }
  15715. }
  15716. function docMethodOp(f) {
  15717. return function() {
  15718. var cm = this.cm;
  15719. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  15720. startOperation(cm);
  15721. try { return f.apply(this, arguments) }
  15722. finally { endOperation(cm); }
  15723. }
  15724. }
  15725. // HIGHLIGHT WORKER
  15726. function startWorker(cm, time) {
  15727. if (cm.doc.highlightFrontier < cm.display.viewTo)
  15728. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  15729. }
  15730. function highlightWorker(cm) {
  15731. var doc = cm.doc;
  15732. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  15733. var end = +new Date + cm.options.workTime;
  15734. var context = getContextBefore(cm, doc.highlightFrontier);
  15735. var changedLines = [];
  15736. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  15737. if (context.line >= cm.display.viewFrom) { // Visible
  15738. var oldStyles = line.styles;
  15739. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  15740. var highlighted = highlightLine(cm, line, context, true);
  15741. if (resetState) { context.state = resetState; }
  15742. line.styles = highlighted.styles;
  15743. var oldCls = line.styleClasses, newCls = highlighted.classes;
  15744. if (newCls) { line.styleClasses = newCls; }
  15745. else if (oldCls) { line.styleClasses = null; }
  15746. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  15747. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  15748. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  15749. if (ischange) { changedLines.push(context.line); }
  15750. line.stateAfter = context.save();
  15751. context.nextLine();
  15752. } else {
  15753. if (line.text.length <= cm.options.maxHighlightLength)
  15754. { processLine(cm, line.text, context); }
  15755. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  15756. context.nextLine();
  15757. }
  15758. if (+new Date > end) {
  15759. startWorker(cm, cm.options.workDelay);
  15760. return true
  15761. }
  15762. });
  15763. doc.highlightFrontier = context.line;
  15764. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  15765. if (changedLines.length) { runInOp(cm, function () {
  15766. for (var i = 0; i < changedLines.length; i++)
  15767. { regLineChange(cm, changedLines[i], "text"); }
  15768. }); }
  15769. }
  15770. // DISPLAY DRAWING
  15771. var DisplayUpdate = function(cm, viewport, force) {
  15772. var display = cm.display;
  15773. this.viewport = viewport;
  15774. // Store some values that we'll need later (but don't want to force a relayout for)
  15775. this.visible = visibleLines(display, cm.doc, viewport);
  15776. this.editorIsHidden = !display.wrapper.offsetWidth;
  15777. this.wrapperHeight = display.wrapper.clientHeight;
  15778. this.wrapperWidth = display.wrapper.clientWidth;
  15779. this.oldDisplayWidth = displayWidth(cm);
  15780. this.force = force;
  15781. this.dims = getDimensions(cm);
  15782. this.events = [];
  15783. };
  15784. DisplayUpdate.prototype.signal = function (emitter, type) {
  15785. if (hasHandler(emitter, type))
  15786. { this.events.push(arguments); }
  15787. };
  15788. DisplayUpdate.prototype.finish = function () {
  15789. for (var i = 0; i < this.events.length; i++)
  15790. { signal.apply(null, this.events[i]); }
  15791. };
  15792. function maybeClipScrollbars(cm) {
  15793. var display = cm.display;
  15794. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  15795. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  15796. display.heightForcer.style.height = scrollGap(cm) + "px";
  15797. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  15798. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  15799. display.scrollbarsClipped = true;
  15800. }
  15801. }
  15802. function selectionSnapshot(cm) {
  15803. if (cm.hasFocus()) { return null }
  15804. var active = activeElt();
  15805. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  15806. var result = {activeElt: active};
  15807. if (window.getSelection) {
  15808. var sel = window.getSelection();
  15809. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  15810. result.anchorNode = sel.anchorNode;
  15811. result.anchorOffset = sel.anchorOffset;
  15812. result.focusNode = sel.focusNode;
  15813. result.focusOffset = sel.focusOffset;
  15814. }
  15815. }
  15816. return result
  15817. }
  15818. function restoreSelection(snapshot) {
  15819. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  15820. snapshot.activeElt.focus();
  15821. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  15822. snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  15823. var sel = window.getSelection(), range = document.createRange();
  15824. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  15825. range.collapse(false);
  15826. sel.removeAllRanges();
  15827. sel.addRange(range);
  15828. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  15829. }
  15830. }
  15831. // Does the actual updating of the line display. Bails out
  15832. // (returning false) when there is nothing to be done and forced is
  15833. // false.
  15834. function updateDisplayIfNeeded(cm, update) {
  15835. var display = cm.display, doc = cm.doc;
  15836. if (update.editorIsHidden) {
  15837. resetView(cm);
  15838. return false
  15839. }
  15840. // Bail out if the visible area is already rendered and nothing changed.
  15841. if (!update.force &&
  15842. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  15843. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  15844. display.renderedView == display.view && countDirtyView(cm) == 0)
  15845. { return false }
  15846. if (maybeUpdateLineNumberWidth(cm)) {
  15847. resetView(cm);
  15848. update.dims = getDimensions(cm);
  15849. }
  15850. // Compute a suitable new viewport (from & to)
  15851. var end = doc.first + doc.size;
  15852. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  15853. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  15854. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  15855. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  15856. if (sawCollapsedSpans) {
  15857. from = visualLineNo(cm.doc, from);
  15858. to = visualLineEndNo(cm.doc, to);
  15859. }
  15860. var different = from != display.viewFrom || to != display.viewTo ||
  15861. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  15862. adjustView(cm, from, to);
  15863. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  15864. // Position the mover div to align with the current scroll position
  15865. cm.display.mover.style.top = display.viewOffset + "px";
  15866. var toUpdate = countDirtyView(cm);
  15867. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  15868. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  15869. { return false }
  15870. // For big changes, we hide the enclosing element during the
  15871. // update, since that speeds up the operations on most browsers.
  15872. var selSnapshot = selectionSnapshot(cm);
  15873. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  15874. patchDisplay(cm, display.updateLineNumbers, update.dims);
  15875. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  15876. display.renderedView = display.view;
  15877. // There might have been a widget with a focused element that got
  15878. // hidden or updated, if so re-focus it.
  15879. restoreSelection(selSnapshot);
  15880. // Prevent selection and cursors from interfering with the scroll
  15881. // width and height.
  15882. removeChildren(display.cursorDiv);
  15883. removeChildren(display.selectionDiv);
  15884. display.gutters.style.height = display.sizer.style.minHeight = 0;
  15885. if (different) {
  15886. display.lastWrapHeight = update.wrapperHeight;
  15887. display.lastWrapWidth = update.wrapperWidth;
  15888. startWorker(cm, 400);
  15889. }
  15890. display.updateLineNumbers = null;
  15891. return true
  15892. }
  15893. function postUpdateDisplay(cm, update) {
  15894. var viewport = update.viewport;
  15895. for (var first = true;; first = false) {
  15896. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  15897. // Clip forced viewport to actual scrollable area.
  15898. if (viewport && viewport.top != null)
  15899. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  15900. // Updated line heights might result in the drawn area not
  15901. // actually covering the viewport. Keep looping until it does.
  15902. update.visible = visibleLines(cm.display, cm.doc, viewport);
  15903. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  15904. { break }
  15905. } else if (first) {
  15906. update.visible = visibleLines(cm.display, cm.doc, viewport);
  15907. }
  15908. if (!updateDisplayIfNeeded(cm, update)) { break }
  15909. updateHeightsInViewport(cm);
  15910. var barMeasure = measureForScrollbars(cm);
  15911. updateSelection(cm);
  15912. updateScrollbars(cm, barMeasure);
  15913. setDocumentHeight(cm, barMeasure);
  15914. update.force = false;
  15915. }
  15916. update.signal(cm, "update", cm);
  15917. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  15918. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  15919. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  15920. }
  15921. }
  15922. function updateDisplaySimple(cm, viewport) {
  15923. var update = new DisplayUpdate(cm, viewport);
  15924. if (updateDisplayIfNeeded(cm, update)) {
  15925. updateHeightsInViewport(cm);
  15926. postUpdateDisplay(cm, update);
  15927. var barMeasure = measureForScrollbars(cm);
  15928. updateSelection(cm);
  15929. updateScrollbars(cm, barMeasure);
  15930. setDocumentHeight(cm, barMeasure);
  15931. update.finish();
  15932. }
  15933. }
  15934. // Sync the actual display DOM structure with display.view, removing
  15935. // nodes for lines that are no longer in view, and creating the ones
  15936. // that are not there yet, and updating the ones that are out of
  15937. // date.
  15938. function patchDisplay(cm, updateNumbersFrom, dims) {
  15939. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  15940. var container = display.lineDiv, cur = container.firstChild;
  15941. function rm(node) {
  15942. var next = node.nextSibling;
  15943. // Works around a throw-scroll bug in OS X Webkit
  15944. if (webkit && mac && cm.display.currentWheelTarget == node)
  15945. { node.style.display = "none"; }
  15946. else
  15947. { node.parentNode.removeChild(node); }
  15948. return next
  15949. }
  15950. var view = display.view, lineN = display.viewFrom;
  15951. // Loop over the elements in the view, syncing cur (the DOM nodes
  15952. // in display.lineDiv) with the view as we go.
  15953. for (var i = 0; i < view.length; i++) {
  15954. var lineView = view[i];
  15955. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  15956. var node = buildLineElement(cm, lineView, lineN, dims);
  15957. container.insertBefore(node, cur);
  15958. } else { // Already drawn
  15959. while (cur != lineView.node) { cur = rm(cur); }
  15960. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  15961. updateNumbersFrom <= lineN && lineView.lineNumber;
  15962. if (lineView.changes) {
  15963. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  15964. updateLineForChanges(cm, lineView, lineN, dims);
  15965. }
  15966. if (updateNumber) {
  15967. removeChildren(lineView.lineNumber);
  15968. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  15969. }
  15970. cur = lineView.node.nextSibling;
  15971. }
  15972. lineN += lineView.size;
  15973. }
  15974. while (cur) { cur = rm(cur); }
  15975. }
  15976. function updateGutterSpace(display) {
  15977. var width = display.gutters.offsetWidth;
  15978. display.sizer.style.marginLeft = width + "px";
  15979. // Send an event to consumers responding to changes in gutter width.
  15980. signalLater(display, "gutterChanged", display);
  15981. }
  15982. function setDocumentHeight(cm, measure) {
  15983. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  15984. cm.display.heightForcer.style.top = measure.docHeight + "px";
  15985. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  15986. }
  15987. // Re-align line numbers and gutter marks to compensate for
  15988. // horizontal scrolling.
  15989. function alignHorizontally(cm) {
  15990. var display = cm.display, view = display.view;
  15991. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  15992. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  15993. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  15994. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  15995. if (cm.options.fixedGutter) {
  15996. if (view[i].gutter)
  15997. { view[i].gutter.style.left = left; }
  15998. if (view[i].gutterBackground)
  15999. { view[i].gutterBackground.style.left = left; }
  16000. }
  16001. var align = view[i].alignable;
  16002. if (align) { for (var j = 0; j < align.length; j++)
  16003. { align[j].style.left = left; } }
  16004. } }
  16005. if (cm.options.fixedGutter)
  16006. { display.gutters.style.left = (comp + gutterW) + "px"; }
  16007. }
  16008. // Used to ensure that the line number gutter is still the right
  16009. // size for the current document size. Returns true when an update
  16010. // is needed.
  16011. function maybeUpdateLineNumberWidth(cm) {
  16012. if (!cm.options.lineNumbers) { return false }
  16013. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  16014. if (last.length != display.lineNumChars) {
  16015. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  16016. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  16017. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  16018. display.lineGutter.style.width = "";
  16019. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  16020. display.lineNumWidth = display.lineNumInnerWidth + padding;
  16021. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  16022. display.lineGutter.style.width = display.lineNumWidth + "px";
  16023. updateGutterSpace(cm.display);
  16024. return true
  16025. }
  16026. return false
  16027. }
  16028. function getGutters(gutters, lineNumbers) {
  16029. var result = [], sawLineNumbers = false;
  16030. for (var i = 0; i < gutters.length; i++) {
  16031. var name = gutters[i], style = null;
  16032. if (typeof name != "string") { style = name.style; name = name.className; }
  16033. if (name == "CodeMirror-linenumbers") {
  16034. if (!lineNumbers) { continue }
  16035. else { sawLineNumbers = true; }
  16036. }
  16037. result.push({className: name, style: style});
  16038. }
  16039. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  16040. return result
  16041. }
  16042. // Rebuild the gutter elements, ensure the margin to the left of the
  16043. // code matches their width.
  16044. function renderGutters(display) {
  16045. var gutters = display.gutters, specs = display.gutterSpecs;
  16046. removeChildren(gutters);
  16047. display.lineGutter = null;
  16048. for (var i = 0; i < specs.length; ++i) {
  16049. var ref = specs[i];
  16050. var className = ref.className;
  16051. var style = ref.style;
  16052. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  16053. if (style) { gElt.style.cssText = style; }
  16054. if (className == "CodeMirror-linenumbers") {
  16055. display.lineGutter = gElt;
  16056. gElt.style.width = (display.lineNumWidth || 1) + "px";
  16057. }
  16058. }
  16059. gutters.style.display = specs.length ? "" : "none";
  16060. updateGutterSpace(display);
  16061. }
  16062. function updateGutters(cm) {
  16063. renderGutters(cm.display);
  16064. regChange(cm);
  16065. alignHorizontally(cm);
  16066. }
  16067. // The display handles the DOM integration, both for input reading
  16068. // and content drawing. It holds references to DOM nodes and
  16069. // display-related state.
  16070. function Display(place, doc, input, options) {
  16071. var d = this;
  16072. this.input = input;
  16073. // Covers bottom-right square when both scrollbars are present.
  16074. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  16075. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  16076. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  16077. // and h scrollbar is present.
  16078. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  16079. d.gutterFiller.setAttribute("cm-not-content", "true");
  16080. // Will contain the actual code, positioned to cover the viewport.
  16081. d.lineDiv = eltP("div", null, "CodeMirror-code");
  16082. // Elements are added to these to represent selection and cursors.
  16083. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  16084. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  16085. // A visibility: hidden element used to find the size of things.
  16086. d.measure = elt("div", null, "CodeMirror-measure");
  16087. // When lines outside of the viewport are measured, they are drawn in this.
  16088. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  16089. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  16090. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  16091. null, "position: relative; outline: none");
  16092. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  16093. // Moved around its parent to cover visible view.
  16094. d.mover = elt("div", [lines], null, "position: relative");
  16095. // Set to the height of the document, allowing scrolling.
  16096. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  16097. d.sizerWidth = null;
  16098. // Behavior of elts with overflow: auto and padding is
  16099. // inconsistent across browsers. This is used to ensure the
  16100. // scrollable area is big enough.
  16101. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  16102. // Will contain the gutters, if any.
  16103. d.gutters = elt("div", null, "CodeMirror-gutters");
  16104. d.lineGutter = null;
  16105. // Actual scrollable element.
  16106. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  16107. d.scroller.setAttribute("tabIndex", "-1");
  16108. // The element in which the editor lives.
  16109. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  16110. // This attribute is respected by automatic translation systems such as Google Translate,
  16111. // and may also be respected by tools used by human translators.
  16112. d.wrapper.setAttribute('translate', 'no');
  16113. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  16114. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  16115. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  16116. if (place) {
  16117. if (place.appendChild) { place.appendChild(d.wrapper); }
  16118. else { place(d.wrapper); }
  16119. }
  16120. // Current rendered range (may be bigger than the view window).
  16121. d.viewFrom = d.viewTo = doc.first;
  16122. d.reportedViewFrom = d.reportedViewTo = doc.first;
  16123. // Information about the rendered lines.
  16124. d.view = [];
  16125. d.renderedView = null;
  16126. // Holds info about a single rendered line when it was rendered
  16127. // for measurement, while not in view.
  16128. d.externalMeasured = null;
  16129. // Empty space (in pixels) above the view
  16130. d.viewOffset = 0;
  16131. d.lastWrapHeight = d.lastWrapWidth = 0;
  16132. d.updateLineNumbers = null;
  16133. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  16134. d.scrollbarsClipped = false;
  16135. // Used to only resize the line number gutter when necessary (when
  16136. // the amount of lines crosses a boundary that makes its width change)
  16137. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  16138. // Set to true when a non-horizontal-scrolling line widget is
  16139. // added. As an optimization, line widget aligning is skipped when
  16140. // this is false.
  16141. d.alignWidgets = false;
  16142. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  16143. // Tracks the maximum line length so that the horizontal scrollbar
  16144. // can be kept static when scrolling.
  16145. d.maxLine = null;
  16146. d.maxLineLength = 0;
  16147. d.maxLineChanged = false;
  16148. // Used for measuring wheel scrolling granularity
  16149. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  16150. // True when shift is held down.
  16151. d.shift = false;
  16152. // Used to track whether anything happened since the context menu
  16153. // was opened.
  16154. d.selForContextMenu = null;
  16155. d.activeTouch = null;
  16156. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  16157. renderGutters(d);
  16158. input.init(d);
  16159. }
  16160. // Since the delta values reported on mouse wheel events are
  16161. // unstandardized between browsers and even browser versions, and
  16162. // generally horribly unpredictable, this code starts by measuring
  16163. // the scroll effect that the first few mouse wheel events have,
  16164. // and, from that, detects the way it can convert deltas to pixel
  16165. // offsets afterwards.
  16166. //
  16167. // The reason we want to know the amount a wheel event will scroll
  16168. // is that it gives us a chance to update the display before the
  16169. // actual scrolling happens, reducing flickering.
  16170. var wheelSamples = 0, wheelPixelsPerUnit = null;
  16171. // Fill in a browser-detected starting value on browsers where we
  16172. // know one. These don't have to be accurate -- the result of them
  16173. // being wrong would just be a slight flicker on the first wheel
  16174. // scroll (if it is large enough).
  16175. if (ie) { wheelPixelsPerUnit = -.53; }
  16176. else if (gecko) { wheelPixelsPerUnit = 15; }
  16177. else if (chrome) { wheelPixelsPerUnit = -.7; }
  16178. else if (safari) { wheelPixelsPerUnit = -1/3; }
  16179. function wheelEventDelta(e) {
  16180. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  16181. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  16182. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  16183. else if (dy == null) { dy = e.wheelDelta; }
  16184. return {x: dx, y: dy}
  16185. }
  16186. function wheelEventPixels(e) {
  16187. var delta = wheelEventDelta(e);
  16188. delta.x *= wheelPixelsPerUnit;
  16189. delta.y *= wheelPixelsPerUnit;
  16190. return delta
  16191. }
  16192. function onScrollWheel(cm, e) {
  16193. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  16194. var pixelsPerUnit = wheelPixelsPerUnit;
  16195. if (e.deltaMode === 0) {
  16196. dx = e.deltaX;
  16197. dy = e.deltaY;
  16198. pixelsPerUnit = 1;
  16199. }
  16200. var display = cm.display, scroll = display.scroller;
  16201. // Quit if there's nothing to scroll here
  16202. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  16203. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  16204. if (!(dx && canScrollX || dy && canScrollY)) { return }
  16205. // Webkit browsers on OS X abort momentum scrolls when the target
  16206. // of the scroll event is removed from the scrollable element.
  16207. // This hack (see related code in patchDisplay) makes sure the
  16208. // element is kept around.
  16209. if (dy && mac && webkit) {
  16210. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  16211. for (var i = 0; i < view.length; i++) {
  16212. if (view[i].node == cur) {
  16213. cm.display.currentWheelTarget = cur;
  16214. break outer
  16215. }
  16216. }
  16217. }
  16218. }
  16219. // On some browsers, horizontal scrolling will cause redraws to
  16220. // happen before the gutter has been realigned, causing it to
  16221. // wriggle around in a most unseemly way. When we have an
  16222. // estimated pixels/delta value, we just handle horizontal
  16223. // scrolling entirely here. It'll be slightly off from native, but
  16224. // better than glitching out.
  16225. if (dx && !gecko && !presto && pixelsPerUnit != null) {
  16226. if (dy && canScrollY)
  16227. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
  16228. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
  16229. // Only prevent default scrolling if vertical scrolling is
  16230. // actually possible. Otherwise, it causes vertical scroll
  16231. // jitter on OSX trackpads when deltaX is small and deltaY
  16232. // is large (issue #3579)
  16233. if (!dy || (dy && canScrollY))
  16234. { e_preventDefault(e); }
  16235. display.wheelStartX = null; // Abort measurement, if in progress
  16236. return
  16237. }
  16238. // 'Project' the visible viewport to cover the area that is being
  16239. // scrolled into view (if we know enough to estimate it).
  16240. if (dy && pixelsPerUnit != null) {
  16241. var pixels = dy * pixelsPerUnit;
  16242. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  16243. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  16244. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  16245. updateDisplaySimple(cm, {top: top, bottom: bot});
  16246. }
  16247. if (wheelSamples < 20 && e.deltaMode !== 0) {
  16248. if (display.wheelStartX == null) {
  16249. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  16250. display.wheelDX = dx; display.wheelDY = dy;
  16251. setTimeout(function () {
  16252. if (display.wheelStartX == null) { return }
  16253. var movedX = scroll.scrollLeft - display.wheelStartX;
  16254. var movedY = scroll.scrollTop - display.wheelStartY;
  16255. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  16256. (movedX && display.wheelDX && movedX / display.wheelDX);
  16257. display.wheelStartX = display.wheelStartY = null;
  16258. if (!sample) { return }
  16259. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  16260. ++wheelSamples;
  16261. }, 200);
  16262. } else {
  16263. display.wheelDX += dx; display.wheelDY += dy;
  16264. }
  16265. }
  16266. }
  16267. // Selection objects are immutable. A new one is created every time
  16268. // the selection changes. A selection is one or more non-overlapping
  16269. // (and non-touching) ranges, sorted, and an integer that indicates
  16270. // which one is the primary selection (the one that's scrolled into
  16271. // view, that getCursor returns, etc).
  16272. var Selection = function(ranges, primIndex) {
  16273. this.ranges = ranges;
  16274. this.primIndex = primIndex;
  16275. };
  16276. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  16277. Selection.prototype.equals = function (other) {
  16278. if (other == this) { return true }
  16279. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  16280. for (var i = 0; i < this.ranges.length; i++) {
  16281. var here = this.ranges[i], there = other.ranges[i];
  16282. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  16283. }
  16284. return true
  16285. };
  16286. Selection.prototype.deepCopy = function () {
  16287. var out = [];
  16288. for (var i = 0; i < this.ranges.length; i++)
  16289. { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  16290. return new Selection(out, this.primIndex)
  16291. };
  16292. Selection.prototype.somethingSelected = function () {
  16293. for (var i = 0; i < this.ranges.length; i++)
  16294. { if (!this.ranges[i].empty()) { return true } }
  16295. return false
  16296. };
  16297. Selection.prototype.contains = function (pos, end) {
  16298. if (!end) { end = pos; }
  16299. for (var i = 0; i < this.ranges.length; i++) {
  16300. var range = this.ranges[i];
  16301. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  16302. { return i }
  16303. }
  16304. return -1
  16305. };
  16306. var Range = function(anchor, head) {
  16307. this.anchor = anchor; this.head = head;
  16308. };
  16309. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  16310. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  16311. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  16312. // Take an unsorted, potentially overlapping set of ranges, and
  16313. // build a selection out of it. 'Consumes' ranges array (modifying
  16314. // it).
  16315. function normalizeSelection(cm, ranges, primIndex) {
  16316. var mayTouch = cm && cm.options.selectionsMayTouch;
  16317. var prim = ranges[primIndex];
  16318. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  16319. primIndex = indexOf(ranges, prim);
  16320. for (var i = 1; i < ranges.length; i++) {
  16321. var cur = ranges[i], prev = ranges[i - 1];
  16322. var diff = cmp(prev.to(), cur.from());
  16323. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  16324. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  16325. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  16326. if (i <= primIndex) { --primIndex; }
  16327. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  16328. }
  16329. }
  16330. return new Selection(ranges, primIndex)
  16331. }
  16332. function simpleSelection(anchor, head) {
  16333. return new Selection([new Range(anchor, head || anchor)], 0)
  16334. }
  16335. // Compute the position of the end of a change (its 'to' property
  16336. // refers to the pre-change end).
  16337. function changeEnd(change) {
  16338. if (!change.text) { return change.to }
  16339. return Pos(change.from.line + change.text.length - 1,
  16340. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  16341. }
  16342. // Adjust a position to refer to the post-change position of the
  16343. // same text, or the end of the change if the change covers it.
  16344. function adjustForChange(pos, change) {
  16345. if (cmp(pos, change.from) < 0) { return pos }
  16346. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  16347. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  16348. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  16349. return Pos(line, ch)
  16350. }
  16351. function computeSelAfterChange(doc, change) {
  16352. var out = [];
  16353. for (var i = 0; i < doc.sel.ranges.length; i++) {
  16354. var range = doc.sel.ranges[i];
  16355. out.push(new Range(adjustForChange(range.anchor, change),
  16356. adjustForChange(range.head, change)));
  16357. }
  16358. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  16359. }
  16360. function offsetPos(pos, old, nw) {
  16361. if (pos.line == old.line)
  16362. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  16363. else
  16364. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  16365. }
  16366. // Used by replaceSelections to allow moving the selection to the
  16367. // start or around the replaced test. Hint may be "start" or "around".
  16368. function computeReplacedSel(doc, changes, hint) {
  16369. var out = [];
  16370. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  16371. for (var i = 0; i < changes.length; i++) {
  16372. var change = changes[i];
  16373. var from = offsetPos(change.from, oldPrev, newPrev);
  16374. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  16375. oldPrev = change.to;
  16376. newPrev = to;
  16377. if (hint == "around") {
  16378. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  16379. out[i] = new Range(inv ? to : from, inv ? from : to);
  16380. } else {
  16381. out[i] = new Range(from, from);
  16382. }
  16383. }
  16384. return new Selection(out, doc.sel.primIndex)
  16385. }
  16386. // Used to get the editor into a consistent state again when options change.
  16387. function loadMode(cm) {
  16388. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  16389. resetModeState(cm);
  16390. }
  16391. function resetModeState(cm) {
  16392. cm.doc.iter(function (line) {
  16393. if (line.stateAfter) { line.stateAfter = null; }
  16394. if (line.styles) { line.styles = null; }
  16395. });
  16396. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  16397. startWorker(cm, 100);
  16398. cm.state.modeGen++;
  16399. if (cm.curOp) { regChange(cm); }
  16400. }
  16401. // DOCUMENT DATA STRUCTURE
  16402. // By default, updates that start and end at the beginning of a line
  16403. // are treated specially, in order to make the association of line
  16404. // widgets and marker elements with the text behave more intuitive.
  16405. function isWholeLineUpdate(doc, change) {
  16406. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  16407. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  16408. }
  16409. // Perform a change on the document data structure.
  16410. function updateDoc(doc, change, markedSpans, estimateHeight) {
  16411. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  16412. function update(line, text, spans) {
  16413. updateLine(line, text, spans, estimateHeight);
  16414. signalLater(line, "change", line, change);
  16415. }
  16416. function linesFor(start, end) {
  16417. var result = [];
  16418. for (var i = start; i < end; ++i)
  16419. { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  16420. return result
  16421. }
  16422. var from = change.from, to = change.to, text = change.text;
  16423. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  16424. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  16425. // Adjust the line structure
  16426. if (change.full) {
  16427. doc.insert(0, linesFor(0, text.length));
  16428. doc.remove(text.length, doc.size - text.length);
  16429. } else if (isWholeLineUpdate(doc, change)) {
  16430. // This is a whole-line replace. Treated specially to make
  16431. // sure line objects move the way they are supposed to.
  16432. var added = linesFor(0, text.length - 1);
  16433. update(lastLine, lastLine.text, lastSpans);
  16434. if (nlines) { doc.remove(from.line, nlines); }
  16435. if (added.length) { doc.insert(from.line, added); }
  16436. } else if (firstLine == lastLine) {
  16437. if (text.length == 1) {
  16438. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  16439. } else {
  16440. var added$1 = linesFor(1, text.length - 1);
  16441. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  16442. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  16443. doc.insert(from.line + 1, added$1);
  16444. }
  16445. } else if (text.length == 1) {
  16446. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  16447. doc.remove(from.line + 1, nlines);
  16448. } else {
  16449. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  16450. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  16451. var added$2 = linesFor(1, text.length - 1);
  16452. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  16453. doc.insert(from.line + 1, added$2);
  16454. }
  16455. signalLater(doc, "change", doc, change);
  16456. }
  16457. // Call f for all linked documents.
  16458. function linkedDocs(doc, f, sharedHistOnly) {
  16459. function propagate(doc, skip, sharedHist) {
  16460. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  16461. var rel = doc.linked[i];
  16462. if (rel.doc == skip) { continue }
  16463. var shared = sharedHist && rel.sharedHist;
  16464. if (sharedHistOnly && !shared) { continue }
  16465. f(rel.doc, shared);
  16466. propagate(rel.doc, doc, shared);
  16467. } }
  16468. }
  16469. propagate(doc, null, true);
  16470. }
  16471. // Attach a document to an editor.
  16472. function attachDoc(cm, doc) {
  16473. if (doc.cm) { throw new Error("This document is already in use.") }
  16474. cm.doc = doc;
  16475. doc.cm = cm;
  16476. estimateLineHeights(cm);
  16477. loadMode(cm);
  16478. setDirectionClass(cm);
  16479. cm.options.direction = doc.direction;
  16480. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  16481. cm.options.mode = doc.modeOption;
  16482. regChange(cm);
  16483. }
  16484. function setDirectionClass(cm) {
  16485. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  16486. }
  16487. function directionChanged(cm) {
  16488. runInOp(cm, function () {
  16489. setDirectionClass(cm);
  16490. regChange(cm);
  16491. });
  16492. }
  16493. function History(prev) {
  16494. // Arrays of change events and selections. Doing something adds an
  16495. // event to done and clears undo. Undoing moves events from done
  16496. // to undone, redoing moves them in the other direction.
  16497. this.done = []; this.undone = [];
  16498. this.undoDepth = prev ? prev.undoDepth : Infinity;
  16499. // Used to track when changes can be merged into a single undo
  16500. // event
  16501. this.lastModTime = this.lastSelTime = 0;
  16502. this.lastOp = this.lastSelOp = null;
  16503. this.lastOrigin = this.lastSelOrigin = null;
  16504. // Used by the isClean() method
  16505. this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
  16506. }
  16507. // Create a history change event from an updateDoc-style change
  16508. // object.
  16509. function historyChangeFromChange(doc, change) {
  16510. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  16511. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  16512. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  16513. return histChange
  16514. }
  16515. // Pop all selection events off the end of a history array. Stop at
  16516. // a change event.
  16517. function clearSelectionEvents(array) {
  16518. while (array.length) {
  16519. var last = lst(array);
  16520. if (last.ranges) { array.pop(); }
  16521. else { break }
  16522. }
  16523. }
  16524. // Find the top change event in the history. Pop off selection
  16525. // events that are in the way.
  16526. function lastChangeEvent(hist, force) {
  16527. if (force) {
  16528. clearSelectionEvents(hist.done);
  16529. return lst(hist.done)
  16530. } else if (hist.done.length && !lst(hist.done).ranges) {
  16531. return lst(hist.done)
  16532. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  16533. hist.done.pop();
  16534. return lst(hist.done)
  16535. }
  16536. }
  16537. // Register a change in the history. Merges changes that are within
  16538. // a single operation, or are close together with an origin that
  16539. // allows merging (starting with "+") into a single event.
  16540. function addChangeToHistory(doc, change, selAfter, opId) {
  16541. var hist = doc.history;
  16542. hist.undone.length = 0;
  16543. var time = +new Date, cur;
  16544. var last;
  16545. if ((hist.lastOp == opId ||
  16546. hist.lastOrigin == change.origin && change.origin &&
  16547. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  16548. change.origin.charAt(0) == "*")) &&
  16549. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  16550. // Merge this change into the last event
  16551. last = lst(cur.changes);
  16552. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  16553. // Optimized case for simple insertion -- don't want to add
  16554. // new changesets for every character typed
  16555. last.to = changeEnd(change);
  16556. } else {
  16557. // Add new sub-event
  16558. cur.changes.push(historyChangeFromChange(doc, change));
  16559. }
  16560. } else {
  16561. // Can not be merged, start a new event.
  16562. var before = lst(hist.done);
  16563. if (!before || !before.ranges)
  16564. { pushSelectionToHistory(doc.sel, hist.done); }
  16565. cur = {changes: [historyChangeFromChange(doc, change)],
  16566. generation: hist.generation};
  16567. hist.done.push(cur);
  16568. while (hist.done.length > hist.undoDepth) {
  16569. hist.done.shift();
  16570. if (!hist.done[0].ranges) { hist.done.shift(); }
  16571. }
  16572. }
  16573. hist.done.push(selAfter);
  16574. hist.generation = ++hist.maxGeneration;
  16575. hist.lastModTime = hist.lastSelTime = time;
  16576. hist.lastOp = hist.lastSelOp = opId;
  16577. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  16578. if (!last) { signal(doc, "historyAdded"); }
  16579. }
  16580. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  16581. var ch = origin.charAt(0);
  16582. return ch == "*" ||
  16583. ch == "+" &&
  16584. prev.ranges.length == sel.ranges.length &&
  16585. prev.somethingSelected() == sel.somethingSelected() &&
  16586. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  16587. }
  16588. // Called whenever the selection changes, sets the new selection as
  16589. // the pending selection in the history, and pushes the old pending
  16590. // selection into the 'done' array when it was significantly
  16591. // different (in number of selected ranges, emptiness, or time).
  16592. function addSelectionToHistory(doc, sel, opId, options) {
  16593. var hist = doc.history, origin = options && options.origin;
  16594. // A new event is started when the previous origin does not match
  16595. // the current, or the origins don't allow matching. Origins
  16596. // starting with * are always merged, those starting with + are
  16597. // merged when similar and close together in time.
  16598. if (opId == hist.lastSelOp ||
  16599. (origin && hist.lastSelOrigin == origin &&
  16600. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  16601. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  16602. { hist.done[hist.done.length - 1] = sel; }
  16603. else
  16604. { pushSelectionToHistory(sel, hist.done); }
  16605. hist.lastSelTime = +new Date;
  16606. hist.lastSelOrigin = origin;
  16607. hist.lastSelOp = opId;
  16608. if (options && options.clearRedo !== false)
  16609. { clearSelectionEvents(hist.undone); }
  16610. }
  16611. function pushSelectionToHistory(sel, dest) {
  16612. var top = lst(dest);
  16613. if (!(top && top.ranges && top.equals(sel)))
  16614. { dest.push(sel); }
  16615. }
  16616. // Used to store marked span information in the history.
  16617. function attachLocalSpans(doc, change, from, to) {
  16618. var existing = change["spans_" + doc.id], n = 0;
  16619. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  16620. if (line.markedSpans)
  16621. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  16622. ++n;
  16623. });
  16624. }
  16625. // When un/re-doing restores text containing marked spans, those
  16626. // that have been explicitly cleared should not be restored.
  16627. function removeClearedSpans(spans) {
  16628. if (!spans) { return null }
  16629. var out;
  16630. for (var i = 0; i < spans.length; ++i) {
  16631. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  16632. else if (out) { out.push(spans[i]); }
  16633. }
  16634. return !out ? spans : out.length ? out : null
  16635. }
  16636. // Retrieve and filter the old marked spans stored in a change event.
  16637. function getOldSpans(doc, change) {
  16638. var found = change["spans_" + doc.id];
  16639. if (!found) { return null }
  16640. var nw = [];
  16641. for (var i = 0; i < change.text.length; ++i)
  16642. { nw.push(removeClearedSpans(found[i])); }
  16643. return nw
  16644. }
  16645. // Used for un/re-doing changes from the history. Combines the
  16646. // result of computing the existing spans with the set of spans that
  16647. // existed in the history (so that deleting around a span and then
  16648. // undoing brings back the span).
  16649. function mergeOldSpans(doc, change) {
  16650. var old = getOldSpans(doc, change);
  16651. var stretched = stretchSpansOverChange(doc, change);
  16652. if (!old) { return stretched }
  16653. if (!stretched) { return old }
  16654. for (var i = 0; i < old.length; ++i) {
  16655. var oldCur = old[i], stretchCur = stretched[i];
  16656. if (oldCur && stretchCur) {
  16657. spans: for (var j = 0; j < stretchCur.length; ++j) {
  16658. var span = stretchCur[j];
  16659. for (var k = 0; k < oldCur.length; ++k)
  16660. { if (oldCur[k].marker == span.marker) { continue spans } }
  16661. oldCur.push(span);
  16662. }
  16663. } else if (stretchCur) {
  16664. old[i] = stretchCur;
  16665. }
  16666. }
  16667. return old
  16668. }
  16669. // Used both to provide a JSON-safe object in .getHistory, and, when
  16670. // detaching a document, to split the history in two
  16671. function copyHistoryArray(events, newGroup, instantiateSel) {
  16672. var copy = [];
  16673. for (var i = 0; i < events.length; ++i) {
  16674. var event = events[i];
  16675. if (event.ranges) {
  16676. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  16677. continue
  16678. }
  16679. var changes = event.changes, newChanges = [];
  16680. copy.push({changes: newChanges});
  16681. for (var j = 0; j < changes.length; ++j) {
  16682. var change = changes[j], m = (void 0);
  16683. newChanges.push({from: change.from, to: change.to, text: change.text});
  16684. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  16685. if (indexOf(newGroup, Number(m[1])) > -1) {
  16686. lst(newChanges)[prop] = change[prop];
  16687. delete change[prop];
  16688. }
  16689. } } }
  16690. }
  16691. }
  16692. return copy
  16693. }
  16694. // The 'scroll' parameter given to many of these indicated whether
  16695. // the new cursor position should be scrolled into view after
  16696. // modifying the selection.
  16697. // If shift is held or the extend flag is set, extends a range to
  16698. // include a given position (and optionally a second position).
  16699. // Otherwise, simply returns the range between the given positions.
  16700. // Used for cursor motion and such.
  16701. function extendRange(range, head, other, extend) {
  16702. if (extend) {
  16703. var anchor = range.anchor;
  16704. if (other) {
  16705. var posBefore = cmp(head, anchor) < 0;
  16706. if (posBefore != (cmp(other, anchor) < 0)) {
  16707. anchor = head;
  16708. head = other;
  16709. } else if (posBefore != (cmp(head, other) < 0)) {
  16710. head = other;
  16711. }
  16712. }
  16713. return new Range(anchor, head)
  16714. } else {
  16715. return new Range(other || head, head)
  16716. }
  16717. }
  16718. // Extend the primary selection range, discard the rest.
  16719. function extendSelection(doc, head, other, options, extend) {
  16720. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  16721. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  16722. }
  16723. // Extend all selections (pos is an array of selections with length
  16724. // equal the number of selections)
  16725. function extendSelections(doc, heads, options) {
  16726. var out = [];
  16727. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  16728. for (var i = 0; i < doc.sel.ranges.length; i++)
  16729. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  16730. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  16731. setSelection(doc, newSel, options);
  16732. }
  16733. // Updates a single range in the selection.
  16734. function replaceOneSelection(doc, i, range, options) {
  16735. var ranges = doc.sel.ranges.slice(0);
  16736. ranges[i] = range;
  16737. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  16738. }
  16739. // Reset the selection to a single range.
  16740. function setSimpleSelection(doc, anchor, head, options) {
  16741. setSelection(doc, simpleSelection(anchor, head), options);
  16742. }
  16743. // Give beforeSelectionChange handlers a change to influence a
  16744. // selection update.
  16745. function filterSelectionChange(doc, sel, options) {
  16746. var obj = {
  16747. ranges: sel.ranges,
  16748. update: function(ranges) {
  16749. this.ranges = [];
  16750. for (var i = 0; i < ranges.length; i++)
  16751. { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  16752. clipPos(doc, ranges[i].head)); }
  16753. },
  16754. origin: options && options.origin
  16755. };
  16756. signal(doc, "beforeSelectionChange", doc, obj);
  16757. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  16758. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  16759. else { return sel }
  16760. }
  16761. function setSelectionReplaceHistory(doc, sel, options) {
  16762. var done = doc.history.done, last = lst(done);
  16763. if (last && last.ranges) {
  16764. done[done.length - 1] = sel;
  16765. setSelectionNoUndo(doc, sel, options);
  16766. } else {
  16767. setSelection(doc, sel, options);
  16768. }
  16769. }
  16770. // Set a new selection.
  16771. function setSelection(doc, sel, options) {
  16772. setSelectionNoUndo(doc, sel, options);
  16773. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  16774. }
  16775. function setSelectionNoUndo(doc, sel, options) {
  16776. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  16777. { sel = filterSelectionChange(doc, sel, options); }
  16778. var bias = options && options.bias ||
  16779. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  16780. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  16781. if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
  16782. { ensureCursorVisible(doc.cm); }
  16783. }
  16784. function setSelectionInner(doc, sel) {
  16785. if (sel.equals(doc.sel)) { return }
  16786. doc.sel = sel;
  16787. if (doc.cm) {
  16788. doc.cm.curOp.updateInput = 1;
  16789. doc.cm.curOp.selectionChanged = true;
  16790. signalCursorActivity(doc.cm);
  16791. }
  16792. signalLater(doc, "cursorActivity", doc);
  16793. }
  16794. // Verify that the selection does not partially select any atomic
  16795. // marked ranges.
  16796. function reCheckSelection(doc) {
  16797. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  16798. }
  16799. // Return a selection that does not partially select any atomic
  16800. // ranges.
  16801. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  16802. var out;
  16803. for (var i = 0; i < sel.ranges.length; i++) {
  16804. var range = sel.ranges[i];
  16805. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  16806. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  16807. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  16808. if (out || newAnchor != range.anchor || newHead != range.head) {
  16809. if (!out) { out = sel.ranges.slice(0, i); }
  16810. out[i] = new Range(newAnchor, newHead);
  16811. }
  16812. }
  16813. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  16814. }
  16815. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  16816. var line = getLine(doc, pos.line);
  16817. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  16818. var sp = line.markedSpans[i], m = sp.marker;
  16819. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  16820. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  16821. // is with selectLeft/Right
  16822. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  16823. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  16824. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  16825. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  16826. if (mayClear) {
  16827. signal(m, "beforeCursorEnter");
  16828. if (m.explicitlyCleared) {
  16829. if (!line.markedSpans) { break }
  16830. else {--i; continue}
  16831. }
  16832. }
  16833. if (!m.atomic) { continue }
  16834. if (oldPos) {
  16835. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  16836. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  16837. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  16838. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  16839. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  16840. }
  16841. var far = m.find(dir < 0 ? -1 : 1);
  16842. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  16843. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  16844. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  16845. }
  16846. } }
  16847. return pos
  16848. }
  16849. // Ensure a given position is not inside an atomic range.
  16850. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  16851. var dir = bias || 1;
  16852. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  16853. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  16854. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  16855. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  16856. if (!found) {
  16857. doc.cantEdit = true;
  16858. return Pos(doc.first, 0)
  16859. }
  16860. return found
  16861. }
  16862. function movePos(doc, pos, dir, line) {
  16863. if (dir < 0 && pos.ch == 0) {
  16864. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  16865. else { return null }
  16866. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  16867. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  16868. else { return null }
  16869. } else {
  16870. return new Pos(pos.line, pos.ch + dir)
  16871. }
  16872. }
  16873. function selectAll(cm) {
  16874. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  16875. }
  16876. // UPDATING
  16877. // Allow "beforeChange" event handlers to influence a change
  16878. function filterChange(doc, change, update) {
  16879. var obj = {
  16880. canceled: false,
  16881. from: change.from,
  16882. to: change.to,
  16883. text: change.text,
  16884. origin: change.origin,
  16885. cancel: function () { return obj.canceled = true; }
  16886. };
  16887. if (update) { obj.update = function (from, to, text, origin) {
  16888. if (from) { obj.from = clipPos(doc, from); }
  16889. if (to) { obj.to = clipPos(doc, to); }
  16890. if (text) { obj.text = text; }
  16891. if (origin !== undefined) { obj.origin = origin; }
  16892. }; }
  16893. signal(doc, "beforeChange", doc, obj);
  16894. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  16895. if (obj.canceled) {
  16896. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  16897. return null
  16898. }
  16899. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  16900. }
  16901. // Apply a change to a document, and add it to the document's
  16902. // history, and propagating it to all linked documents.
  16903. function makeChange(doc, change, ignoreReadOnly) {
  16904. if (doc.cm) {
  16905. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  16906. if (doc.cm.state.suppressEdits) { return }
  16907. }
  16908. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  16909. change = filterChange(doc, change, true);
  16910. if (!change) { return }
  16911. }
  16912. // Possibly split or suppress the update based on the presence
  16913. // of read-only spans in its range.
  16914. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  16915. if (split) {
  16916. for (var i = split.length - 1; i >= 0; --i)
  16917. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  16918. } else {
  16919. makeChangeInner(doc, change);
  16920. }
  16921. }
  16922. function makeChangeInner(doc, change) {
  16923. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  16924. var selAfter = computeSelAfterChange(doc, change);
  16925. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  16926. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  16927. var rebased = [];
  16928. linkedDocs(doc, function (doc, sharedHist) {
  16929. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  16930. rebaseHist(doc.history, change);
  16931. rebased.push(doc.history);
  16932. }
  16933. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  16934. });
  16935. }
  16936. // Revert a change stored in a document's history.
  16937. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  16938. var suppress = doc.cm && doc.cm.state.suppressEdits;
  16939. if (suppress && !allowSelectionOnly) { return }
  16940. var hist = doc.history, event, selAfter = doc.sel;
  16941. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  16942. // Verify that there is a useable event (so that ctrl-z won't
  16943. // needlessly clear selection events)
  16944. var i = 0;
  16945. for (; i < source.length; i++) {
  16946. event = source[i];
  16947. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  16948. { break }
  16949. }
  16950. if (i == source.length) { return }
  16951. hist.lastOrigin = hist.lastSelOrigin = null;
  16952. for (;;) {
  16953. event = source.pop();
  16954. if (event.ranges) {
  16955. pushSelectionToHistory(event, dest);
  16956. if (allowSelectionOnly && !event.equals(doc.sel)) {
  16957. setSelection(doc, event, {clearRedo: false});
  16958. return
  16959. }
  16960. selAfter = event;
  16961. } else if (suppress) {
  16962. source.push(event);
  16963. return
  16964. } else { break }
  16965. }
  16966. // Build up a reverse change object to add to the opposite history
  16967. // stack (redo when undoing, and vice versa).
  16968. var antiChanges = [];
  16969. pushSelectionToHistory(selAfter, dest);
  16970. dest.push({changes: antiChanges, generation: hist.generation});
  16971. hist.generation = event.generation || ++hist.maxGeneration;
  16972. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  16973. var loop = function ( i ) {
  16974. var change = event.changes[i];
  16975. change.origin = type;
  16976. if (filter && !filterChange(doc, change, false)) {
  16977. source.length = 0;
  16978. return {}
  16979. }
  16980. antiChanges.push(historyChangeFromChange(doc, change));
  16981. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  16982. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  16983. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  16984. var rebased = [];
  16985. // Propagate to the linked documents
  16986. linkedDocs(doc, function (doc, sharedHist) {
  16987. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  16988. rebaseHist(doc.history, change);
  16989. rebased.push(doc.history);
  16990. }
  16991. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  16992. });
  16993. };
  16994. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  16995. var returned = loop( i$1 );
  16996. if ( returned ) return returned.v;
  16997. }
  16998. }
  16999. // Sub-views need their line numbers shifted when text is added
  17000. // above or below them in the parent document.
  17001. function shiftDoc(doc, distance) {
  17002. if (distance == 0) { return }
  17003. doc.first += distance;
  17004. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  17005. Pos(range.anchor.line + distance, range.anchor.ch),
  17006. Pos(range.head.line + distance, range.head.ch)
  17007. ); }), doc.sel.primIndex);
  17008. if (doc.cm) {
  17009. regChange(doc.cm, doc.first, doc.first - distance, distance);
  17010. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  17011. { regLineChange(doc.cm, l, "gutter"); }
  17012. }
  17013. }
  17014. // More lower-level change function, handling only a single document
  17015. // (not linked ones).
  17016. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  17017. if (doc.cm && !doc.cm.curOp)
  17018. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  17019. if (change.to.line < doc.first) {
  17020. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  17021. return
  17022. }
  17023. if (change.from.line > doc.lastLine()) { return }
  17024. // Clip the change to the size of this doc
  17025. if (change.from.line < doc.first) {
  17026. var shift = change.text.length - 1 - (doc.first - change.from.line);
  17027. shiftDoc(doc, shift);
  17028. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  17029. text: [lst(change.text)], origin: change.origin};
  17030. }
  17031. var last = doc.lastLine();
  17032. if (change.to.line > last) {
  17033. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  17034. text: [change.text[0]], origin: change.origin};
  17035. }
  17036. change.removed = getBetween(doc, change.from, change.to);
  17037. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  17038. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  17039. else { updateDoc(doc, change, spans); }
  17040. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  17041. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  17042. { doc.cantEdit = false; }
  17043. }
  17044. // Handle the interaction of a change to a document with the editor
  17045. // that this document is part of.
  17046. function makeChangeSingleDocInEditor(cm, change, spans) {
  17047. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  17048. var recomputeMaxLength = false, checkWidthStart = from.line;
  17049. if (!cm.options.lineWrapping) {
  17050. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  17051. doc.iter(checkWidthStart, to.line + 1, function (line) {
  17052. if (line == display.maxLine) {
  17053. recomputeMaxLength = true;
  17054. return true
  17055. }
  17056. });
  17057. }
  17058. if (doc.sel.contains(change.from, change.to) > -1)
  17059. { signalCursorActivity(cm); }
  17060. updateDoc(doc, change, spans, estimateHeight(cm));
  17061. if (!cm.options.lineWrapping) {
  17062. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  17063. var len = lineLength(line);
  17064. if (len > display.maxLineLength) {
  17065. display.maxLine = line;
  17066. display.maxLineLength = len;
  17067. display.maxLineChanged = true;
  17068. recomputeMaxLength = false;
  17069. }
  17070. });
  17071. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  17072. }
  17073. retreatFrontier(doc, from.line);
  17074. startWorker(cm, 400);
  17075. var lendiff = change.text.length - (to.line - from.line) - 1;
  17076. // Remember that these lines changed, for updating the display
  17077. if (change.full)
  17078. { regChange(cm); }
  17079. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  17080. { regLineChange(cm, from.line, "text"); }
  17081. else
  17082. { regChange(cm, from.line, to.line + 1, lendiff); }
  17083. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  17084. if (changeHandler || changesHandler) {
  17085. var obj = {
  17086. from: from, to: to,
  17087. text: change.text,
  17088. removed: change.removed,
  17089. origin: change.origin
  17090. };
  17091. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  17092. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  17093. }
  17094. cm.display.selForContextMenu = null;
  17095. }
  17096. function replaceRange(doc, code, from, to, origin) {
  17097. var assign;
  17098. if (!to) { to = from; }
  17099. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  17100. if (typeof code == "string") { code = doc.splitLines(code); }
  17101. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  17102. }
  17103. // Rebasing/resetting history to deal with externally-sourced changes
  17104. function rebaseHistSelSingle(pos, from, to, diff) {
  17105. if (to < pos.line) {
  17106. pos.line += diff;
  17107. } else if (from < pos.line) {
  17108. pos.line = from;
  17109. pos.ch = 0;
  17110. }
  17111. }
  17112. // Tries to rebase an array of history events given a change in the
  17113. // document. If the change touches the same lines as the event, the
  17114. // event, and everything 'behind' it, is discarded. If the change is
  17115. // before the event, the event's positions are updated. Uses a
  17116. // copy-on-write scheme for the positions, to avoid having to
  17117. // reallocate them all on every rebase, but also avoid problems with
  17118. // shared position objects being unsafely updated.
  17119. function rebaseHistArray(array, from, to, diff) {
  17120. for (var i = 0; i < array.length; ++i) {
  17121. var sub = array[i], ok = true;
  17122. if (sub.ranges) {
  17123. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  17124. for (var j = 0; j < sub.ranges.length; j++) {
  17125. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  17126. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  17127. }
  17128. continue
  17129. }
  17130. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  17131. var cur = sub.changes[j$1];
  17132. if (to < cur.from.line) {
  17133. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  17134. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  17135. } else if (from <= cur.to.line) {
  17136. ok = false;
  17137. break
  17138. }
  17139. }
  17140. if (!ok) {
  17141. array.splice(0, i + 1);
  17142. i = 0;
  17143. }
  17144. }
  17145. }
  17146. function rebaseHist(hist, change) {
  17147. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  17148. rebaseHistArray(hist.done, from, to, diff);
  17149. rebaseHistArray(hist.undone, from, to, diff);
  17150. }
  17151. // Utility for applying a change to a line by handle or number,
  17152. // returning the number and optionally registering the line as
  17153. // changed.
  17154. function changeLine(doc, handle, changeType, op) {
  17155. var no = handle, line = handle;
  17156. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  17157. else { no = lineNo(handle); }
  17158. if (no == null) { return null }
  17159. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  17160. return line
  17161. }
  17162. // The document is represented as a BTree consisting of leaves, with
  17163. // chunk of lines in them, and branches, with up to ten leaves or
  17164. // other branch nodes below them. The top node is always a branch
  17165. // node, and is the document object itself (meaning it has
  17166. // additional methods and properties).
  17167. //
  17168. // All nodes have parent links. The tree is used both to go from
  17169. // line numbers to line objects, and to go from objects to numbers.
  17170. // It also indexes by height, and is used to convert between height
  17171. // and line object, and to find the total height of the document.
  17172. //
  17173. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  17174. function LeafChunk(lines) {
  17175. this.lines = lines;
  17176. this.parent = null;
  17177. var height = 0;
  17178. for (var i = 0; i < lines.length; ++i) {
  17179. lines[i].parent = this;
  17180. height += lines[i].height;
  17181. }
  17182. this.height = height;
  17183. }
  17184. LeafChunk.prototype = {
  17185. chunkSize: function() { return this.lines.length },
  17186. // Remove the n lines at offset 'at'.
  17187. removeInner: function(at, n) {
  17188. for (var i = at, e = at + n; i < e; ++i) {
  17189. var line = this.lines[i];
  17190. this.height -= line.height;
  17191. cleanUpLine(line);
  17192. signalLater(line, "delete");
  17193. }
  17194. this.lines.splice(at, n);
  17195. },
  17196. // Helper used to collapse a small branch into a single leaf.
  17197. collapse: function(lines) {
  17198. lines.push.apply(lines, this.lines);
  17199. },
  17200. // Insert the given array of lines at offset 'at', count them as
  17201. // having the given height.
  17202. insertInner: function(at, lines, height) {
  17203. this.height += height;
  17204. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  17205. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  17206. },
  17207. // Used to iterate over a part of the tree.
  17208. iterN: function(at, n, op) {
  17209. for (var e = at + n; at < e; ++at)
  17210. { if (op(this.lines[at])) { return true } }
  17211. }
  17212. };
  17213. function BranchChunk(children) {
  17214. this.children = children;
  17215. var size = 0, height = 0;
  17216. for (var i = 0; i < children.length; ++i) {
  17217. var ch = children[i];
  17218. size += ch.chunkSize(); height += ch.height;
  17219. ch.parent = this;
  17220. }
  17221. this.size = size;
  17222. this.height = height;
  17223. this.parent = null;
  17224. }
  17225. BranchChunk.prototype = {
  17226. chunkSize: function() { return this.size },
  17227. removeInner: function(at, n) {
  17228. this.size -= n;
  17229. for (var i = 0; i < this.children.length; ++i) {
  17230. var child = this.children[i], sz = child.chunkSize();
  17231. if (at < sz) {
  17232. var rm = Math.min(n, sz - at), oldHeight = child.height;
  17233. child.removeInner(at, rm);
  17234. this.height -= oldHeight - child.height;
  17235. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  17236. if ((n -= rm) == 0) { break }
  17237. at = 0;
  17238. } else { at -= sz; }
  17239. }
  17240. // If the result is smaller than 25 lines, ensure that it is a
  17241. // single leaf node.
  17242. if (this.size - n < 25 &&
  17243. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  17244. var lines = [];
  17245. this.collapse(lines);
  17246. this.children = [new LeafChunk(lines)];
  17247. this.children[0].parent = this;
  17248. }
  17249. },
  17250. collapse: function(lines) {
  17251. for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  17252. },
  17253. insertInner: function(at, lines, height) {
  17254. this.size += lines.length;
  17255. this.height += height;
  17256. for (var i = 0; i < this.children.length; ++i) {
  17257. var child = this.children[i], sz = child.chunkSize();
  17258. if (at <= sz) {
  17259. child.insertInner(at, lines, height);
  17260. if (child.lines && child.lines.length > 50) {
  17261. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  17262. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  17263. var remaining = child.lines.length % 25 + 25;
  17264. for (var pos = remaining; pos < child.lines.length;) {
  17265. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  17266. child.height -= leaf.height;
  17267. this.children.splice(++i, 0, leaf);
  17268. leaf.parent = this;
  17269. }
  17270. child.lines = child.lines.slice(0, remaining);
  17271. this.maybeSpill();
  17272. }
  17273. break
  17274. }
  17275. at -= sz;
  17276. }
  17277. },
  17278. // When a node has grown, check whether it should be split.
  17279. maybeSpill: function() {
  17280. if (this.children.length <= 10) { return }
  17281. var me = this;
  17282. do {
  17283. var spilled = me.children.splice(me.children.length - 5, 5);
  17284. var sibling = new BranchChunk(spilled);
  17285. if (!me.parent) { // Become the parent node
  17286. var copy = new BranchChunk(me.children);
  17287. copy.parent = me;
  17288. me.children = [copy, sibling];
  17289. me = copy;
  17290. } else {
  17291. me.size -= sibling.size;
  17292. me.height -= sibling.height;
  17293. var myIndex = indexOf(me.parent.children, me);
  17294. me.parent.children.splice(myIndex + 1, 0, sibling);
  17295. }
  17296. sibling.parent = me.parent;
  17297. } while (me.children.length > 10)
  17298. me.parent.maybeSpill();
  17299. },
  17300. iterN: function(at, n, op) {
  17301. for (var i = 0; i < this.children.length; ++i) {
  17302. var child = this.children[i], sz = child.chunkSize();
  17303. if (at < sz) {
  17304. var used = Math.min(n, sz - at);
  17305. if (child.iterN(at, used, op)) { return true }
  17306. if ((n -= used) == 0) { break }
  17307. at = 0;
  17308. } else { at -= sz; }
  17309. }
  17310. }
  17311. };
  17312. // Line widgets are block elements displayed above or below a line.
  17313. var LineWidget = function(doc, node, options) {
  17314. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  17315. { this[opt] = options[opt]; } } }
  17316. this.doc = doc;
  17317. this.node = node;
  17318. };
  17319. LineWidget.prototype.clear = function () {
  17320. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  17321. if (no == null || !ws) { return }
  17322. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  17323. if (!ws.length) { line.widgets = null; }
  17324. var height = widgetHeight(this);
  17325. updateLineHeight(line, Math.max(0, line.height - height));
  17326. if (cm) {
  17327. runInOp(cm, function () {
  17328. adjustScrollWhenAboveVisible(cm, line, -height);
  17329. regLineChange(cm, no, "widget");
  17330. });
  17331. signalLater(cm, "lineWidgetCleared", cm, this, no);
  17332. }
  17333. };
  17334. LineWidget.prototype.changed = function () {
  17335. var this$1 = this;
  17336. var oldH = this.height, cm = this.doc.cm, line = this.line;
  17337. this.height = null;
  17338. var diff = widgetHeight(this) - oldH;
  17339. if (!diff) { return }
  17340. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  17341. if (cm) {
  17342. runInOp(cm, function () {
  17343. cm.curOp.forceUpdate = true;
  17344. adjustScrollWhenAboveVisible(cm, line, diff);
  17345. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  17346. });
  17347. }
  17348. };
  17349. eventMixin(LineWidget);
  17350. function adjustScrollWhenAboveVisible(cm, line, diff) {
  17351. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  17352. { addToScrollTop(cm, diff); }
  17353. }
  17354. function addLineWidget(doc, handle, node, options) {
  17355. var widget = new LineWidget(doc, node, options);
  17356. var cm = doc.cm;
  17357. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  17358. changeLine(doc, handle, "widget", function (line) {
  17359. var widgets = line.widgets || (line.widgets = []);
  17360. if (widget.insertAt == null) { widgets.push(widget); }
  17361. else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
  17362. widget.line = line;
  17363. if (cm && !lineIsHidden(doc, line)) {
  17364. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  17365. updateLineHeight(line, line.height + widgetHeight(widget));
  17366. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  17367. cm.curOp.forceUpdate = true;
  17368. }
  17369. return true
  17370. });
  17371. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  17372. return widget
  17373. }
  17374. // TEXTMARKERS
  17375. // Created with markText and setBookmark methods. A TextMarker is a
  17376. // handle that can be used to clear or find a marked position in the
  17377. // document. Line objects hold arrays (markedSpans) containing
  17378. // {from, to, marker} object pointing to such marker objects, and
  17379. // indicating that such a marker is present on that line. Multiple
  17380. // lines may point to the same marker when it spans across lines.
  17381. // The spans will have null for their from/to properties when the
  17382. // marker continues beyond the start/end of the line. Markers have
  17383. // links back to the lines they currently touch.
  17384. // Collapsed markers have unique ids, in order to be able to order
  17385. // them, which is needed for uniquely determining an outer marker
  17386. // when they overlap (they may nest, but not partially overlap).
  17387. var nextMarkerId = 0;
  17388. var TextMarker = function(doc, type) {
  17389. this.lines = [];
  17390. this.type = type;
  17391. this.doc = doc;
  17392. this.id = ++nextMarkerId;
  17393. };
  17394. // Clear the marker.
  17395. TextMarker.prototype.clear = function () {
  17396. if (this.explicitlyCleared) { return }
  17397. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  17398. if (withOp) { startOperation(cm); }
  17399. if (hasHandler(this, "clear")) {
  17400. var found = this.find();
  17401. if (found) { signalLater(this, "clear", found.from, found.to); }
  17402. }
  17403. var min = null, max = null;
  17404. for (var i = 0; i < this.lines.length; ++i) {
  17405. var line = this.lines[i];
  17406. var span = getMarkedSpanFor(line.markedSpans, this);
  17407. if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  17408. else if (cm) {
  17409. if (span.to != null) { max = lineNo(line); }
  17410. if (span.from != null) { min = lineNo(line); }
  17411. }
  17412. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  17413. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  17414. { updateLineHeight(line, textHeight(cm.display)); }
  17415. }
  17416. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  17417. var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  17418. if (len > cm.display.maxLineLength) {
  17419. cm.display.maxLine = visual;
  17420. cm.display.maxLineLength = len;
  17421. cm.display.maxLineChanged = true;
  17422. }
  17423. } }
  17424. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  17425. this.lines.length = 0;
  17426. this.explicitlyCleared = true;
  17427. if (this.atomic && this.doc.cantEdit) {
  17428. this.doc.cantEdit = false;
  17429. if (cm) { reCheckSelection(cm.doc); }
  17430. }
  17431. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  17432. if (withOp) { endOperation(cm); }
  17433. if (this.parent) { this.parent.clear(); }
  17434. };
  17435. // Find the position of the marker in the document. Returns a {from,
  17436. // to} object by default. Side can be passed to get a specific side
  17437. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  17438. // Pos objects returned contain a line object, rather than a line
  17439. // number (used to prevent looking up the same line twice).
  17440. TextMarker.prototype.find = function (side, lineObj) {
  17441. if (side == null && this.type == "bookmark") { side = 1; }
  17442. var from, to;
  17443. for (var i = 0; i < this.lines.length; ++i) {
  17444. var line = this.lines[i];
  17445. var span = getMarkedSpanFor(line.markedSpans, this);
  17446. if (span.from != null) {
  17447. from = Pos(lineObj ? line : lineNo(line), span.from);
  17448. if (side == -1) { return from }
  17449. }
  17450. if (span.to != null) {
  17451. to = Pos(lineObj ? line : lineNo(line), span.to);
  17452. if (side == 1) { return to }
  17453. }
  17454. }
  17455. return from && {from: from, to: to}
  17456. };
  17457. // Signals that the marker's widget changed, and surrounding layout
  17458. // should be recomputed.
  17459. TextMarker.prototype.changed = function () {
  17460. var this$1 = this;
  17461. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  17462. if (!pos || !cm) { return }
  17463. runInOp(cm, function () {
  17464. var line = pos.line, lineN = lineNo(pos.line);
  17465. var view = findViewForLine(cm, lineN);
  17466. if (view) {
  17467. clearLineMeasurementCacheFor(view);
  17468. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  17469. }
  17470. cm.curOp.updateMaxLine = true;
  17471. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  17472. var oldHeight = widget.height;
  17473. widget.height = null;
  17474. var dHeight = widgetHeight(widget) - oldHeight;
  17475. if (dHeight)
  17476. { updateLineHeight(line, line.height + dHeight); }
  17477. }
  17478. signalLater(cm, "markerChanged", cm, this$1);
  17479. });
  17480. };
  17481. TextMarker.prototype.attachLine = function (line) {
  17482. if (!this.lines.length && this.doc.cm) {
  17483. var op = this.doc.cm.curOp;
  17484. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  17485. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  17486. }
  17487. this.lines.push(line);
  17488. };
  17489. TextMarker.prototype.detachLine = function (line) {
  17490. this.lines.splice(indexOf(this.lines, line), 1);
  17491. if (!this.lines.length && this.doc.cm) {
  17492. var op = this.doc.cm.curOp
  17493. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  17494. }
  17495. };
  17496. eventMixin(TextMarker);
  17497. // Create a marker, wire it up to the right lines, and
  17498. function markText(doc, from, to, options, type) {
  17499. // Shared markers (across linked documents) are handled separately
  17500. // (markTextShared will call out to this again, once per
  17501. // document).
  17502. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  17503. // Ensure we are in an operation.
  17504. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  17505. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  17506. if (options) { copyObj(options, marker, false); }
  17507. // Don't connect empty markers unless clearWhenEmpty is false
  17508. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  17509. { return marker }
  17510. if (marker.replacedWith) {
  17511. // Showing up as a widget implies collapsed (widget replaces text)
  17512. marker.collapsed = true;
  17513. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  17514. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  17515. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  17516. }
  17517. if (marker.collapsed) {
  17518. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  17519. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  17520. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  17521. seeCollapsedSpans();
  17522. }
  17523. if (marker.addToHistory)
  17524. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  17525. var curLine = from.line, cm = doc.cm, updateMaxLine;
  17526. doc.iter(curLine, to.line + 1, function (line) {
  17527. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  17528. { updateMaxLine = true; }
  17529. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  17530. addMarkedSpan(line, new MarkedSpan(marker,
  17531. curLine == from.line ? from.ch : null,
  17532. curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
  17533. ++curLine;
  17534. });
  17535. // lineIsHidden depends on the presence of the spans, so needs a second pass
  17536. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  17537. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  17538. }); }
  17539. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  17540. if (marker.readOnly) {
  17541. seeReadOnlySpans();
  17542. if (doc.history.done.length || doc.history.undone.length)
  17543. { doc.clearHistory(); }
  17544. }
  17545. if (marker.collapsed) {
  17546. marker.id = ++nextMarkerId;
  17547. marker.atomic = true;
  17548. }
  17549. if (cm) {
  17550. // Sync editor state
  17551. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  17552. if (marker.collapsed)
  17553. { regChange(cm, from.line, to.line + 1); }
  17554. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  17555. marker.attributes || marker.title)
  17556. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  17557. if (marker.atomic) { reCheckSelection(cm.doc); }
  17558. signalLater(cm, "markerAdded", cm, marker);
  17559. }
  17560. return marker
  17561. }
  17562. // SHARED TEXTMARKERS
  17563. // A shared marker spans multiple linked documents. It is
  17564. // implemented as a meta-marker-object controlling multiple normal
  17565. // markers.
  17566. var SharedTextMarker = function(markers, primary) {
  17567. this.markers = markers;
  17568. this.primary = primary;
  17569. for (var i = 0; i < markers.length; ++i)
  17570. { markers[i].parent = this; }
  17571. };
  17572. SharedTextMarker.prototype.clear = function () {
  17573. if (this.explicitlyCleared) { return }
  17574. this.explicitlyCleared = true;
  17575. for (var i = 0; i < this.markers.length; ++i)
  17576. { this.markers[i].clear(); }
  17577. signalLater(this, "clear");
  17578. };
  17579. SharedTextMarker.prototype.find = function (side, lineObj) {
  17580. return this.primary.find(side, lineObj)
  17581. };
  17582. eventMixin(SharedTextMarker);
  17583. function markTextShared(doc, from, to, options, type) {
  17584. options = copyObj(options);
  17585. options.shared = false;
  17586. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  17587. var widget = options.widgetNode;
  17588. linkedDocs(doc, function (doc) {
  17589. if (widget) { options.widgetNode = widget.cloneNode(true); }
  17590. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  17591. for (var i = 0; i < doc.linked.length; ++i)
  17592. { if (doc.linked[i].isParent) { return } }
  17593. primary = lst(markers);
  17594. });
  17595. return new SharedTextMarker(markers, primary)
  17596. }
  17597. function findSharedMarkers(doc) {
  17598. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  17599. }
  17600. function copySharedMarkers(doc, markers) {
  17601. for (var i = 0; i < markers.length; i++) {
  17602. var marker = markers[i], pos = marker.find();
  17603. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  17604. if (cmp(mFrom, mTo)) {
  17605. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  17606. marker.markers.push(subMark);
  17607. subMark.parent = marker;
  17608. }
  17609. }
  17610. }
  17611. function detachSharedMarkers(markers) {
  17612. var loop = function ( i ) {
  17613. var marker = markers[i], linked = [marker.primary.doc];
  17614. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  17615. for (var j = 0; j < marker.markers.length; j++) {
  17616. var subMarker = marker.markers[j];
  17617. if (indexOf(linked, subMarker.doc) == -1) {
  17618. subMarker.parent = null;
  17619. marker.markers.splice(j--, 1);
  17620. }
  17621. }
  17622. };
  17623. for (var i = 0; i < markers.length; i++) loop( i );
  17624. }
  17625. var nextDocId = 0;
  17626. var Doc = function(text, mode, firstLine, lineSep, direction) {
  17627. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  17628. if (firstLine == null) { firstLine = 0; }
  17629. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  17630. this.first = firstLine;
  17631. this.scrollTop = this.scrollLeft = 0;
  17632. this.cantEdit = false;
  17633. this.cleanGeneration = 1;
  17634. this.modeFrontier = this.highlightFrontier = firstLine;
  17635. var start = Pos(firstLine, 0);
  17636. this.sel = simpleSelection(start);
  17637. this.history = new History(null);
  17638. this.id = ++nextDocId;
  17639. this.modeOption = mode;
  17640. this.lineSep = lineSep;
  17641. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  17642. this.extend = false;
  17643. if (typeof text == "string") { text = this.splitLines(text); }
  17644. updateDoc(this, {from: start, to: start, text: text});
  17645. setSelection(this, simpleSelection(start), sel_dontScroll);
  17646. };
  17647. Doc.prototype = createObj(BranchChunk.prototype, {
  17648. constructor: Doc,
  17649. // Iterate over the document. Supports two forms -- with only one
  17650. // argument, it calls that for each line in the document. With
  17651. // three, it iterates over the range given by the first two (with
  17652. // the second being non-inclusive).
  17653. iter: function(from, to, op) {
  17654. if (op) { this.iterN(from - this.first, to - from, op); }
  17655. else { this.iterN(this.first, this.first + this.size, from); }
  17656. },
  17657. // Non-public interface for adding and removing lines.
  17658. insert: function(at, lines) {
  17659. var height = 0;
  17660. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  17661. this.insertInner(at - this.first, lines, height);
  17662. },
  17663. remove: function(at, n) { this.removeInner(at - this.first, n); },
  17664. // From here, the methods are part of the public interface. Most
  17665. // are also available from CodeMirror (editor) instances.
  17666. getValue: function(lineSep) {
  17667. var lines = getLines(this, this.first, this.first + this.size);
  17668. if (lineSep === false) { return lines }
  17669. return lines.join(lineSep || this.lineSeparator())
  17670. },
  17671. setValue: docMethodOp(function(code) {
  17672. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  17673. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  17674. text: this.splitLines(code), origin: "setValue", full: true}, true);
  17675. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  17676. setSelection(this, simpleSelection(top), sel_dontScroll);
  17677. }),
  17678. replaceRange: function(code, from, to, origin) {
  17679. from = clipPos(this, from);
  17680. to = to ? clipPos(this, to) : from;
  17681. replaceRange(this, code, from, to, origin);
  17682. },
  17683. getRange: function(from, to, lineSep) {
  17684. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  17685. if (lineSep === false) { return lines }
  17686. if (lineSep === '') { return lines.join('') }
  17687. return lines.join(lineSep || this.lineSeparator())
  17688. },
  17689. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  17690. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  17691. getLineNumber: function(line) {return lineNo(line)},
  17692. getLineHandleVisualStart: function(line) {
  17693. if (typeof line == "number") { line = getLine(this, line); }
  17694. return visualLine(line)
  17695. },
  17696. lineCount: function() {return this.size},
  17697. firstLine: function() {return this.first},
  17698. lastLine: function() {return this.first + this.size - 1},
  17699. clipPos: function(pos) {return clipPos(this, pos)},
  17700. getCursor: function(start) {
  17701. var range = this.sel.primary(), pos;
  17702. if (start == null || start == "head") { pos = range.head; }
  17703. else if (start == "anchor") { pos = range.anchor; }
  17704. else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  17705. else { pos = range.from(); }
  17706. return pos
  17707. },
  17708. listSelections: function() { return this.sel.ranges },
  17709. somethingSelected: function() {return this.sel.somethingSelected()},
  17710. setCursor: docMethodOp(function(line, ch, options) {
  17711. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  17712. }),
  17713. setSelection: docMethodOp(function(anchor, head, options) {
  17714. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  17715. }),
  17716. extendSelection: docMethodOp(function(head, other, options) {
  17717. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  17718. }),
  17719. extendSelections: docMethodOp(function(heads, options) {
  17720. extendSelections(this, clipPosArray(this, heads), options);
  17721. }),
  17722. extendSelectionsBy: docMethodOp(function(f, options) {
  17723. var heads = map(this.sel.ranges, f);
  17724. extendSelections(this, clipPosArray(this, heads), options);
  17725. }),
  17726. setSelections: docMethodOp(function(ranges, primary, options) {
  17727. if (!ranges.length) { return }
  17728. var out = [];
  17729. for (var i = 0; i < ranges.length; i++)
  17730. { out[i] = new Range(clipPos(this, ranges[i].anchor),
  17731. clipPos(this, ranges[i].head || ranges[i].anchor)); }
  17732. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  17733. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  17734. }),
  17735. addSelection: docMethodOp(function(anchor, head, options) {
  17736. var ranges = this.sel.ranges.slice(0);
  17737. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  17738. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  17739. }),
  17740. getSelection: function(lineSep) {
  17741. var ranges = this.sel.ranges, lines;
  17742. for (var i = 0; i < ranges.length; i++) {
  17743. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  17744. lines = lines ? lines.concat(sel) : sel;
  17745. }
  17746. if (lineSep === false) { return lines }
  17747. else { return lines.join(lineSep || this.lineSeparator()) }
  17748. },
  17749. getSelections: function(lineSep) {
  17750. var parts = [], ranges = this.sel.ranges;
  17751. for (var i = 0; i < ranges.length; i++) {
  17752. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  17753. if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  17754. parts[i] = sel;
  17755. }
  17756. return parts
  17757. },
  17758. replaceSelection: function(code, collapse, origin) {
  17759. var dup = [];
  17760. for (var i = 0; i < this.sel.ranges.length; i++)
  17761. { dup[i] = code; }
  17762. this.replaceSelections(dup, collapse, origin || "+input");
  17763. },
  17764. replaceSelections: docMethodOp(function(code, collapse, origin) {
  17765. var changes = [], sel = this.sel;
  17766. for (var i = 0; i < sel.ranges.length; i++) {
  17767. var range = sel.ranges[i];
  17768. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  17769. }
  17770. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  17771. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  17772. { makeChange(this, changes[i$1]); }
  17773. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  17774. else if (this.cm) { ensureCursorVisible(this.cm); }
  17775. }),
  17776. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  17777. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  17778. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  17779. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  17780. setExtending: function(val) {this.extend = val;},
  17781. getExtending: function() {return this.extend},
  17782. historySize: function() {
  17783. var hist = this.history, done = 0, undone = 0;
  17784. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  17785. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  17786. return {undo: done, redo: undone}
  17787. },
  17788. clearHistory: function() {
  17789. var this$1 = this;
  17790. this.history = new History(this.history);
  17791. linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  17792. },
  17793. markClean: function() {
  17794. this.cleanGeneration = this.changeGeneration(true);
  17795. },
  17796. changeGeneration: function(forceSplit) {
  17797. if (forceSplit)
  17798. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  17799. return this.history.generation
  17800. },
  17801. isClean: function (gen) {
  17802. return this.history.generation == (gen || this.cleanGeneration)
  17803. },
  17804. getHistory: function() {
  17805. return {done: copyHistoryArray(this.history.done),
  17806. undone: copyHistoryArray(this.history.undone)}
  17807. },
  17808. setHistory: function(histData) {
  17809. var hist = this.history = new History(this.history);
  17810. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  17811. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  17812. },
  17813. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  17814. return changeLine(this, line, "gutter", function (line) {
  17815. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  17816. markers[gutterID] = value;
  17817. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  17818. return true
  17819. })
  17820. }),
  17821. clearGutter: docMethodOp(function(gutterID) {
  17822. var this$1 = this;
  17823. this.iter(function (line) {
  17824. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  17825. changeLine(this$1, line, "gutter", function () {
  17826. line.gutterMarkers[gutterID] = null;
  17827. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  17828. return true
  17829. });
  17830. }
  17831. });
  17832. }),
  17833. lineInfo: function(line) {
  17834. var n;
  17835. if (typeof line == "number") {
  17836. if (!isLine(this, line)) { return null }
  17837. n = line;
  17838. line = getLine(this, line);
  17839. if (!line) { return null }
  17840. } else {
  17841. n = lineNo(line);
  17842. if (n == null) { return null }
  17843. }
  17844. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  17845. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  17846. widgets: line.widgets}
  17847. },
  17848. addLineClass: docMethodOp(function(handle, where, cls) {
  17849. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  17850. var prop = where == "text" ? "textClass"
  17851. : where == "background" ? "bgClass"
  17852. : where == "gutter" ? "gutterClass" : "wrapClass";
  17853. if (!line[prop]) { line[prop] = cls; }
  17854. else if (classTest(cls).test(line[prop])) { return false }
  17855. else { line[prop] += " " + cls; }
  17856. return true
  17857. })
  17858. }),
  17859. removeLineClass: docMethodOp(function(handle, where, cls) {
  17860. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  17861. var prop = where == "text" ? "textClass"
  17862. : where == "background" ? "bgClass"
  17863. : where == "gutter" ? "gutterClass" : "wrapClass";
  17864. var cur = line[prop];
  17865. if (!cur) { return false }
  17866. else if (cls == null) { line[prop] = null; }
  17867. else {
  17868. var found = cur.match(classTest(cls));
  17869. if (!found) { return false }
  17870. var end = found.index + found[0].length;
  17871. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  17872. }
  17873. return true
  17874. })
  17875. }),
  17876. addLineWidget: docMethodOp(function(handle, node, options) {
  17877. return addLineWidget(this, handle, node, options)
  17878. }),
  17879. removeLineWidget: function(widget) { widget.clear(); },
  17880. markText: function(from, to, options) {
  17881. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  17882. },
  17883. setBookmark: function(pos, options) {
  17884. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  17885. insertLeft: options && options.insertLeft,
  17886. clearWhenEmpty: false, shared: options && options.shared,
  17887. handleMouseEvents: options && options.handleMouseEvents};
  17888. pos = clipPos(this, pos);
  17889. return markText(this, pos, pos, realOpts, "bookmark")
  17890. },
  17891. findMarksAt: function(pos) {
  17892. pos = clipPos(this, pos);
  17893. var markers = [], spans = getLine(this, pos.line).markedSpans;
  17894. if (spans) { for (var i = 0; i < spans.length; ++i) {
  17895. var span = spans[i];
  17896. if ((span.from == null || span.from <= pos.ch) &&
  17897. (span.to == null || span.to >= pos.ch))
  17898. { markers.push(span.marker.parent || span.marker); }
  17899. } }
  17900. return markers
  17901. },
  17902. findMarks: function(from, to, filter) {
  17903. from = clipPos(this, from); to = clipPos(this, to);
  17904. var found = [], lineNo = from.line;
  17905. this.iter(from.line, to.line + 1, function (line) {
  17906. var spans = line.markedSpans;
  17907. if (spans) { for (var i = 0; i < spans.length; i++) {
  17908. var span = spans[i];
  17909. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  17910. span.from == null && lineNo != from.line ||
  17911. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  17912. (!filter || filter(span.marker)))
  17913. { found.push(span.marker.parent || span.marker); }
  17914. } }
  17915. ++lineNo;
  17916. });
  17917. return found
  17918. },
  17919. getAllMarks: function() {
  17920. var markers = [];
  17921. this.iter(function (line) {
  17922. var sps = line.markedSpans;
  17923. if (sps) { for (var i = 0; i < sps.length; ++i)
  17924. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  17925. });
  17926. return markers
  17927. },
  17928. posFromIndex: function(off) {
  17929. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  17930. this.iter(function (line) {
  17931. var sz = line.text.length + sepSize;
  17932. if (sz > off) { ch = off; return true }
  17933. off -= sz;
  17934. ++lineNo;
  17935. });
  17936. return clipPos(this, Pos(lineNo, ch))
  17937. },
  17938. indexFromPos: function (coords) {
  17939. coords = clipPos(this, coords);
  17940. var index = coords.ch;
  17941. if (coords.line < this.first || coords.ch < 0) { return 0 }
  17942. var sepSize = this.lineSeparator().length;
  17943. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  17944. index += line.text.length + sepSize;
  17945. });
  17946. return index
  17947. },
  17948. copy: function(copyHistory) {
  17949. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  17950. this.modeOption, this.first, this.lineSep, this.direction);
  17951. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  17952. doc.sel = this.sel;
  17953. doc.extend = false;
  17954. if (copyHistory) {
  17955. doc.history.undoDepth = this.history.undoDepth;
  17956. doc.setHistory(this.getHistory());
  17957. }
  17958. return doc
  17959. },
  17960. linkedDoc: function(options) {
  17961. if (!options) { options = {}; }
  17962. var from = this.first, to = this.first + this.size;
  17963. if (options.from != null && options.from > from) { from = options.from; }
  17964. if (options.to != null && options.to < to) { to = options.to; }
  17965. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  17966. if (options.sharedHist) { copy.history = this.history
  17967. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  17968. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  17969. copySharedMarkers(copy, findSharedMarkers(this));
  17970. return copy
  17971. },
  17972. unlinkDoc: function(other) {
  17973. if (other instanceof CodeMirror) { other = other.doc; }
  17974. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  17975. var link = this.linked[i];
  17976. if (link.doc != other) { continue }
  17977. this.linked.splice(i, 1);
  17978. other.unlinkDoc(this);
  17979. detachSharedMarkers(findSharedMarkers(this));
  17980. break
  17981. } }
  17982. // If the histories were shared, split them again
  17983. if (other.history == this.history) {
  17984. var splitIds = [other.id];
  17985. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  17986. other.history = new History(null);
  17987. other.history.done = copyHistoryArray(this.history.done, splitIds);
  17988. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  17989. }
  17990. },
  17991. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  17992. getMode: function() {return this.mode},
  17993. getEditor: function() {return this.cm},
  17994. splitLines: function(str) {
  17995. if (this.lineSep) { return str.split(this.lineSep) }
  17996. return splitLinesAuto(str)
  17997. },
  17998. lineSeparator: function() { return this.lineSep || "\n" },
  17999. setDirection: docMethodOp(function (dir) {
  18000. if (dir != "rtl") { dir = "ltr"; }
  18001. if (dir == this.direction) { return }
  18002. this.direction = dir;
  18003. this.iter(function (line) { return line.order = null; });
  18004. if (this.cm) { directionChanged(this.cm); }
  18005. })
  18006. });
  18007. // Public alias.
  18008. Doc.prototype.eachLine = Doc.prototype.iter;
  18009. // Kludge to work around strange IE behavior where it'll sometimes
  18010. // re-fire a series of drag-related events right after the drop (#1551)
  18011. var lastDrop = 0;
  18012. function onDrop(e) {
  18013. var cm = this;
  18014. clearDragCursor(cm);
  18015. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  18016. { return }
  18017. e_preventDefault(e);
  18018. if (ie) { lastDrop = +new Date; }
  18019. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  18020. if (!pos || cm.isReadOnly()) { return }
  18021. // Might be a file drop, in which case we simply extract the text
  18022. // and insert it.
  18023. if (files && files.length && window.FileReader && window.File) {
  18024. var n = files.length, text = Array(n), read = 0;
  18025. var markAsReadAndPasteIfAllFilesAreRead = function () {
  18026. if (++read == n) {
  18027. operation(cm, function () {
  18028. pos = clipPos(cm.doc, pos);
  18029. var change = {from: pos, to: pos,
  18030. text: cm.doc.splitLines(
  18031. text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  18032. origin: "paste"};
  18033. makeChange(cm.doc, change);
  18034. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  18035. })();
  18036. }
  18037. };
  18038. var readTextFromFile = function (file, i) {
  18039. if (cm.options.allowDropFileTypes &&
  18040. indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  18041. markAsReadAndPasteIfAllFilesAreRead();
  18042. return
  18043. }
  18044. var reader = new FileReader;
  18045. reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  18046. reader.onload = function () {
  18047. var content = reader.result;
  18048. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  18049. markAsReadAndPasteIfAllFilesAreRead();
  18050. return
  18051. }
  18052. text[i] = content;
  18053. markAsReadAndPasteIfAllFilesAreRead();
  18054. };
  18055. reader.readAsText(file);
  18056. };
  18057. for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  18058. } else { // Normal drop
  18059. // Don't do a replace if the drop happened inside of the selected text.
  18060. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  18061. cm.state.draggingText(e);
  18062. // Ensure the editor is re-focused
  18063. setTimeout(function () { return cm.display.input.focus(); }, 20);
  18064. return
  18065. }
  18066. try {
  18067. var text$1 = e.dataTransfer.getData("Text");
  18068. if (text$1) {
  18069. var selected;
  18070. if (cm.state.draggingText && !cm.state.draggingText.copy)
  18071. { selected = cm.listSelections(); }
  18072. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  18073. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  18074. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  18075. cm.replaceSelection(text$1, "around", "paste");
  18076. cm.display.input.focus();
  18077. }
  18078. }
  18079. catch(e$1){}
  18080. }
  18081. }
  18082. function onDragStart(cm, e) {
  18083. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  18084. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  18085. e.dataTransfer.setData("Text", cm.getSelection());
  18086. e.dataTransfer.effectAllowed = "copyMove";
  18087. // Use dummy image instead of default browsers image.
  18088. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  18089. if (e.dataTransfer.setDragImage && !safari) {
  18090. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  18091. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  18092. if (presto) {
  18093. img.width = img.height = 1;
  18094. cm.display.wrapper.appendChild(img);
  18095. // Force a relayout, or Opera won't use our image for some obscure reason
  18096. img._top = img.offsetTop;
  18097. }
  18098. e.dataTransfer.setDragImage(img, 0, 0);
  18099. if (presto) { img.parentNode.removeChild(img); }
  18100. }
  18101. }
  18102. function onDragOver(cm, e) {
  18103. var pos = posFromMouse(cm, e);
  18104. if (!pos) { return }
  18105. var frag = document.createDocumentFragment();
  18106. drawSelectionCursor(cm, pos, frag);
  18107. if (!cm.display.dragCursor) {
  18108. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  18109. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  18110. }
  18111. removeChildrenAndAdd(cm.display.dragCursor, frag);
  18112. }
  18113. function clearDragCursor(cm) {
  18114. if (cm.display.dragCursor) {
  18115. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  18116. cm.display.dragCursor = null;
  18117. }
  18118. }
  18119. // These must be handled carefully, because naively registering a
  18120. // handler for each editor will cause the editors to never be
  18121. // garbage collected.
  18122. function forEachCodeMirror(f) {
  18123. if (!document.getElementsByClassName) { return }
  18124. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  18125. for (var i = 0; i < byClass.length; i++) {
  18126. var cm = byClass[i].CodeMirror;
  18127. if (cm) { editors.push(cm); }
  18128. }
  18129. if (editors.length) { editors[0].operation(function () {
  18130. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  18131. }); }
  18132. }
  18133. var globalsRegistered = false;
  18134. function ensureGlobalHandlers() {
  18135. if (globalsRegistered) { return }
  18136. registerGlobalHandlers();
  18137. globalsRegistered = true;
  18138. }
  18139. function registerGlobalHandlers() {
  18140. // When the window resizes, we need to refresh active editors.
  18141. var resizeTimer;
  18142. on(window, "resize", function () {
  18143. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  18144. resizeTimer = null;
  18145. forEachCodeMirror(onResize);
  18146. }, 100); }
  18147. });
  18148. // When the window loses focus, we want to show the editor as blurred
  18149. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  18150. }
  18151. // Called when the window resizes
  18152. function onResize(cm) {
  18153. var d = cm.display;
  18154. // Might be a text scaling operation, clear size caches.
  18155. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  18156. d.scrollbarsClipped = false;
  18157. cm.setSize();
  18158. }
  18159. var keyNames = {
  18160. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  18161. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  18162. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  18163. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  18164. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  18165. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  18166. 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  18167. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  18168. };
  18169. // Number keys
  18170. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  18171. // Alphabetic keys
  18172. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  18173. // Function keys
  18174. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  18175. var keyMap = {};
  18176. keyMap.basic = {
  18177. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  18178. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  18179. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  18180. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  18181. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  18182. "Esc": "singleSelection"
  18183. };
  18184. // Note that the save and find-related commands aren't defined by
  18185. // default. User code or addons can define them. Unknown commands
  18186. // are simply ignored.
  18187. keyMap.pcDefault = {
  18188. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  18189. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  18190. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  18191. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  18192. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  18193. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  18194. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  18195. "fallthrough": "basic"
  18196. };
  18197. // Very basic readline/emacs-style bindings, which are standard on Mac.
  18198. keyMap.emacsy = {
  18199. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  18200. "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
  18201. "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
  18202. "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
  18203. };
  18204. keyMap.macDefault = {
  18205. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  18206. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  18207. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  18208. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  18209. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  18210. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  18211. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  18212. "fallthrough": ["basic", "emacsy"]
  18213. };
  18214. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  18215. // KEYMAP DISPATCH
  18216. function normalizeKeyName(name) {
  18217. var parts = name.split(/-(?!$)/);
  18218. name = parts[parts.length - 1];
  18219. var alt, ctrl, shift, cmd;
  18220. for (var i = 0; i < parts.length - 1; i++) {
  18221. var mod = parts[i];
  18222. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  18223. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  18224. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  18225. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  18226. else { throw new Error("Unrecognized modifier name: " + mod) }
  18227. }
  18228. if (alt) { name = "Alt-" + name; }
  18229. if (ctrl) { name = "Ctrl-" + name; }
  18230. if (cmd) { name = "Cmd-" + name; }
  18231. if (shift) { name = "Shift-" + name; }
  18232. return name
  18233. }
  18234. // This is a kludge to keep keymaps mostly working as raw objects
  18235. // (backwards compatibility) while at the same time support features
  18236. // like normalization and multi-stroke key bindings. It compiles a
  18237. // new normalized keymap, and then updates the old object to reflect
  18238. // this.
  18239. function normalizeKeyMap(keymap) {
  18240. var copy = {};
  18241. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  18242. var value = keymap[keyname];
  18243. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  18244. if (value == "...") { delete keymap[keyname]; continue }
  18245. var keys = map(keyname.split(" "), normalizeKeyName);
  18246. for (var i = 0; i < keys.length; i++) {
  18247. var val = (void 0), name = (void 0);
  18248. if (i == keys.length - 1) {
  18249. name = keys.join(" ");
  18250. val = value;
  18251. } else {
  18252. name = keys.slice(0, i + 1).join(" ");
  18253. val = "...";
  18254. }
  18255. var prev = copy[name];
  18256. if (!prev) { copy[name] = val; }
  18257. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  18258. }
  18259. delete keymap[keyname];
  18260. } }
  18261. for (var prop in copy) { keymap[prop] = copy[prop]; }
  18262. return keymap
  18263. }
  18264. function lookupKey(key, map, handle, context) {
  18265. map = getKeyMap(map);
  18266. var found = map.call ? map.call(key, context) : map[key];
  18267. if (found === false) { return "nothing" }
  18268. if (found === "...") { return "multi" }
  18269. if (found != null && handle(found)) { return "handled" }
  18270. if (map.fallthrough) {
  18271. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  18272. { return lookupKey(key, map.fallthrough, handle, context) }
  18273. for (var i = 0; i < map.fallthrough.length; i++) {
  18274. var result = lookupKey(key, map.fallthrough[i], handle, context);
  18275. if (result) { return result }
  18276. }
  18277. }
  18278. }
  18279. // Modifier key presses don't count as 'real' key presses for the
  18280. // purpose of keymap fallthrough.
  18281. function isModifierKey(value) {
  18282. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  18283. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  18284. }
  18285. function addModifierNames(name, event, noShift) {
  18286. var base = name;
  18287. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  18288. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  18289. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
  18290. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  18291. return name
  18292. }
  18293. // Look up the name of a key as indicated by an event object.
  18294. function keyName(event, noShift) {
  18295. if (presto && event.keyCode == 34 && event["char"]) { return false }
  18296. var name = keyNames[event.keyCode];
  18297. if (name == null || event.altGraphKey) { return false }
  18298. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  18299. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  18300. if (event.keyCode == 3 && event.code) { name = event.code; }
  18301. return addModifierNames(name, event, noShift)
  18302. }
  18303. function getKeyMap(val) {
  18304. return typeof val == "string" ? keyMap[val] : val
  18305. }
  18306. // Helper for deleting text near the selection(s), used to implement
  18307. // backspace, delete, and similar functionality.
  18308. function deleteNearSelection(cm, compute) {
  18309. var ranges = cm.doc.sel.ranges, kill = [];
  18310. // Build up a set of ranges to kill first, merging overlapping
  18311. // ranges.
  18312. for (var i = 0; i < ranges.length; i++) {
  18313. var toKill = compute(ranges[i]);
  18314. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  18315. var replaced = kill.pop();
  18316. if (cmp(replaced.from, toKill.from) < 0) {
  18317. toKill.from = replaced.from;
  18318. break
  18319. }
  18320. }
  18321. kill.push(toKill);
  18322. }
  18323. // Next, remove those actual ranges.
  18324. runInOp(cm, function () {
  18325. for (var i = kill.length - 1; i >= 0; i--)
  18326. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  18327. ensureCursorVisible(cm);
  18328. });
  18329. }
  18330. function moveCharLogically(line, ch, dir) {
  18331. var target = skipExtendingChars(line.text, ch + dir, dir);
  18332. return target < 0 || target > line.text.length ? null : target
  18333. }
  18334. function moveLogically(line, start, dir) {
  18335. var ch = moveCharLogically(line, start.ch, dir);
  18336. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  18337. }
  18338. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  18339. if (visually) {
  18340. if (cm.doc.direction == "rtl") { dir = -dir; }
  18341. var order = getOrder(lineObj, cm.doc.direction);
  18342. if (order) {
  18343. var part = dir < 0 ? lst(order) : order[0];
  18344. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  18345. var sticky = moveInStorageOrder ? "after" : "before";
  18346. var ch;
  18347. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  18348. // it could be that the last bidi part is not on the last visual line,
  18349. // since visual lines contain content order-consecutive chunks.
  18350. // Thus, in rtl, we are looking for the first (content-order) character
  18351. // in the rtl chunk that is on the last line (that is, the same line
  18352. // as the last (content-order) character).
  18353. if (part.level > 0 || cm.doc.direction == "rtl") {
  18354. var prep = prepareMeasureForLine(cm, lineObj);
  18355. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  18356. var targetTop = measureCharPrepared(cm, prep, ch).top;
  18357. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  18358. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  18359. } else { ch = dir < 0 ? part.to : part.from; }
  18360. return new Pos(lineNo, ch, sticky)
  18361. }
  18362. }
  18363. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  18364. }
  18365. function moveVisually(cm, line, start, dir) {
  18366. var bidi = getOrder(line, cm.doc.direction);
  18367. if (!bidi) { return moveLogically(line, start, dir) }
  18368. if (start.ch >= line.text.length) {
  18369. start.ch = line.text.length;
  18370. start.sticky = "before";
  18371. } else if (start.ch <= 0) {
  18372. start.ch = 0;
  18373. start.sticky = "after";
  18374. }
  18375. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  18376. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  18377. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  18378. // nothing interesting happens.
  18379. return moveLogically(line, start, dir)
  18380. }
  18381. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  18382. var prep;
  18383. var getWrappedLineExtent = function (ch) {
  18384. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  18385. prep = prep || prepareMeasureForLine(cm, line);
  18386. return wrappedLineExtentChar(cm, line, prep, ch)
  18387. };
  18388. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  18389. if (cm.doc.direction == "rtl" || part.level == 1) {
  18390. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  18391. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  18392. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  18393. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  18394. var sticky = moveInStorageOrder ? "before" : "after";
  18395. return new Pos(start.line, ch, sticky)
  18396. }
  18397. }
  18398. // Case 3: Could not move within this bidi part in this visual line, so leave
  18399. // the current bidi part
  18400. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  18401. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  18402. ? new Pos(start.line, mv(ch, 1), "before")
  18403. : new Pos(start.line, ch, "after"); };
  18404. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  18405. var part = bidi[partPos];
  18406. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  18407. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  18408. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  18409. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  18410. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  18411. }
  18412. };
  18413. // Case 3a: Look for other bidi parts on the same visual line
  18414. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  18415. if (res) { return res }
  18416. // Case 3b: Look for other bidi parts on the next visual line
  18417. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  18418. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  18419. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  18420. if (res) { return res }
  18421. }
  18422. // Case 4: Nowhere to move
  18423. return null
  18424. }
  18425. // Commands are parameter-less actions that can be performed on an
  18426. // editor, mostly used for keybindings.
  18427. var commands = {
  18428. selectAll: selectAll,
  18429. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  18430. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  18431. if (range.empty()) {
  18432. var len = getLine(cm.doc, range.head.line).text.length;
  18433. if (range.head.ch == len && range.head.line < cm.lastLine())
  18434. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  18435. else
  18436. { return {from: range.head, to: Pos(range.head.line, len)} }
  18437. } else {
  18438. return {from: range.from(), to: range.to()}
  18439. }
  18440. }); },
  18441. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  18442. from: Pos(range.from().line, 0),
  18443. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  18444. }); }); },
  18445. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  18446. from: Pos(range.from().line, 0), to: range.from()
  18447. }); }); },
  18448. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  18449. var top = cm.charCoords(range.head, "div").top + 5;
  18450. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  18451. return {from: leftPos, to: range.from()}
  18452. }); },
  18453. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  18454. var top = cm.charCoords(range.head, "div").top + 5;
  18455. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  18456. return {from: range.from(), to: rightPos }
  18457. }); },
  18458. undo: function (cm) { return cm.undo(); },
  18459. redo: function (cm) { return cm.redo(); },
  18460. undoSelection: function (cm) { return cm.undoSelection(); },
  18461. redoSelection: function (cm) { return cm.redoSelection(); },
  18462. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  18463. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  18464. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  18465. {origin: "+move", bias: 1}
  18466. ); },
  18467. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  18468. {origin: "+move", bias: 1}
  18469. ); },
  18470. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  18471. {origin: "+move", bias: -1}
  18472. ); },
  18473. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  18474. var top = cm.cursorCoords(range.head, "div").top + 5;
  18475. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  18476. }, sel_move); },
  18477. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  18478. var top = cm.cursorCoords(range.head, "div").top + 5;
  18479. return cm.coordsChar({left: 0, top: top}, "div")
  18480. }, sel_move); },
  18481. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  18482. var top = cm.cursorCoords(range.head, "div").top + 5;
  18483. var pos = cm.coordsChar({left: 0, top: top}, "div");
  18484. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  18485. return pos
  18486. }, sel_move); },
  18487. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  18488. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  18489. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  18490. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  18491. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  18492. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  18493. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  18494. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  18495. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  18496. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  18497. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  18498. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  18499. delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
  18500. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  18501. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  18502. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  18503. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  18504. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  18505. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  18506. indentMore: function (cm) { return cm.indentSelection("add"); },
  18507. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  18508. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  18509. insertSoftTab: function (cm) {
  18510. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  18511. for (var i = 0; i < ranges.length; i++) {
  18512. var pos = ranges[i].from();
  18513. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  18514. spaces.push(spaceStr(tabSize - col % tabSize));
  18515. }
  18516. cm.replaceSelections(spaces);
  18517. },
  18518. defaultTab: function (cm) {
  18519. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  18520. else { cm.execCommand("insertTab"); }
  18521. },
  18522. // Swap the two chars left and right of each selection's head.
  18523. // Move cursor behind the two swapped characters afterwards.
  18524. //
  18525. // Doesn't consider line feeds a character.
  18526. // Doesn't scan more than one line above to find a character.
  18527. // Doesn't do anything on an empty line.
  18528. // Doesn't do anything with non-empty selections.
  18529. transposeChars: function (cm) { return runInOp(cm, function () {
  18530. var ranges = cm.listSelections(), newSel = [];
  18531. for (var i = 0; i < ranges.length; i++) {
  18532. if (!ranges[i].empty()) { continue }
  18533. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  18534. if (line) {
  18535. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  18536. if (cur.ch > 0) {
  18537. cur = new Pos(cur.line, cur.ch + 1);
  18538. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  18539. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  18540. } else if (cur.line > cm.doc.first) {
  18541. var prev = getLine(cm.doc, cur.line - 1).text;
  18542. if (prev) {
  18543. cur = new Pos(cur.line, 1);
  18544. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  18545. prev.charAt(prev.length - 1),
  18546. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  18547. }
  18548. }
  18549. }
  18550. newSel.push(new Range(cur, cur));
  18551. }
  18552. cm.setSelections(newSel);
  18553. }); },
  18554. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  18555. var sels = cm.listSelections();
  18556. for (var i = sels.length - 1; i >= 0; i--)
  18557. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  18558. sels = cm.listSelections();
  18559. for (var i$1 = 0; i$1 < sels.length; i$1++)
  18560. { cm.indentLine(sels[i$1].from().line, null, true); }
  18561. ensureCursorVisible(cm);
  18562. }); },
  18563. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  18564. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  18565. };
  18566. function lineStart(cm, lineN) {
  18567. var line = getLine(cm.doc, lineN);
  18568. var visual = visualLine(line);
  18569. if (visual != line) { lineN = lineNo(visual); }
  18570. return endOfLine(true, cm, visual, lineN, 1)
  18571. }
  18572. function lineEnd(cm, lineN) {
  18573. var line = getLine(cm.doc, lineN);
  18574. var visual = visualLineEnd(line);
  18575. if (visual != line) { lineN = lineNo(visual); }
  18576. return endOfLine(true, cm, line, lineN, -1)
  18577. }
  18578. function lineStartSmart(cm, pos) {
  18579. var start = lineStart(cm, pos.line);
  18580. var line = getLine(cm.doc, start.line);
  18581. var order = getOrder(line, cm.doc.direction);
  18582. if (!order || order[0].level == 0) {
  18583. var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  18584. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  18585. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  18586. }
  18587. return start
  18588. }
  18589. // Run a handler that was bound to a key.
  18590. function doHandleBinding(cm, bound, dropShift) {
  18591. if (typeof bound == "string") {
  18592. bound = commands[bound];
  18593. if (!bound) { return false }
  18594. }
  18595. // Ensure previous input has been read, so that the handler sees a
  18596. // consistent view of the document
  18597. cm.display.input.ensurePolled();
  18598. var prevShift = cm.display.shift, done = false;
  18599. try {
  18600. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  18601. if (dropShift) { cm.display.shift = false; }
  18602. done = bound(cm) != Pass;
  18603. } finally {
  18604. cm.display.shift = prevShift;
  18605. cm.state.suppressEdits = false;
  18606. }
  18607. return done
  18608. }
  18609. function lookupKeyForEditor(cm, name, handle) {
  18610. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  18611. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  18612. if (result) { return result }
  18613. }
  18614. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  18615. || lookupKey(name, cm.options.keyMap, handle, cm)
  18616. }
  18617. // Note that, despite the name, this function is also used to check
  18618. // for bound mouse clicks.
  18619. var stopSeq = new Delayed;
  18620. function dispatchKey(cm, name, e, handle) {
  18621. var seq = cm.state.keySeq;
  18622. if (seq) {
  18623. if (isModifierKey(name)) { return "handled" }
  18624. if (/\'$/.test(name))
  18625. { cm.state.keySeq = null; }
  18626. else
  18627. { stopSeq.set(50, function () {
  18628. if (cm.state.keySeq == seq) {
  18629. cm.state.keySeq = null;
  18630. cm.display.input.reset();
  18631. }
  18632. }); }
  18633. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  18634. }
  18635. return dispatchKeyInner(cm, name, e, handle)
  18636. }
  18637. function dispatchKeyInner(cm, name, e, handle) {
  18638. var result = lookupKeyForEditor(cm, name, handle);
  18639. if (result == "multi")
  18640. { cm.state.keySeq = name; }
  18641. if (result == "handled")
  18642. { signalLater(cm, "keyHandled", cm, name, e); }
  18643. if (result == "handled" || result == "multi") {
  18644. e_preventDefault(e);
  18645. restartBlink(cm);
  18646. }
  18647. return !!result
  18648. }
  18649. // Handle a key from the keydown event.
  18650. function handleKeyBinding(cm, e) {
  18651. var name = keyName(e, true);
  18652. if (!name) { return false }
  18653. if (e.shiftKey && !cm.state.keySeq) {
  18654. // First try to resolve full name (including 'Shift-'). Failing
  18655. // that, see if there is a cursor-motion command (starting with
  18656. // 'go') bound to the keyname without 'Shift-'.
  18657. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  18658. || dispatchKey(cm, name, e, function (b) {
  18659. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  18660. { return doHandleBinding(cm, b) }
  18661. })
  18662. } else {
  18663. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  18664. }
  18665. }
  18666. // Handle a key from the keypress event
  18667. function handleCharBinding(cm, e, ch) {
  18668. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  18669. }
  18670. var lastStoppedKey = null;
  18671. function onKeyDown(e) {
  18672. var cm = this;
  18673. if (e.target && e.target != cm.display.input.getField()) { return }
  18674. cm.curOp.focus = activeElt();
  18675. if (signalDOMEvent(cm, e)) { return }
  18676. // IE does strange things with escape.
  18677. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  18678. var code = e.keyCode;
  18679. cm.display.shift = code == 16 || e.shiftKey;
  18680. var handled = handleKeyBinding(cm, e);
  18681. if (presto) {
  18682. lastStoppedKey = handled ? code : null;
  18683. // Opera has no cut event... we try to at least catch the key combo
  18684. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  18685. { cm.replaceSelection("", null, "cut"); }
  18686. }
  18687. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  18688. { document.execCommand("cut"); }
  18689. // Turn mouse into crosshair when Alt is held on Mac.
  18690. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  18691. { showCrossHair(cm); }
  18692. }
  18693. function showCrossHair(cm) {
  18694. var lineDiv = cm.display.lineDiv;
  18695. addClass(lineDiv, "CodeMirror-crosshair");
  18696. function up(e) {
  18697. if (e.keyCode == 18 || !e.altKey) {
  18698. rmClass(lineDiv, "CodeMirror-crosshair");
  18699. off(document, "keyup", up);
  18700. off(document, "mouseover", up);
  18701. }
  18702. }
  18703. on(document, "keyup", up);
  18704. on(document, "mouseover", up);
  18705. }
  18706. function onKeyUp(e) {
  18707. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  18708. signalDOMEvent(this, e);
  18709. }
  18710. function onKeyPress(e) {
  18711. var cm = this;
  18712. if (e.target && e.target != cm.display.input.getField()) { return }
  18713. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  18714. var keyCode = e.keyCode, charCode = e.charCode;
  18715. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  18716. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  18717. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  18718. // Some browsers fire keypress events for backspace
  18719. if (ch == "\x08") { return }
  18720. if (handleCharBinding(cm, e, ch)) { return }
  18721. cm.display.input.onKeyPress(e);
  18722. }
  18723. var DOUBLECLICK_DELAY = 400;
  18724. var PastClick = function(time, pos, button) {
  18725. this.time = time;
  18726. this.pos = pos;
  18727. this.button = button;
  18728. };
  18729. PastClick.prototype.compare = function (time, pos, button) {
  18730. return this.time + DOUBLECLICK_DELAY > time &&
  18731. cmp(pos, this.pos) == 0 && button == this.button
  18732. };
  18733. var lastClick, lastDoubleClick;
  18734. function clickRepeat(pos, button) {
  18735. var now = +new Date;
  18736. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  18737. lastClick = lastDoubleClick = null;
  18738. return "triple"
  18739. } else if (lastClick && lastClick.compare(now, pos, button)) {
  18740. lastDoubleClick = new PastClick(now, pos, button);
  18741. lastClick = null;
  18742. return "double"
  18743. } else {
  18744. lastClick = new PastClick(now, pos, button);
  18745. lastDoubleClick = null;
  18746. return "single"
  18747. }
  18748. }
  18749. // A mouse down can be a single click, double click, triple click,
  18750. // start of selection drag, start of text drag, new cursor
  18751. // (ctrl-click), rectangle drag (alt-drag), or xwin
  18752. // middle-click-paste. Or it might be a click on something we should
  18753. // not interfere with, such as a scrollbar or widget.
  18754. function onMouseDown(e) {
  18755. var cm = this, display = cm.display;
  18756. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  18757. display.input.ensurePolled();
  18758. display.shift = e.shiftKey;
  18759. if (eventInWidget(display, e)) {
  18760. if (!webkit) {
  18761. // Briefly turn off draggability, to allow widgets to do
  18762. // normal dragging things.
  18763. display.scroller.draggable = false;
  18764. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  18765. }
  18766. return
  18767. }
  18768. if (clickInGutter(cm, e)) { return }
  18769. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  18770. window.focus();
  18771. // #3261: make sure, that we're not starting a second selection
  18772. if (button == 1 && cm.state.selectingText)
  18773. { cm.state.selectingText(e); }
  18774. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  18775. if (button == 1) {
  18776. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  18777. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  18778. } else if (button == 2) {
  18779. if (pos) { extendSelection(cm.doc, pos); }
  18780. setTimeout(function () { return display.input.focus(); }, 20);
  18781. } else if (button == 3) {
  18782. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  18783. else { delayBlurEvent(cm); }
  18784. }
  18785. }
  18786. function handleMappedButton(cm, button, pos, repeat, event) {
  18787. var name = "Click";
  18788. if (repeat == "double") { name = "Double" + name; }
  18789. else if (repeat == "triple") { name = "Triple" + name; }
  18790. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  18791. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  18792. if (typeof bound == "string") { bound = commands[bound]; }
  18793. if (!bound) { return false }
  18794. var done = false;
  18795. try {
  18796. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  18797. done = bound(cm, pos) != Pass;
  18798. } finally {
  18799. cm.state.suppressEdits = false;
  18800. }
  18801. return done
  18802. })
  18803. }
  18804. function configureMouse(cm, repeat, event) {
  18805. var option = cm.getOption("configureMouse");
  18806. var value = option ? option(cm, repeat, event) : {};
  18807. if (value.unit == null) {
  18808. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  18809. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  18810. }
  18811. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  18812. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  18813. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  18814. return value
  18815. }
  18816. function leftButtonDown(cm, pos, repeat, event) {
  18817. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  18818. else { cm.curOp.focus = activeElt(); }
  18819. var behavior = configureMouse(cm, repeat, event);
  18820. var sel = cm.doc.sel, contained;
  18821. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  18822. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  18823. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  18824. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  18825. { leftButtonStartDrag(cm, event, pos, behavior); }
  18826. else
  18827. { leftButtonSelect(cm, event, pos, behavior); }
  18828. }
  18829. // Start a text drag. When it ends, see if any dragging actually
  18830. // happen, and treat as a click if it didn't.
  18831. function leftButtonStartDrag(cm, event, pos, behavior) {
  18832. var display = cm.display, moved = false;
  18833. var dragEnd = operation(cm, function (e) {
  18834. if (webkit) { display.scroller.draggable = false; }
  18835. cm.state.draggingText = false;
  18836. if (cm.state.delayingBlurEvent) {
  18837. if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
  18838. else { delayBlurEvent(cm); }
  18839. }
  18840. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  18841. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  18842. off(display.scroller, "dragstart", dragStart);
  18843. off(display.scroller, "drop", dragEnd);
  18844. if (!moved) {
  18845. e_preventDefault(e);
  18846. if (!behavior.addNew)
  18847. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  18848. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  18849. if ((webkit && !safari) || ie && ie_version == 9)
  18850. { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
  18851. else
  18852. { display.input.focus(); }
  18853. }
  18854. });
  18855. var mouseMove = function(e2) {
  18856. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  18857. };
  18858. var dragStart = function () { return moved = true; };
  18859. // Let the drag handler handle this.
  18860. if (webkit) { display.scroller.draggable = true; }
  18861. cm.state.draggingText = dragEnd;
  18862. dragEnd.copy = !behavior.moveOnDrag;
  18863. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  18864. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  18865. on(display.scroller, "dragstart", dragStart);
  18866. on(display.scroller, "drop", dragEnd);
  18867. cm.state.delayingBlurEvent = true;
  18868. setTimeout(function () { return display.input.focus(); }, 20);
  18869. // IE's approach to draggable
  18870. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  18871. }
  18872. function rangeForUnit(cm, pos, unit) {
  18873. if (unit == "char") { return new Range(pos, pos) }
  18874. if (unit == "word") { return cm.findWordAt(pos) }
  18875. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  18876. var result = unit(cm, pos);
  18877. return new Range(result.from, result.to)
  18878. }
  18879. // Normal selection, as opposed to text dragging.
  18880. function leftButtonSelect(cm, event, start, behavior) {
  18881. if (ie) { delayBlurEvent(cm); }
  18882. var display = cm.display, doc = cm.doc;
  18883. e_preventDefault(event);
  18884. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  18885. if (behavior.addNew && !behavior.extend) {
  18886. ourIndex = doc.sel.contains(start);
  18887. if (ourIndex > -1)
  18888. { ourRange = ranges[ourIndex]; }
  18889. else
  18890. { ourRange = new Range(start, start); }
  18891. } else {
  18892. ourRange = doc.sel.primary();
  18893. ourIndex = doc.sel.primIndex;
  18894. }
  18895. if (behavior.unit == "rectangle") {
  18896. if (!behavior.addNew) { ourRange = new Range(start, start); }
  18897. start = posFromMouse(cm, event, true, true);
  18898. ourIndex = -1;
  18899. } else {
  18900. var range = rangeForUnit(cm, start, behavior.unit);
  18901. if (behavior.extend)
  18902. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  18903. else
  18904. { ourRange = range; }
  18905. }
  18906. if (!behavior.addNew) {
  18907. ourIndex = 0;
  18908. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  18909. startSel = doc.sel;
  18910. } else if (ourIndex == -1) {
  18911. ourIndex = ranges.length;
  18912. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  18913. {scroll: false, origin: "*mouse"});
  18914. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  18915. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  18916. {scroll: false, origin: "*mouse"});
  18917. startSel = doc.sel;
  18918. } else {
  18919. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  18920. }
  18921. var lastPos = start;
  18922. function extendTo(pos) {
  18923. if (cmp(lastPos, pos) == 0) { return }
  18924. lastPos = pos;
  18925. if (behavior.unit == "rectangle") {
  18926. var ranges = [], tabSize = cm.options.tabSize;
  18927. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  18928. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  18929. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  18930. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  18931. line <= end; line++) {
  18932. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  18933. if (left == right)
  18934. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  18935. else if (text.length > leftPos)
  18936. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  18937. }
  18938. if (!ranges.length) { ranges.push(new Range(start, start)); }
  18939. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  18940. {origin: "*mouse", scroll: false});
  18941. cm.scrollIntoView(pos);
  18942. } else {
  18943. var oldRange = ourRange;
  18944. var range = rangeForUnit(cm, pos, behavior.unit);
  18945. var anchor = oldRange.anchor, head;
  18946. if (cmp(range.anchor, anchor) > 0) {
  18947. head = range.head;
  18948. anchor = minPos(oldRange.from(), range.anchor);
  18949. } else {
  18950. head = range.anchor;
  18951. anchor = maxPos(oldRange.to(), range.head);
  18952. }
  18953. var ranges$1 = startSel.ranges.slice(0);
  18954. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  18955. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  18956. }
  18957. }
  18958. var editorSize = display.wrapper.getBoundingClientRect();
  18959. // Used to ensure timeout re-tries don't fire when another extend
  18960. // happened in the meantime (clearTimeout isn't reliable -- at
  18961. // least on Chrome, the timeouts still happen even when cleared,
  18962. // if the clear happens after their scheduled firing time).
  18963. var counter = 0;
  18964. function extend(e) {
  18965. var curCount = ++counter;
  18966. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  18967. if (!cur) { return }
  18968. if (cmp(cur, lastPos) != 0) {
  18969. cm.curOp.focus = activeElt();
  18970. extendTo(cur);
  18971. var visible = visibleLines(display, doc);
  18972. if (cur.line >= visible.to || cur.line < visible.from)
  18973. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  18974. } else {
  18975. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  18976. if (outside) { setTimeout(operation(cm, function () {
  18977. if (counter != curCount) { return }
  18978. display.scroller.scrollTop += outside;
  18979. extend(e);
  18980. }), 50); }
  18981. }
  18982. }
  18983. function done(e) {
  18984. cm.state.selectingText = false;
  18985. counter = Infinity;
  18986. // If e is null or undefined we interpret this as someone trying
  18987. // to explicitly cancel the selection rather than the user
  18988. // letting go of the mouse button.
  18989. if (e) {
  18990. e_preventDefault(e);
  18991. display.input.focus();
  18992. }
  18993. off(display.wrapper.ownerDocument, "mousemove", move);
  18994. off(display.wrapper.ownerDocument, "mouseup", up);
  18995. doc.history.lastSelOrigin = null;
  18996. }
  18997. var move = operation(cm, function (e) {
  18998. if (e.buttons === 0 || !e_button(e)) { done(e); }
  18999. else { extend(e); }
  19000. });
  19001. var up = operation(cm, done);
  19002. cm.state.selectingText = up;
  19003. on(display.wrapper.ownerDocument, "mousemove", move);
  19004. on(display.wrapper.ownerDocument, "mouseup", up);
  19005. }
  19006. // Used when mouse-selecting to adjust the anchor to the proper side
  19007. // of a bidi jump depending on the visual position of the head.
  19008. function bidiSimplify(cm, range) {
  19009. var anchor = range.anchor;
  19010. var head = range.head;
  19011. var anchorLine = getLine(cm.doc, anchor.line);
  19012. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  19013. var order = getOrder(anchorLine);
  19014. if (!order) { return range }
  19015. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  19016. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  19017. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  19018. if (boundary == 0 || boundary == order.length) { return range }
  19019. // Compute the relative visual position of the head compared to the
  19020. // anchor (<0 is to the left, >0 to the right)
  19021. var leftSide;
  19022. if (head.line != anchor.line) {
  19023. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  19024. } else {
  19025. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  19026. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  19027. if (headIndex == boundary - 1 || headIndex == boundary)
  19028. { leftSide = dir < 0; }
  19029. else
  19030. { leftSide = dir > 0; }
  19031. }
  19032. var usePart = order[boundary + (leftSide ? -1 : 0)];
  19033. var from = leftSide == (usePart.level == 1);
  19034. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  19035. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  19036. }
  19037. // Determines whether an event happened in the gutter, and fires the
  19038. // handlers for the corresponding event.
  19039. function gutterEvent(cm, e, type, prevent) {
  19040. var mX, mY;
  19041. if (e.touches) {
  19042. mX = e.touches[0].clientX;
  19043. mY = e.touches[0].clientY;
  19044. } else {
  19045. try { mX = e.clientX; mY = e.clientY; }
  19046. catch(e$1) { return false }
  19047. }
  19048. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  19049. if (prevent) { e_preventDefault(e); }
  19050. var display = cm.display;
  19051. var lineBox = display.lineDiv.getBoundingClientRect();
  19052. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  19053. mY -= lineBox.top - display.viewOffset;
  19054. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  19055. var g = display.gutters.childNodes[i];
  19056. if (g && g.getBoundingClientRect().right >= mX) {
  19057. var line = lineAtHeight(cm.doc, mY);
  19058. var gutter = cm.display.gutterSpecs[i];
  19059. signal(cm, type, cm, line, gutter.className, e);
  19060. return e_defaultPrevented(e)
  19061. }
  19062. }
  19063. }
  19064. function clickInGutter(cm, e) {
  19065. return gutterEvent(cm, e, "gutterClick", true)
  19066. }
  19067. // CONTEXT MENU HANDLING
  19068. // To make the context menu work, we need to briefly unhide the
  19069. // textarea (making it as unobtrusive as possible) to let the
  19070. // right-click take effect on it.
  19071. function onContextMenu(cm, e) {
  19072. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  19073. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  19074. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  19075. }
  19076. function contextMenuInGutter(cm, e) {
  19077. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  19078. return gutterEvent(cm, e, "gutterContextMenu", false)
  19079. }
  19080. function themeChanged(cm) {
  19081. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  19082. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  19083. clearCaches(cm);
  19084. }
  19085. var Init = {toString: function(){return "CodeMirror.Init"}};
  19086. var defaults = {};
  19087. var optionHandlers = {};
  19088. function defineOptions(CodeMirror) {
  19089. var optionHandlers = CodeMirror.optionHandlers;
  19090. function option(name, deflt, handle, notOnInit) {
  19091. CodeMirror.defaults[name] = deflt;
  19092. if (handle) { optionHandlers[name] =
  19093. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  19094. }
  19095. CodeMirror.defineOption = option;
  19096. // Passed to option handlers when there is no old value.
  19097. CodeMirror.Init = Init;
  19098. // These two are, on init, called from the constructor because they
  19099. // have to be initialized before the editor can start at all.
  19100. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  19101. option("mode", null, function (cm, val) {
  19102. cm.doc.modeOption = val;
  19103. loadMode(cm);
  19104. }, true);
  19105. option("indentUnit", 2, loadMode, true);
  19106. option("indentWithTabs", false);
  19107. option("smartIndent", true);
  19108. option("tabSize", 4, function (cm) {
  19109. resetModeState(cm);
  19110. clearCaches(cm);
  19111. regChange(cm);
  19112. }, true);
  19113. option("lineSeparator", null, function (cm, val) {
  19114. cm.doc.lineSep = val;
  19115. if (!val) { return }
  19116. var newBreaks = [], lineNo = cm.doc.first;
  19117. cm.doc.iter(function (line) {
  19118. for (var pos = 0;;) {
  19119. var found = line.text.indexOf(val, pos);
  19120. if (found == -1) { break }
  19121. pos = found + val.length;
  19122. newBreaks.push(Pos(lineNo, found));
  19123. }
  19124. lineNo++;
  19125. });
  19126. for (var i = newBreaks.length - 1; i >= 0; i--)
  19127. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  19128. });
  19129. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  19130. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  19131. if (old != Init) { cm.refresh(); }
  19132. });
  19133. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  19134. option("electricChars", true);
  19135. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  19136. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  19137. }, true);
  19138. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  19139. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  19140. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  19141. option("rtlMoveVisually", !windows);
  19142. option("wholeLineUpdateBefore", true);
  19143. option("theme", "default", function (cm) {
  19144. themeChanged(cm);
  19145. updateGutters(cm);
  19146. }, true);
  19147. option("keyMap", "default", function (cm, val, old) {
  19148. var next = getKeyMap(val);
  19149. var prev = old != Init && getKeyMap(old);
  19150. if (prev && prev.detach) { prev.detach(cm, next); }
  19151. if (next.attach) { next.attach(cm, prev || null); }
  19152. });
  19153. option("extraKeys", null);
  19154. option("configureMouse", null);
  19155. option("lineWrapping", false, wrappingChanged, true);
  19156. option("gutters", [], function (cm, val) {
  19157. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  19158. updateGutters(cm);
  19159. }, true);
  19160. option("fixedGutter", true, function (cm, val) {
  19161. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  19162. cm.refresh();
  19163. }, true);
  19164. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  19165. option("scrollbarStyle", "native", function (cm) {
  19166. initScrollbars(cm);
  19167. updateScrollbars(cm);
  19168. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  19169. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  19170. }, true);
  19171. option("lineNumbers", false, function (cm, val) {
  19172. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  19173. updateGutters(cm);
  19174. }, true);
  19175. option("firstLineNumber", 1, updateGutters, true);
  19176. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  19177. option("showCursorWhenSelecting", false, updateSelection, true);
  19178. option("resetSelectionOnContextMenu", true);
  19179. option("lineWiseCopyCut", true);
  19180. option("pasteLinesPerSelection", true);
  19181. option("selectionsMayTouch", false);
  19182. option("readOnly", false, function (cm, val) {
  19183. if (val == "nocursor") {
  19184. onBlur(cm);
  19185. cm.display.input.blur();
  19186. }
  19187. cm.display.input.readOnlyChanged(val);
  19188. });
  19189. option("screenReaderLabel", null, function (cm, val) {
  19190. val = (val === '') ? null : val;
  19191. cm.display.input.screenReaderLabelChanged(val);
  19192. });
  19193. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  19194. option("dragDrop", true, dragDropChanged);
  19195. option("allowDropFileTypes", null);
  19196. option("cursorBlinkRate", 530);
  19197. option("cursorScrollMargin", 0);
  19198. option("cursorHeight", 1, updateSelection, true);
  19199. option("singleCursorHeightPerLine", true, updateSelection, true);
  19200. option("workTime", 100);
  19201. option("workDelay", 100);
  19202. option("flattenSpans", true, resetModeState, true);
  19203. option("addModeClass", false, resetModeState, true);
  19204. option("pollInterval", 100);
  19205. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  19206. option("historyEventDelay", 1250);
  19207. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  19208. option("maxHighlightLength", 10000, resetModeState, true);
  19209. option("moveInputWithCursor", true, function (cm, val) {
  19210. if (!val) { cm.display.input.resetPosition(); }
  19211. });
  19212. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  19213. option("autofocus", null);
  19214. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  19215. option("phrases", null);
  19216. }
  19217. function dragDropChanged(cm, value, old) {
  19218. var wasOn = old && old != Init;
  19219. if (!value != !wasOn) {
  19220. var funcs = cm.display.dragFunctions;
  19221. var toggle = value ? on : off;
  19222. toggle(cm.display.scroller, "dragstart", funcs.start);
  19223. toggle(cm.display.scroller, "dragenter", funcs.enter);
  19224. toggle(cm.display.scroller, "dragover", funcs.over);
  19225. toggle(cm.display.scroller, "dragleave", funcs.leave);
  19226. toggle(cm.display.scroller, "drop", funcs.drop);
  19227. }
  19228. }
  19229. function wrappingChanged(cm) {
  19230. if (cm.options.lineWrapping) {
  19231. addClass(cm.display.wrapper, "CodeMirror-wrap");
  19232. cm.display.sizer.style.minWidth = "";
  19233. cm.display.sizerWidth = null;
  19234. } else {
  19235. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  19236. findMaxLine(cm);
  19237. }
  19238. estimateLineHeights(cm);
  19239. regChange(cm);
  19240. clearCaches(cm);
  19241. setTimeout(function () { return updateScrollbars(cm); }, 100);
  19242. }
  19243. // A CodeMirror instance represents an editor. This is the object
  19244. // that user code is usually dealing with.
  19245. function CodeMirror(place, options) {
  19246. var this$1 = this;
  19247. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  19248. this.options = options = options ? copyObj(options) : {};
  19249. // Determine effective options based on given values and defaults.
  19250. copyObj(defaults, options, false);
  19251. var doc = options.value;
  19252. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  19253. else if (options.mode) { doc.modeOption = options.mode; }
  19254. this.doc = doc;
  19255. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  19256. var display = this.display = new Display(place, doc, input, options);
  19257. display.wrapper.CodeMirror = this;
  19258. themeChanged(this);
  19259. if (options.lineWrapping)
  19260. { this.display.wrapper.className += " CodeMirror-wrap"; }
  19261. initScrollbars(this);
  19262. this.state = {
  19263. keyMaps: [], // stores maps added by addKeyMap
  19264. overlays: [], // highlighting overlays, as added by addOverlay
  19265. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  19266. overwrite: false,
  19267. delayingBlurEvent: false,
  19268. focused: false,
  19269. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  19270. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  19271. selectingText: false,
  19272. draggingText: false,
  19273. highlight: new Delayed(), // stores highlight worker timeout
  19274. keySeq: null, // Unfinished key sequence
  19275. specialChars: null
  19276. };
  19277. if (options.autofocus && !mobile) { display.input.focus(); }
  19278. // Override magic textarea content restore that IE sometimes does
  19279. // on our hidden textarea on reload
  19280. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  19281. registerEventHandlers(this);
  19282. ensureGlobalHandlers();
  19283. startOperation(this);
  19284. this.curOp.forceUpdate = true;
  19285. attachDoc(this, doc);
  19286. if ((options.autofocus && !mobile) || this.hasFocus())
  19287. { setTimeout(function () {
  19288. if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
  19289. }, 20); }
  19290. else
  19291. { onBlur(this); }
  19292. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  19293. { optionHandlers[opt](this, options[opt], Init); } }
  19294. maybeUpdateLineNumberWidth(this);
  19295. if (options.finishInit) { options.finishInit(this); }
  19296. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  19297. endOperation(this);
  19298. // Suppress optimizelegibility in Webkit, since it breaks text
  19299. // measuring on line wrapping boundaries.
  19300. if (webkit && options.lineWrapping &&
  19301. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  19302. { display.lineDiv.style.textRendering = "auto"; }
  19303. }
  19304. // The default configuration options.
  19305. CodeMirror.defaults = defaults;
  19306. // Functions to run when options are changed.
  19307. CodeMirror.optionHandlers = optionHandlers;
  19308. // Attach the necessary event handlers when initializing the editor
  19309. function registerEventHandlers(cm) {
  19310. var d = cm.display;
  19311. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  19312. // Older IE's will not fire a second mousedown for a double click
  19313. if (ie && ie_version < 11)
  19314. { on(d.scroller, "dblclick", operation(cm, function (e) {
  19315. if (signalDOMEvent(cm, e)) { return }
  19316. var pos = posFromMouse(cm, e);
  19317. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  19318. e_preventDefault(e);
  19319. var word = cm.findWordAt(pos);
  19320. extendSelection(cm.doc, word.anchor, word.head);
  19321. })); }
  19322. else
  19323. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  19324. // Some browsers fire contextmenu *after* opening the menu, at
  19325. // which point we can't mess with it anymore. Context menu is
  19326. // handled in onMouseDown for these browsers.
  19327. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  19328. on(d.input.getField(), "contextmenu", function (e) {
  19329. if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  19330. });
  19331. // Used to suppress mouse event handling when a touch happens
  19332. var touchFinished, prevTouch = {end: 0};
  19333. function finishTouch() {
  19334. if (d.activeTouch) {
  19335. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  19336. prevTouch = d.activeTouch;
  19337. prevTouch.end = +new Date;
  19338. }
  19339. }
  19340. function isMouseLikeTouchEvent(e) {
  19341. if (e.touches.length != 1) { return false }
  19342. var touch = e.touches[0];
  19343. return touch.radiusX <= 1 && touch.radiusY <= 1
  19344. }
  19345. function farAway(touch, other) {
  19346. if (other.left == null) { return true }
  19347. var dx = other.left - touch.left, dy = other.top - touch.top;
  19348. return dx * dx + dy * dy > 20 * 20
  19349. }
  19350. on(d.scroller, "touchstart", function (e) {
  19351. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  19352. d.input.ensurePolled();
  19353. clearTimeout(touchFinished);
  19354. var now = +new Date;
  19355. d.activeTouch = {start: now, moved: false,
  19356. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  19357. if (e.touches.length == 1) {
  19358. d.activeTouch.left = e.touches[0].pageX;
  19359. d.activeTouch.top = e.touches[0].pageY;
  19360. }
  19361. }
  19362. });
  19363. on(d.scroller, "touchmove", function () {
  19364. if (d.activeTouch) { d.activeTouch.moved = true; }
  19365. });
  19366. on(d.scroller, "touchend", function (e) {
  19367. var touch = d.activeTouch;
  19368. if (touch && !eventInWidget(d, e) && touch.left != null &&
  19369. !touch.moved && new Date - touch.start < 300) {
  19370. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  19371. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  19372. { range = new Range(pos, pos); }
  19373. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  19374. { range = cm.findWordAt(pos); }
  19375. else // Triple tap
  19376. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  19377. cm.setSelection(range.anchor, range.head);
  19378. cm.focus();
  19379. e_preventDefault(e);
  19380. }
  19381. finishTouch();
  19382. });
  19383. on(d.scroller, "touchcancel", finishTouch);
  19384. // Sync scrolling between fake scrollbars and real scrollable
  19385. // area, ensure viewport is updated when scrolling.
  19386. on(d.scroller, "scroll", function () {
  19387. if (d.scroller.clientHeight) {
  19388. updateScrollTop(cm, d.scroller.scrollTop);
  19389. setScrollLeft(cm, d.scroller.scrollLeft, true);
  19390. signal(cm, "scroll", cm);
  19391. }
  19392. });
  19393. // Listen to wheel events in order to try and update the viewport on time.
  19394. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  19395. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  19396. // Prevent wrapper from ever scrolling
  19397. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  19398. d.dragFunctions = {
  19399. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  19400. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  19401. start: function (e) { return onDragStart(cm, e); },
  19402. drop: operation(cm, onDrop),
  19403. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  19404. };
  19405. var inp = d.input.getField();
  19406. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  19407. on(inp, "keydown", operation(cm, onKeyDown));
  19408. on(inp, "keypress", operation(cm, onKeyPress));
  19409. on(inp, "focus", function (e) { return onFocus(cm, e); });
  19410. on(inp, "blur", function (e) { return onBlur(cm, e); });
  19411. }
  19412. var initHooks = [];
  19413. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  19414. // Indent the given line. The how parameter can be "smart",
  19415. // "add"/null, "subtract", or "prev". When aggressive is false
  19416. // (typically set to true for forced single-line indents), empty
  19417. // lines are not indented, and places where the mode returns Pass
  19418. // are left alone.
  19419. function indentLine(cm, n, how, aggressive) {
  19420. var doc = cm.doc, state;
  19421. if (how == null) { how = "add"; }
  19422. if (how == "smart") {
  19423. // Fall back to "prev" when the mode doesn't have an indentation
  19424. // method.
  19425. if (!doc.mode.indent) { how = "prev"; }
  19426. else { state = getContextBefore(cm, n).state; }
  19427. }
  19428. var tabSize = cm.options.tabSize;
  19429. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  19430. if (line.stateAfter) { line.stateAfter = null; }
  19431. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  19432. if (!aggressive && !/\S/.test(line.text)) {
  19433. indentation = 0;
  19434. how = "not";
  19435. } else if (how == "smart") {
  19436. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  19437. if (indentation == Pass || indentation > 150) {
  19438. if (!aggressive) { return }
  19439. how = "prev";
  19440. }
  19441. }
  19442. if (how == "prev") {
  19443. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  19444. else { indentation = 0; }
  19445. } else if (how == "add") {
  19446. indentation = curSpace + cm.options.indentUnit;
  19447. } else if (how == "subtract") {
  19448. indentation = curSpace - cm.options.indentUnit;
  19449. } else if (typeof how == "number") {
  19450. indentation = curSpace + how;
  19451. }
  19452. indentation = Math.max(0, indentation);
  19453. var indentString = "", pos = 0;
  19454. if (cm.options.indentWithTabs)
  19455. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  19456. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  19457. if (indentString != curSpaceString) {
  19458. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  19459. line.stateAfter = null;
  19460. return true
  19461. } else {
  19462. // Ensure that, if the cursor was in the whitespace at the start
  19463. // of the line, it is moved to the end of that space.
  19464. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  19465. var range = doc.sel.ranges[i$1];
  19466. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  19467. var pos$1 = Pos(n, curSpaceString.length);
  19468. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  19469. break
  19470. }
  19471. }
  19472. }
  19473. }
  19474. // This will be set to a {lineWise: bool, text: [string]} object, so
  19475. // that, when pasting, we know what kind of selections the copied
  19476. // text was made out of.
  19477. var lastCopied = null;
  19478. function setLastCopied(newLastCopied) {
  19479. lastCopied = newLastCopied;
  19480. }
  19481. function applyTextInput(cm, inserted, deleted, sel, origin) {
  19482. var doc = cm.doc;
  19483. cm.display.shift = false;
  19484. if (!sel) { sel = doc.sel; }
  19485. var recent = +new Date - 200;
  19486. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  19487. var textLines = splitLinesAuto(inserted), multiPaste = null;
  19488. // When pasting N lines into N selections, insert one line per selection
  19489. if (paste && sel.ranges.length > 1) {
  19490. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  19491. if (sel.ranges.length % lastCopied.text.length == 0) {
  19492. multiPaste = [];
  19493. for (var i = 0; i < lastCopied.text.length; i++)
  19494. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  19495. }
  19496. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  19497. multiPaste = map(textLines, function (l) { return [l]; });
  19498. }
  19499. }
  19500. var updateInput = cm.curOp.updateInput;
  19501. // Normal behavior is to insert the new text into every selection
  19502. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  19503. var range = sel.ranges[i$1];
  19504. var from = range.from(), to = range.to();
  19505. if (range.empty()) {
  19506. if (deleted && deleted > 0) // Handle deletion
  19507. { from = Pos(from.line, from.ch - deleted); }
  19508. else if (cm.state.overwrite && !paste) // Handle overwrite
  19509. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  19510. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
  19511. { from = to = Pos(from.line, 0); }
  19512. }
  19513. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  19514. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  19515. makeChange(cm.doc, changeEvent);
  19516. signalLater(cm, "inputRead", cm, changeEvent);
  19517. }
  19518. if (inserted && !paste)
  19519. { triggerElectric(cm, inserted); }
  19520. ensureCursorVisible(cm);
  19521. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  19522. cm.curOp.typing = true;
  19523. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  19524. }
  19525. function handlePaste(e, cm) {
  19526. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  19527. if (pasted) {
  19528. e.preventDefault();
  19529. if (!cm.isReadOnly() && !cm.options.disableInput)
  19530. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  19531. return true
  19532. }
  19533. }
  19534. function triggerElectric(cm, inserted) {
  19535. // When an 'electric' character is inserted, immediately trigger a reindent
  19536. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  19537. var sel = cm.doc.sel;
  19538. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  19539. var range = sel.ranges[i];
  19540. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  19541. var mode = cm.getModeAt(range.head);
  19542. var indented = false;
  19543. if (mode.electricChars) {
  19544. for (var j = 0; j < mode.electricChars.length; j++)
  19545. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  19546. indented = indentLine(cm, range.head.line, "smart");
  19547. break
  19548. } }
  19549. } else if (mode.electricInput) {
  19550. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  19551. { indented = indentLine(cm, range.head.line, "smart"); }
  19552. }
  19553. if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  19554. }
  19555. }
  19556. function copyableRanges(cm) {
  19557. var text = [], ranges = [];
  19558. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  19559. var line = cm.doc.sel.ranges[i].head.line;
  19560. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  19561. ranges.push(lineRange);
  19562. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  19563. }
  19564. return {text: text, ranges: ranges}
  19565. }
  19566. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  19567. field.setAttribute("autocorrect", autocorrect ? "" : "off");
  19568. field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  19569. field.setAttribute("spellcheck", !!spellcheck);
  19570. }
  19571. function hiddenTextarea() {
  19572. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
  19573. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  19574. // The textarea is kept positioned near the cursor to prevent the
  19575. // fact that it'll be scrolled into view on input from scrolling
  19576. // our fake cursor out of view. On webkit, when wrap=off, paste is
  19577. // very slow. So make the area wide instead.
  19578. if (webkit) { te.style.width = "1000px"; }
  19579. else { te.setAttribute("wrap", "off"); }
  19580. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  19581. if (ios) { te.style.border = "1px solid black"; }
  19582. disableBrowserMagic(te);
  19583. return div
  19584. }
  19585. // The publicly visible API. Note that methodOp(f) means
  19586. // 'wrap f in an operation, performed on its `this` parameter'.
  19587. // This is not the complete set of editor methods. Most of the
  19588. // methods defined on the Doc type are also injected into
  19589. // CodeMirror.prototype, for backwards compatibility and
  19590. // convenience.
  19591. function addEditorMethods(CodeMirror) {
  19592. var optionHandlers = CodeMirror.optionHandlers;
  19593. var helpers = CodeMirror.helpers = {};
  19594. CodeMirror.prototype = {
  19595. constructor: CodeMirror,
  19596. focus: function(){window.focus(); this.display.input.focus();},
  19597. setOption: function(option, value) {
  19598. var options = this.options, old = options[option];
  19599. if (options[option] == value && option != "mode") { return }
  19600. options[option] = value;
  19601. if (optionHandlers.hasOwnProperty(option))
  19602. { operation(this, optionHandlers[option])(this, value, old); }
  19603. signal(this, "optionChange", this, option);
  19604. },
  19605. getOption: function(option) {return this.options[option]},
  19606. getDoc: function() {return this.doc},
  19607. addKeyMap: function(map, bottom) {
  19608. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  19609. },
  19610. removeKeyMap: function(map) {
  19611. var maps = this.state.keyMaps;
  19612. for (var i = 0; i < maps.length; ++i)
  19613. { if (maps[i] == map || maps[i].name == map) {
  19614. maps.splice(i, 1);
  19615. return true
  19616. } }
  19617. },
  19618. addOverlay: methodOp(function(spec, options) {
  19619. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  19620. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  19621. insertSorted(this.state.overlays,
  19622. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  19623. priority: (options && options.priority) || 0},
  19624. function (overlay) { return overlay.priority; });
  19625. this.state.modeGen++;
  19626. regChange(this);
  19627. }),
  19628. removeOverlay: methodOp(function(spec) {
  19629. var overlays = this.state.overlays;
  19630. for (var i = 0; i < overlays.length; ++i) {
  19631. var cur = overlays[i].modeSpec;
  19632. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  19633. overlays.splice(i, 1);
  19634. this.state.modeGen++;
  19635. regChange(this);
  19636. return
  19637. }
  19638. }
  19639. }),
  19640. indentLine: methodOp(function(n, dir, aggressive) {
  19641. if (typeof dir != "string" && typeof dir != "number") {
  19642. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  19643. else { dir = dir ? "add" : "subtract"; }
  19644. }
  19645. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  19646. }),
  19647. indentSelection: methodOp(function(how) {
  19648. var ranges = this.doc.sel.ranges, end = -1;
  19649. for (var i = 0; i < ranges.length; i++) {
  19650. var range = ranges[i];
  19651. if (!range.empty()) {
  19652. var from = range.from(), to = range.to();
  19653. var start = Math.max(end, from.line);
  19654. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  19655. for (var j = start; j < end; ++j)
  19656. { indentLine(this, j, how); }
  19657. var newRanges = this.doc.sel.ranges;
  19658. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  19659. { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  19660. } else if (range.head.line > end) {
  19661. indentLine(this, range.head.line, how, true);
  19662. end = range.head.line;
  19663. if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  19664. }
  19665. }
  19666. }),
  19667. // Fetch the parser token for a given character. Useful for hacks
  19668. // that want to inspect the mode state (say, for completion).
  19669. getTokenAt: function(pos, precise) {
  19670. return takeToken(this, pos, precise)
  19671. },
  19672. getLineTokens: function(line, precise) {
  19673. return takeToken(this, Pos(line), precise, true)
  19674. },
  19675. getTokenTypeAt: function(pos) {
  19676. pos = clipPos(this.doc, pos);
  19677. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  19678. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  19679. var type;
  19680. if (ch == 0) { type = styles[2]; }
  19681. else { for (;;) {
  19682. var mid = (before + after) >> 1;
  19683. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  19684. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  19685. else { type = styles[mid * 2 + 2]; break }
  19686. } }
  19687. var cut = type ? type.indexOf("overlay ") : -1;
  19688. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  19689. },
  19690. getModeAt: function(pos) {
  19691. var mode = this.doc.mode;
  19692. if (!mode.innerMode) { return mode }
  19693. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  19694. },
  19695. getHelper: function(pos, type) {
  19696. return this.getHelpers(pos, type)[0]
  19697. },
  19698. getHelpers: function(pos, type) {
  19699. var found = [];
  19700. if (!helpers.hasOwnProperty(type)) { return found }
  19701. var help = helpers[type], mode = this.getModeAt(pos);
  19702. if (typeof mode[type] == "string") {
  19703. if (help[mode[type]]) { found.push(help[mode[type]]); }
  19704. } else if (mode[type]) {
  19705. for (var i = 0; i < mode[type].length; i++) {
  19706. var val = help[mode[type][i]];
  19707. if (val) { found.push(val); }
  19708. }
  19709. } else if (mode.helperType && help[mode.helperType]) {
  19710. found.push(help[mode.helperType]);
  19711. } else if (help[mode.name]) {
  19712. found.push(help[mode.name]);
  19713. }
  19714. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  19715. var cur = help._global[i$1];
  19716. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  19717. { found.push(cur.val); }
  19718. }
  19719. return found
  19720. },
  19721. getStateAfter: function(line, precise) {
  19722. var doc = this.doc;
  19723. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  19724. return getContextBefore(this, line + 1, precise).state
  19725. },
  19726. cursorCoords: function(start, mode) {
  19727. var pos, range = this.doc.sel.primary();
  19728. if (start == null) { pos = range.head; }
  19729. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  19730. else { pos = start ? range.from() : range.to(); }
  19731. return cursorCoords(this, pos, mode || "page")
  19732. },
  19733. charCoords: function(pos, mode) {
  19734. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  19735. },
  19736. coordsChar: function(coords, mode) {
  19737. coords = fromCoordSystem(this, coords, mode || "page");
  19738. return coordsChar(this, coords.left, coords.top)
  19739. },
  19740. lineAtHeight: function(height, mode) {
  19741. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  19742. return lineAtHeight(this.doc, height + this.display.viewOffset)
  19743. },
  19744. heightAtLine: function(line, mode, includeWidgets) {
  19745. var end = false, lineObj;
  19746. if (typeof line == "number") {
  19747. var last = this.doc.first + this.doc.size - 1;
  19748. if (line < this.doc.first) { line = this.doc.first; }
  19749. else if (line > last) { line = last; end = true; }
  19750. lineObj = getLine(this.doc, line);
  19751. } else {
  19752. lineObj = line;
  19753. }
  19754. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  19755. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  19756. },
  19757. defaultTextHeight: function() { return textHeight(this.display) },
  19758. defaultCharWidth: function() { return charWidth(this.display) },
  19759. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  19760. addWidget: function(pos, node, scroll, vert, horiz) {
  19761. var display = this.display;
  19762. pos = cursorCoords(this, clipPos(this.doc, pos));
  19763. var top = pos.bottom, left = pos.left;
  19764. node.style.position = "absolute";
  19765. node.setAttribute("cm-ignore-events", "true");
  19766. this.display.input.setUneditable(node);
  19767. display.sizer.appendChild(node);
  19768. if (vert == "over") {
  19769. top = pos.top;
  19770. } else if (vert == "above" || vert == "near") {
  19771. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  19772. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  19773. // Default to positioning above (if specified and possible); otherwise default to positioning below
  19774. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  19775. { top = pos.top - node.offsetHeight; }
  19776. else if (pos.bottom + node.offsetHeight <= vspace)
  19777. { top = pos.bottom; }
  19778. if (left + node.offsetWidth > hspace)
  19779. { left = hspace - node.offsetWidth; }
  19780. }
  19781. node.style.top = top + "px";
  19782. node.style.left = node.style.right = "";
  19783. if (horiz == "right") {
  19784. left = display.sizer.clientWidth - node.offsetWidth;
  19785. node.style.right = "0px";
  19786. } else {
  19787. if (horiz == "left") { left = 0; }
  19788. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  19789. node.style.left = left + "px";
  19790. }
  19791. if (scroll)
  19792. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  19793. },
  19794. triggerOnKeyDown: methodOp(onKeyDown),
  19795. triggerOnKeyPress: methodOp(onKeyPress),
  19796. triggerOnKeyUp: onKeyUp,
  19797. triggerOnMouseDown: methodOp(onMouseDown),
  19798. execCommand: function(cmd) {
  19799. if (commands.hasOwnProperty(cmd))
  19800. { return commands[cmd].call(null, this) }
  19801. },
  19802. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  19803. findPosH: function(from, amount, unit, visually) {
  19804. var dir = 1;
  19805. if (amount < 0) { dir = -1; amount = -amount; }
  19806. var cur = clipPos(this.doc, from);
  19807. for (var i = 0; i < amount; ++i) {
  19808. cur = findPosH(this.doc, cur, dir, unit, visually);
  19809. if (cur.hitSide) { break }
  19810. }
  19811. return cur
  19812. },
  19813. moveH: methodOp(function(dir, unit) {
  19814. var this$1 = this;
  19815. this.extendSelectionsBy(function (range) {
  19816. if (this$1.display.shift || this$1.doc.extend || range.empty())
  19817. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  19818. else
  19819. { return dir < 0 ? range.from() : range.to() }
  19820. }, sel_move);
  19821. }),
  19822. deleteH: methodOp(function(dir, unit) {
  19823. var sel = this.doc.sel, doc = this.doc;
  19824. if (sel.somethingSelected())
  19825. { doc.replaceSelection("", null, "+delete"); }
  19826. else
  19827. { deleteNearSelection(this, function (range) {
  19828. var other = findPosH(doc, range.head, dir, unit, false);
  19829. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  19830. }); }
  19831. }),
  19832. findPosV: function(from, amount, unit, goalColumn) {
  19833. var dir = 1, x = goalColumn;
  19834. if (amount < 0) { dir = -1; amount = -amount; }
  19835. var cur = clipPos(this.doc, from);
  19836. for (var i = 0; i < amount; ++i) {
  19837. var coords = cursorCoords(this, cur, "div");
  19838. if (x == null) { x = coords.left; }
  19839. else { coords.left = x; }
  19840. cur = findPosV(this, coords, dir, unit);
  19841. if (cur.hitSide) { break }
  19842. }
  19843. return cur
  19844. },
  19845. moveV: methodOp(function(dir, unit) {
  19846. var this$1 = this;
  19847. var doc = this.doc, goals = [];
  19848. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  19849. doc.extendSelectionsBy(function (range) {
  19850. if (collapse)
  19851. { return dir < 0 ? range.from() : range.to() }
  19852. var headPos = cursorCoords(this$1, range.head, "div");
  19853. if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  19854. goals.push(headPos.left);
  19855. var pos = findPosV(this$1, headPos, dir, unit);
  19856. if (unit == "page" && range == doc.sel.primary())
  19857. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  19858. return pos
  19859. }, sel_move);
  19860. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  19861. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  19862. }),
  19863. // Find the word at the given position (as returned by coordsChar).
  19864. findWordAt: function(pos) {
  19865. var doc = this.doc, line = getLine(doc, pos.line).text;
  19866. var start = pos.ch, end = pos.ch;
  19867. if (line) {
  19868. var helper = this.getHelper(pos, "wordChars");
  19869. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  19870. var startChar = line.charAt(start);
  19871. var check = isWordChar(startChar, helper)
  19872. ? function (ch) { return isWordChar(ch, helper); }
  19873. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  19874. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  19875. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  19876. while (end < line.length && check(line.charAt(end))) { ++end; }
  19877. }
  19878. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  19879. },
  19880. toggleOverwrite: function(value) {
  19881. if (value != null && value == this.state.overwrite) { return }
  19882. if (this.state.overwrite = !this.state.overwrite)
  19883. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  19884. else
  19885. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  19886. signal(this, "overwriteToggle", this, this.state.overwrite);
  19887. },
  19888. hasFocus: function() { return this.display.input.getField() == activeElt() },
  19889. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  19890. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  19891. getScrollInfo: function() {
  19892. var scroller = this.display.scroller;
  19893. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  19894. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  19895. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  19896. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  19897. },
  19898. scrollIntoView: methodOp(function(range, margin) {
  19899. if (range == null) {
  19900. range = {from: this.doc.sel.primary().head, to: null};
  19901. if (margin == null) { margin = this.options.cursorScrollMargin; }
  19902. } else if (typeof range == "number") {
  19903. range = {from: Pos(range, 0), to: null};
  19904. } else if (range.from == null) {
  19905. range = {from: range, to: null};
  19906. }
  19907. if (!range.to) { range.to = range.from; }
  19908. range.margin = margin || 0;
  19909. if (range.from.line != null) {
  19910. scrollToRange(this, range);
  19911. } else {
  19912. scrollToCoordsRange(this, range.from, range.to, range.margin);
  19913. }
  19914. }),
  19915. setSize: methodOp(function(width, height) {
  19916. var this$1 = this;
  19917. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  19918. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  19919. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  19920. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  19921. var lineNo = this.display.viewFrom;
  19922. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  19923. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  19924. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  19925. ++lineNo;
  19926. });
  19927. this.curOp.forceUpdate = true;
  19928. signal(this, "refresh", this);
  19929. }),
  19930. operation: function(f){return runInOp(this, f)},
  19931. startOperation: function(){return startOperation(this)},
  19932. endOperation: function(){return endOperation(this)},
  19933. refresh: methodOp(function() {
  19934. var oldHeight = this.display.cachedTextHeight;
  19935. regChange(this);
  19936. this.curOp.forceUpdate = true;
  19937. clearCaches(this);
  19938. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  19939. updateGutterSpace(this.display);
  19940. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  19941. { estimateLineHeights(this); }
  19942. signal(this, "refresh", this);
  19943. }),
  19944. swapDoc: methodOp(function(doc) {
  19945. var old = this.doc;
  19946. old.cm = null;
  19947. // Cancel the current text selection if any (#5821)
  19948. if (this.state.selectingText) { this.state.selectingText(); }
  19949. attachDoc(this, doc);
  19950. clearCaches(this);
  19951. this.display.input.reset();
  19952. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  19953. this.curOp.forceScroll = true;
  19954. signalLater(this, "swapDoc", this, old);
  19955. return old
  19956. }),
  19957. phrase: function(phraseText) {
  19958. var phrases = this.options.phrases;
  19959. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  19960. },
  19961. getInputField: function(){return this.display.input.getField()},
  19962. getWrapperElement: function(){return this.display.wrapper},
  19963. getScrollerElement: function(){return this.display.scroller},
  19964. getGutterElement: function(){return this.display.gutters}
  19965. };
  19966. eventMixin(CodeMirror);
  19967. CodeMirror.registerHelper = function(type, name, value) {
  19968. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  19969. helpers[type][name] = value;
  19970. };
  19971. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  19972. CodeMirror.registerHelper(type, name, value);
  19973. helpers[type]._global.push({pred: predicate, val: value});
  19974. };
  19975. }
  19976. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  19977. // right), unit can be "codepoint", "char", "column" (like char, but
  19978. // doesn't cross line boundaries), "word" (across next word), or
  19979. // "group" (to the start of next group of word or
  19980. // non-word-non-whitespace chars). The visually param controls
  19981. // whether, in right-to-left text, direction 1 means to move towards
  19982. // the next index in the string, or towards the character to the right
  19983. // of the current position. The resulting position will have a
  19984. // hitSide=true property if it reached the end of the document.
  19985. function findPosH(doc, pos, dir, unit, visually) {
  19986. var oldPos = pos;
  19987. var origDir = dir;
  19988. var lineObj = getLine(doc, pos.line);
  19989. var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  19990. function findNextLine() {
  19991. var l = pos.line + lineDir;
  19992. if (l < doc.first || l >= doc.first + doc.size) { return false }
  19993. pos = new Pos(l, pos.ch, pos.sticky);
  19994. return lineObj = getLine(doc, l)
  19995. }
  19996. function moveOnce(boundToLine) {
  19997. var next;
  19998. if (unit == "codepoint") {
  19999. var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
  20000. if (isNaN(ch)) {
  20001. next = null;
  20002. } else {
  20003. var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
  20004. next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
  20005. }
  20006. } else if (visually) {
  20007. next = moveVisually(doc.cm, lineObj, pos, dir);
  20008. } else {
  20009. next = moveLogically(lineObj, pos, dir);
  20010. }
  20011. if (next == null) {
  20012. if (!boundToLine && findNextLine())
  20013. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  20014. else
  20015. { return false }
  20016. } else {
  20017. pos = next;
  20018. }
  20019. return true
  20020. }
  20021. if (unit == "char" || unit == "codepoint") {
  20022. moveOnce();
  20023. } else if (unit == "column") {
  20024. moveOnce(true);
  20025. } else if (unit == "word" || unit == "group") {
  20026. var sawType = null, group = unit == "group";
  20027. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  20028. for (var first = true;; first = false) {
  20029. if (dir < 0 && !moveOnce(!first)) { break }
  20030. var cur = lineObj.text.charAt(pos.ch) || "\n";
  20031. var type = isWordChar(cur, helper) ? "w"
  20032. : group && cur == "\n" ? "n"
  20033. : !group || /\s/.test(cur) ? null
  20034. : "p";
  20035. if (group && !first && !type) { type = "s"; }
  20036. if (sawType && sawType != type) {
  20037. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  20038. break
  20039. }
  20040. if (type) { sawType = type; }
  20041. if (dir > 0 && !moveOnce(!first)) { break }
  20042. }
  20043. }
  20044. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  20045. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  20046. return result
  20047. }
  20048. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  20049. // "page" or "line". The resulting position will have a hitSide=true
  20050. // property if it reached the end of the document.
  20051. function findPosV(cm, pos, dir, unit) {
  20052. var doc = cm.doc, x = pos.left, y;
  20053. if (unit == "page") {
  20054. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  20055. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  20056. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  20057. } else if (unit == "line") {
  20058. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  20059. }
  20060. var target;
  20061. for (;;) {
  20062. target = coordsChar(cm, x, y);
  20063. if (!target.outside) { break }
  20064. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  20065. y += dir * 5;
  20066. }
  20067. return target
  20068. }
  20069. // CONTENTEDITABLE INPUT STYLE
  20070. var ContentEditableInput = function(cm) {
  20071. this.cm = cm;
  20072. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  20073. this.polling = new Delayed();
  20074. this.composing = null;
  20075. this.gracePeriod = false;
  20076. this.readDOMTimeout = null;
  20077. };
  20078. ContentEditableInput.prototype.init = function (display) {
  20079. var this$1 = this;
  20080. var input = this, cm = input.cm;
  20081. var div = input.div = display.lineDiv;
  20082. div.contentEditable = true;
  20083. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  20084. function belongsToInput(e) {
  20085. for (var t = e.target; t; t = t.parentNode) {
  20086. if (t == div) { return true }
  20087. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  20088. }
  20089. return false
  20090. }
  20091. on(div, "paste", function (e) {
  20092. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  20093. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  20094. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  20095. });
  20096. on(div, "compositionstart", function (e) {
  20097. this$1.composing = {data: e.data, done: false};
  20098. });
  20099. on(div, "compositionupdate", function (e) {
  20100. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  20101. });
  20102. on(div, "compositionend", function (e) {
  20103. if (this$1.composing) {
  20104. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  20105. this$1.composing.done = true;
  20106. }
  20107. });
  20108. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  20109. on(div, "input", function () {
  20110. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  20111. });
  20112. function onCopyCut(e) {
  20113. if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  20114. if (cm.somethingSelected()) {
  20115. setLastCopied({lineWise: false, text: cm.getSelections()});
  20116. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  20117. } else if (!cm.options.lineWiseCopyCut) {
  20118. return
  20119. } else {
  20120. var ranges = copyableRanges(cm);
  20121. setLastCopied({lineWise: true, text: ranges.text});
  20122. if (e.type == "cut") {
  20123. cm.operation(function () {
  20124. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  20125. cm.replaceSelection("", null, "cut");
  20126. });
  20127. }
  20128. }
  20129. if (e.clipboardData) {
  20130. e.clipboardData.clearData();
  20131. var content = lastCopied.text.join("\n");
  20132. // iOS exposes the clipboard API, but seems to discard content inserted into it
  20133. e.clipboardData.setData("Text", content);
  20134. if (e.clipboardData.getData("Text") == content) {
  20135. e.preventDefault();
  20136. return
  20137. }
  20138. }
  20139. // Old-fashioned briefly-focus-a-textarea hack
  20140. var kludge = hiddenTextarea(), te = kludge.firstChild;
  20141. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  20142. te.value = lastCopied.text.join("\n");
  20143. var hadFocus = activeElt();
  20144. selectInput(te);
  20145. setTimeout(function () {
  20146. cm.display.lineSpace.removeChild(kludge);
  20147. hadFocus.focus();
  20148. if (hadFocus == div) { input.showPrimarySelection(); }
  20149. }, 50);
  20150. }
  20151. on(div, "copy", onCopyCut);
  20152. on(div, "cut", onCopyCut);
  20153. };
  20154. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  20155. // Label for screenreaders, accessibility
  20156. if(label) {
  20157. this.div.setAttribute('aria-label', label);
  20158. } else {
  20159. this.div.removeAttribute('aria-label');
  20160. }
  20161. };
  20162. ContentEditableInput.prototype.prepareSelection = function () {
  20163. var result = prepareSelection(this.cm, false);
  20164. result.focus = activeElt() == this.div;
  20165. return result
  20166. };
  20167. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  20168. if (!info || !this.cm.display.view.length) { return }
  20169. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  20170. this.showMultipleSelections(info);
  20171. };
  20172. ContentEditableInput.prototype.getSelection = function () {
  20173. return this.cm.display.wrapper.ownerDocument.getSelection()
  20174. };
  20175. ContentEditableInput.prototype.showPrimarySelection = function () {
  20176. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  20177. var from = prim.from(), to = prim.to();
  20178. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  20179. sel.removeAllRanges();
  20180. return
  20181. }
  20182. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  20183. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  20184. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  20185. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  20186. cmp(maxPos(curAnchor, curFocus), to) == 0)
  20187. { return }
  20188. var view = cm.display.view;
  20189. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  20190. {node: view[0].measure.map[2], offset: 0};
  20191. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  20192. if (!end) {
  20193. var measure = view[view.length - 1].measure;
  20194. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  20195. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  20196. }
  20197. if (!start || !end) {
  20198. sel.removeAllRanges();
  20199. return
  20200. }
  20201. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  20202. try { rng = range(start.node, start.offset, end.offset, end.node); }
  20203. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  20204. if (rng) {
  20205. if (!gecko && cm.state.focused) {
  20206. sel.collapse(start.node, start.offset);
  20207. if (!rng.collapsed) {
  20208. sel.removeAllRanges();
  20209. sel.addRange(rng);
  20210. }
  20211. } else {
  20212. sel.removeAllRanges();
  20213. sel.addRange(rng);
  20214. }
  20215. if (old && sel.anchorNode == null) { sel.addRange(old); }
  20216. else if (gecko) { this.startGracePeriod(); }
  20217. }
  20218. this.rememberSelection();
  20219. };
  20220. ContentEditableInput.prototype.startGracePeriod = function () {
  20221. var this$1 = this;
  20222. clearTimeout(this.gracePeriod);
  20223. this.gracePeriod = setTimeout(function () {
  20224. this$1.gracePeriod = false;
  20225. if (this$1.selectionChanged())
  20226. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  20227. }, 20);
  20228. };
  20229. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  20230. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  20231. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  20232. };
  20233. ContentEditableInput.prototype.rememberSelection = function () {
  20234. var sel = this.getSelection();
  20235. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  20236. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  20237. };
  20238. ContentEditableInput.prototype.selectionInEditor = function () {
  20239. var sel = this.getSelection();
  20240. if (!sel.rangeCount) { return false }
  20241. var node = sel.getRangeAt(0).commonAncestorContainer;
  20242. return contains(this.div, node)
  20243. };
  20244. ContentEditableInput.prototype.focus = function () {
  20245. if (this.cm.options.readOnly != "nocursor") {
  20246. if (!this.selectionInEditor() || activeElt() != this.div)
  20247. { this.showSelection(this.prepareSelection(), true); }
  20248. this.div.focus();
  20249. }
  20250. };
  20251. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  20252. ContentEditableInput.prototype.getField = function () { return this.div };
  20253. ContentEditableInput.prototype.supportsTouch = function () { return true };
  20254. ContentEditableInput.prototype.receivedFocus = function () {
  20255. var this$1 = this;
  20256. var input = this;
  20257. if (this.selectionInEditor())
  20258. { setTimeout(function () { return this$1.pollSelection(); }, 20); }
  20259. else
  20260. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  20261. function poll() {
  20262. if (input.cm.state.focused) {
  20263. input.pollSelection();
  20264. input.polling.set(input.cm.options.pollInterval, poll);
  20265. }
  20266. }
  20267. this.polling.set(this.cm.options.pollInterval, poll);
  20268. };
  20269. ContentEditableInput.prototype.selectionChanged = function () {
  20270. var sel = this.getSelection();
  20271. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  20272. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  20273. };
  20274. ContentEditableInput.prototype.pollSelection = function () {
  20275. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  20276. var sel = this.getSelection(), cm = this.cm;
  20277. // On Android Chrome (version 56, at least), backspacing into an
  20278. // uneditable block element will put the cursor in that element,
  20279. // and then, because it's not editable, hide the virtual keyboard.
  20280. // Because Android doesn't allow us to actually detect backspace
  20281. // presses in a sane way, this code checks for when that happens
  20282. // and simulates a backspace press in this case.
  20283. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  20284. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  20285. this.blur();
  20286. this.focus();
  20287. return
  20288. }
  20289. if (this.composing) { return }
  20290. this.rememberSelection();
  20291. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  20292. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  20293. if (anchor && head) { runInOp(cm, function () {
  20294. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  20295. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  20296. }); }
  20297. };
  20298. ContentEditableInput.prototype.pollContent = function () {
  20299. if (this.readDOMTimeout != null) {
  20300. clearTimeout(this.readDOMTimeout);
  20301. this.readDOMTimeout = null;
  20302. }
  20303. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  20304. var from = sel.from(), to = sel.to();
  20305. if (from.ch == 0 && from.line > cm.firstLine())
  20306. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  20307. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  20308. { to = Pos(to.line + 1, 0); }
  20309. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  20310. var fromIndex, fromLine, fromNode;
  20311. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  20312. fromLine = lineNo(display.view[0].line);
  20313. fromNode = display.view[0].node;
  20314. } else {
  20315. fromLine = lineNo(display.view[fromIndex].line);
  20316. fromNode = display.view[fromIndex - 1].node.nextSibling;
  20317. }
  20318. var toIndex = findViewIndex(cm, to.line);
  20319. var toLine, toNode;
  20320. if (toIndex == display.view.length - 1) {
  20321. toLine = display.viewTo - 1;
  20322. toNode = display.lineDiv.lastChild;
  20323. } else {
  20324. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  20325. toNode = display.view[toIndex + 1].node.previousSibling;
  20326. }
  20327. if (!fromNode) { return false }
  20328. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  20329. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  20330. while (newText.length > 1 && oldText.length > 1) {
  20331. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  20332. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  20333. else { break }
  20334. }
  20335. var cutFront = 0, cutEnd = 0;
  20336. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  20337. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  20338. { ++cutFront; }
  20339. var newBot = lst(newText), oldBot = lst(oldText);
  20340. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  20341. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  20342. while (cutEnd < maxCutEnd &&
  20343. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  20344. { ++cutEnd; }
  20345. // Try to move start of change to start of selection if ambiguous
  20346. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  20347. while (cutFront && cutFront > from.ch &&
  20348. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  20349. cutFront--;
  20350. cutEnd++;
  20351. }
  20352. }
  20353. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  20354. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  20355. var chFrom = Pos(fromLine, cutFront);
  20356. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  20357. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  20358. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  20359. return true
  20360. }
  20361. };
  20362. ContentEditableInput.prototype.ensurePolled = function () {
  20363. this.forceCompositionEnd();
  20364. };
  20365. ContentEditableInput.prototype.reset = function () {
  20366. this.forceCompositionEnd();
  20367. };
  20368. ContentEditableInput.prototype.forceCompositionEnd = function () {
  20369. if (!this.composing) { return }
  20370. clearTimeout(this.readDOMTimeout);
  20371. this.composing = null;
  20372. this.updateFromDOM();
  20373. this.div.blur();
  20374. this.div.focus();
  20375. };
  20376. ContentEditableInput.prototype.readFromDOMSoon = function () {
  20377. var this$1 = this;
  20378. if (this.readDOMTimeout != null) { return }
  20379. this.readDOMTimeout = setTimeout(function () {
  20380. this$1.readDOMTimeout = null;
  20381. if (this$1.composing) {
  20382. if (this$1.composing.done) { this$1.composing = null; }
  20383. else { return }
  20384. }
  20385. this$1.updateFromDOM();
  20386. }, 80);
  20387. };
  20388. ContentEditableInput.prototype.updateFromDOM = function () {
  20389. var this$1 = this;
  20390. if (this.cm.isReadOnly() || !this.pollContent())
  20391. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  20392. };
  20393. ContentEditableInput.prototype.setUneditable = function (node) {
  20394. node.contentEditable = "false";
  20395. };
  20396. ContentEditableInput.prototype.onKeyPress = function (e) {
  20397. if (e.charCode == 0 || this.composing) { return }
  20398. e.preventDefault();
  20399. if (!this.cm.isReadOnly())
  20400. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  20401. };
  20402. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  20403. this.div.contentEditable = String(val != "nocursor");
  20404. };
  20405. ContentEditableInput.prototype.onContextMenu = function () {};
  20406. ContentEditableInput.prototype.resetPosition = function () {};
  20407. ContentEditableInput.prototype.needsContentAttribute = true;
  20408. function posToDOM(cm, pos) {
  20409. var view = findViewForLine(cm, pos.line);
  20410. if (!view || view.hidden) { return null }
  20411. var line = getLine(cm.doc, pos.line);
  20412. var info = mapFromLineView(view, line, pos.line);
  20413. var order = getOrder(line, cm.doc.direction), side = "left";
  20414. if (order) {
  20415. var partPos = getBidiPartAt(order, pos.ch);
  20416. side = partPos % 2 ? "right" : "left";
  20417. }
  20418. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  20419. result.offset = result.collapse == "right" ? result.end : result.start;
  20420. return result
  20421. }
  20422. function isInGutter(node) {
  20423. for (var scan = node; scan; scan = scan.parentNode)
  20424. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  20425. return false
  20426. }
  20427. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  20428. function domTextBetween(cm, from, to, fromLine, toLine) {
  20429. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  20430. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  20431. function close() {
  20432. if (closing) {
  20433. text += lineSep;
  20434. if (extraLinebreak) { text += lineSep; }
  20435. closing = extraLinebreak = false;
  20436. }
  20437. }
  20438. function addText(str) {
  20439. if (str) {
  20440. close();
  20441. text += str;
  20442. }
  20443. }
  20444. function walk(node) {
  20445. if (node.nodeType == 1) {
  20446. var cmText = node.getAttribute("cm-text");
  20447. if (cmText) {
  20448. addText(cmText);
  20449. return
  20450. }
  20451. var markerID = node.getAttribute("cm-marker"), range;
  20452. if (markerID) {
  20453. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  20454. if (found.length && (range = found[0].find(0)))
  20455. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  20456. return
  20457. }
  20458. if (node.getAttribute("contenteditable") == "false") { return }
  20459. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  20460. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  20461. if (isBlock) { close(); }
  20462. for (var i = 0; i < node.childNodes.length; i++)
  20463. { walk(node.childNodes[i]); }
  20464. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  20465. if (isBlock) { closing = true; }
  20466. } else if (node.nodeType == 3) {
  20467. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  20468. }
  20469. }
  20470. for (;;) {
  20471. walk(from);
  20472. if (from == to) { break }
  20473. from = from.nextSibling;
  20474. extraLinebreak = false;
  20475. }
  20476. return text
  20477. }
  20478. function domToPos(cm, node, offset) {
  20479. var lineNode;
  20480. if (node == cm.display.lineDiv) {
  20481. lineNode = cm.display.lineDiv.childNodes[offset];
  20482. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  20483. node = null; offset = 0;
  20484. } else {
  20485. for (lineNode = node;; lineNode = lineNode.parentNode) {
  20486. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  20487. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  20488. }
  20489. }
  20490. for (var i = 0; i < cm.display.view.length; i++) {
  20491. var lineView = cm.display.view[i];
  20492. if (lineView.node == lineNode)
  20493. { return locateNodeInLineView(lineView, node, offset) }
  20494. }
  20495. }
  20496. function locateNodeInLineView(lineView, node, offset) {
  20497. var wrapper = lineView.text.firstChild, bad = false;
  20498. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  20499. if (node == wrapper) {
  20500. bad = true;
  20501. node = wrapper.childNodes[offset];
  20502. offset = 0;
  20503. if (!node) {
  20504. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  20505. return badPos(Pos(lineNo(line), line.text.length), bad)
  20506. }
  20507. }
  20508. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  20509. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  20510. textNode = node.firstChild;
  20511. if (offset) { offset = textNode.nodeValue.length; }
  20512. }
  20513. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  20514. var measure = lineView.measure, maps = measure.maps;
  20515. function find(textNode, topNode, offset) {
  20516. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  20517. var map = i < 0 ? measure.map : maps[i];
  20518. for (var j = 0; j < map.length; j += 3) {
  20519. var curNode = map[j + 2];
  20520. if (curNode == textNode || curNode == topNode) {
  20521. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  20522. var ch = map[j] + offset;
  20523. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  20524. return Pos(line, ch)
  20525. }
  20526. }
  20527. }
  20528. }
  20529. var found = find(textNode, topNode, offset);
  20530. if (found) { return badPos(found, bad) }
  20531. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  20532. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  20533. found = find(after, after.firstChild, 0);
  20534. if (found)
  20535. { return badPos(Pos(found.line, found.ch - dist), bad) }
  20536. else
  20537. { dist += after.textContent.length; }
  20538. }
  20539. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  20540. found = find(before, before.firstChild, -1);
  20541. if (found)
  20542. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  20543. else
  20544. { dist$1 += before.textContent.length; }
  20545. }
  20546. }
  20547. // TEXTAREA INPUT STYLE
  20548. var TextareaInput = function(cm) {
  20549. this.cm = cm;
  20550. // See input.poll and input.reset
  20551. this.prevInput = "";
  20552. // Flag that indicates whether we expect input to appear real soon
  20553. // now (after some event like 'keypress' or 'input') and are
  20554. // polling intensively.
  20555. this.pollingFast = false;
  20556. // Self-resetting timeout for the poller
  20557. this.polling = new Delayed();
  20558. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  20559. this.hasSelection = false;
  20560. this.composing = null;
  20561. };
  20562. TextareaInput.prototype.init = function (display) {
  20563. var this$1 = this;
  20564. var input = this, cm = this.cm;
  20565. this.createField(display);
  20566. var te = this.textarea;
  20567. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  20568. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  20569. if (ios) { te.style.width = "0px"; }
  20570. on(te, "input", function () {
  20571. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  20572. input.poll();
  20573. });
  20574. on(te, "paste", function (e) {
  20575. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  20576. cm.state.pasteIncoming = +new Date;
  20577. input.fastPoll();
  20578. });
  20579. function prepareCopyCut(e) {
  20580. if (signalDOMEvent(cm, e)) { return }
  20581. if (cm.somethingSelected()) {
  20582. setLastCopied({lineWise: false, text: cm.getSelections()});
  20583. } else if (!cm.options.lineWiseCopyCut) {
  20584. return
  20585. } else {
  20586. var ranges = copyableRanges(cm);
  20587. setLastCopied({lineWise: true, text: ranges.text});
  20588. if (e.type == "cut") {
  20589. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  20590. } else {
  20591. input.prevInput = "";
  20592. te.value = ranges.text.join("\n");
  20593. selectInput(te);
  20594. }
  20595. }
  20596. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  20597. }
  20598. on(te, "cut", prepareCopyCut);
  20599. on(te, "copy", prepareCopyCut);
  20600. on(display.scroller, "paste", function (e) {
  20601. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  20602. if (!te.dispatchEvent) {
  20603. cm.state.pasteIncoming = +new Date;
  20604. input.focus();
  20605. return
  20606. }
  20607. // Pass the `paste` event to the textarea so it's handled by its event listener.
  20608. var event = new Event("paste");
  20609. event.clipboardData = e.clipboardData;
  20610. te.dispatchEvent(event);
  20611. });
  20612. // Prevent normal selection in the editor (we handle our own)
  20613. on(display.lineSpace, "selectstart", function (e) {
  20614. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  20615. });
  20616. on(te, "compositionstart", function () {
  20617. var start = cm.getCursor("from");
  20618. if (input.composing) { input.composing.range.clear(); }
  20619. input.composing = {
  20620. start: start,
  20621. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  20622. };
  20623. });
  20624. on(te, "compositionend", function () {
  20625. if (input.composing) {
  20626. input.poll();
  20627. input.composing.range.clear();
  20628. input.composing = null;
  20629. }
  20630. });
  20631. };
  20632. TextareaInput.prototype.createField = function (_display) {
  20633. // Wraps and hides input textarea
  20634. this.wrapper = hiddenTextarea();
  20635. // The semihidden textarea that is focused when the editor is
  20636. // focused, and receives input.
  20637. this.textarea = this.wrapper.firstChild;
  20638. };
  20639. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  20640. // Label for screenreaders, accessibility
  20641. if(label) {
  20642. this.textarea.setAttribute('aria-label', label);
  20643. } else {
  20644. this.textarea.removeAttribute('aria-label');
  20645. }
  20646. };
  20647. TextareaInput.prototype.prepareSelection = function () {
  20648. // Redraw the selection and/or cursor
  20649. var cm = this.cm, display = cm.display, doc = cm.doc;
  20650. var result = prepareSelection(cm);
  20651. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  20652. if (cm.options.moveInputWithCursor) {
  20653. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  20654. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  20655. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  20656. headPos.top + lineOff.top - wrapOff.top));
  20657. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  20658. headPos.left + lineOff.left - wrapOff.left));
  20659. }
  20660. return result
  20661. };
  20662. TextareaInput.prototype.showSelection = function (drawn) {
  20663. var cm = this.cm, display = cm.display;
  20664. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  20665. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  20666. if (drawn.teTop != null) {
  20667. this.wrapper.style.top = drawn.teTop + "px";
  20668. this.wrapper.style.left = drawn.teLeft + "px";
  20669. }
  20670. };
  20671. // Reset the input to correspond to the selection (or to be empty,
  20672. // when not typing and nothing is selected)
  20673. TextareaInput.prototype.reset = function (typing) {
  20674. if (this.contextMenuPending || this.composing) { return }
  20675. var cm = this.cm;
  20676. if (cm.somethingSelected()) {
  20677. this.prevInput = "";
  20678. var content = cm.getSelection();
  20679. this.textarea.value = content;
  20680. if (cm.state.focused) { selectInput(this.textarea); }
  20681. if (ie && ie_version >= 9) { this.hasSelection = content; }
  20682. } else if (!typing) {
  20683. this.prevInput = this.textarea.value = "";
  20684. if (ie && ie_version >= 9) { this.hasSelection = null; }
  20685. }
  20686. };
  20687. TextareaInput.prototype.getField = function () { return this.textarea };
  20688. TextareaInput.prototype.supportsTouch = function () { return false };
  20689. TextareaInput.prototype.focus = function () {
  20690. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  20691. try { this.textarea.focus(); }
  20692. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  20693. }
  20694. };
  20695. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  20696. TextareaInput.prototype.resetPosition = function () {
  20697. this.wrapper.style.top = this.wrapper.style.left = 0;
  20698. };
  20699. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  20700. // Poll for input changes, using the normal rate of polling. This
  20701. // runs as long as the editor is focused.
  20702. TextareaInput.prototype.slowPoll = function () {
  20703. var this$1 = this;
  20704. if (this.pollingFast) { return }
  20705. this.polling.set(this.cm.options.pollInterval, function () {
  20706. this$1.poll();
  20707. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  20708. });
  20709. };
  20710. // When an event has just come in that is likely to add or change
  20711. // something in the input textarea, we poll faster, to ensure that
  20712. // the change appears on the screen quickly.
  20713. TextareaInput.prototype.fastPoll = function () {
  20714. var missed = false, input = this;
  20715. input.pollingFast = true;
  20716. function p() {
  20717. var changed = input.poll();
  20718. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  20719. else {input.pollingFast = false; input.slowPoll();}
  20720. }
  20721. input.polling.set(20, p);
  20722. };
  20723. // Read input from the textarea, and update the document to match.
  20724. // When something is selected, it is present in the textarea, and
  20725. // selected (unless it is huge, in which case a placeholder is
  20726. // used). When nothing is selected, the cursor sits after previously
  20727. // seen text (can be empty), which is stored in prevInput (we must
  20728. // not reset the textarea when typing, because that breaks IME).
  20729. TextareaInput.prototype.poll = function () {
  20730. var this$1 = this;
  20731. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  20732. // Since this is called a *lot*, try to bail out as cheaply as
  20733. // possible when it is clear that nothing happened. hasSelection
  20734. // will be the case when there is a lot of text in the textarea,
  20735. // in which case reading its value would be expensive.
  20736. if (this.contextMenuPending || !cm.state.focused ||
  20737. (hasSelection(input) && !prevInput && !this.composing) ||
  20738. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  20739. { return false }
  20740. var text = input.value;
  20741. // If nothing changed, bail.
  20742. if (text == prevInput && !cm.somethingSelected()) { return false }
  20743. // Work around nonsensical selection resetting in IE9/10, and
  20744. // inexplicable appearance of private area unicode characters on
  20745. // some key combos in Mac (#2689).
  20746. if (ie && ie_version >= 9 && this.hasSelection === text ||
  20747. mac && /[\uf700-\uf7ff]/.test(text)) {
  20748. cm.display.input.reset();
  20749. return false
  20750. }
  20751. if (cm.doc.sel == cm.display.selForContextMenu) {
  20752. var first = text.charCodeAt(0);
  20753. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  20754. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  20755. }
  20756. // Find the part of the input that is actually new
  20757. var same = 0, l = Math.min(prevInput.length, text.length);
  20758. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  20759. runInOp(cm, function () {
  20760. applyTextInput(cm, text.slice(same), prevInput.length - same,
  20761. null, this$1.composing ? "*compose" : null);
  20762. // Don't leave long text in the textarea, since it makes further polling slow
  20763. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  20764. else { this$1.prevInput = text; }
  20765. if (this$1.composing) {
  20766. this$1.composing.range.clear();
  20767. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  20768. {className: "CodeMirror-composing"});
  20769. }
  20770. });
  20771. return true
  20772. };
  20773. TextareaInput.prototype.ensurePolled = function () {
  20774. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  20775. };
  20776. TextareaInput.prototype.onKeyPress = function () {
  20777. if (ie && ie_version >= 9) { this.hasSelection = null; }
  20778. this.fastPoll();
  20779. };
  20780. TextareaInput.prototype.onContextMenu = function (e) {
  20781. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  20782. if (input.contextMenuPending) { input.contextMenuPending(); }
  20783. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  20784. if (!pos || presto) { return } // Opera is difficult.
  20785. // Reset the current text selection only if the click is done outside of the selection
  20786. // and 'resetSelectionOnContextMenu' option is true.
  20787. var reset = cm.options.resetSelectionOnContextMenu;
  20788. if (reset && cm.doc.sel.contains(pos) == -1)
  20789. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  20790. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  20791. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  20792. input.wrapper.style.cssText = "position: static";
  20793. 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);";
  20794. var oldScrollY;
  20795. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  20796. display.input.focus();
  20797. if (webkit) { window.scrollTo(null, oldScrollY); }
  20798. display.input.reset();
  20799. // Adds "Select all" to context menu in FF
  20800. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  20801. input.contextMenuPending = rehide;
  20802. display.selForContextMenu = cm.doc.sel;
  20803. clearTimeout(display.detectingSelectAll);
  20804. // Select-all will be greyed out if there's nothing to select, so
  20805. // this adds a zero-width space so that we can later check whether
  20806. // it got selected.
  20807. function prepareSelectAllHack() {
  20808. if (te.selectionStart != null) {
  20809. var selected = cm.somethingSelected();
  20810. var extval = "\u200b" + (selected ? te.value : "");
  20811. te.value = "\u21da"; // Used to catch context-menu undo
  20812. te.value = extval;
  20813. input.prevInput = selected ? "" : "\u200b";
  20814. te.selectionStart = 1; te.selectionEnd = extval.length;
  20815. // Re-set this, in case some other handler touched the
  20816. // selection in the meantime.
  20817. display.selForContextMenu = cm.doc.sel;
  20818. }
  20819. }
  20820. function rehide() {
  20821. if (input.contextMenuPending != rehide) { return }
  20822. input.contextMenuPending = false;
  20823. input.wrapper.style.cssText = oldWrapperCSS;
  20824. te.style.cssText = oldCSS;
  20825. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  20826. // Try to detect the user choosing select-all
  20827. if (te.selectionStart != null) {
  20828. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  20829. var i = 0, poll = function () {
  20830. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  20831. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  20832. operation(cm, selectAll)(cm);
  20833. } else if (i++ < 10) {
  20834. display.detectingSelectAll = setTimeout(poll, 500);
  20835. } else {
  20836. display.selForContextMenu = null;
  20837. display.input.reset();
  20838. }
  20839. };
  20840. display.detectingSelectAll = setTimeout(poll, 200);
  20841. }
  20842. }
  20843. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  20844. if (captureRightClick) {
  20845. e_stop(e);
  20846. var mouseup = function () {
  20847. off(window, "mouseup", mouseup);
  20848. setTimeout(rehide, 20);
  20849. };
  20850. on(window, "mouseup", mouseup);
  20851. } else {
  20852. setTimeout(rehide, 50);
  20853. }
  20854. };
  20855. TextareaInput.prototype.readOnlyChanged = function (val) {
  20856. if (!val) { this.reset(); }
  20857. this.textarea.disabled = val == "nocursor";
  20858. this.textarea.readOnly = !!val;
  20859. };
  20860. TextareaInput.prototype.setUneditable = function () {};
  20861. TextareaInput.prototype.needsContentAttribute = false;
  20862. function fromTextArea(textarea, options) {
  20863. options = options ? copyObj(options) : {};
  20864. options.value = textarea.value;
  20865. if (!options.tabindex && textarea.tabIndex)
  20866. { options.tabindex = textarea.tabIndex; }
  20867. if (!options.placeholder && textarea.placeholder)
  20868. { options.placeholder = textarea.placeholder; }
  20869. // Set autofocus to true if this textarea is focused, or if it has
  20870. // autofocus and no other element is focused.
  20871. if (options.autofocus == null) {
  20872. var hasFocus = activeElt();
  20873. options.autofocus = hasFocus == textarea ||
  20874. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  20875. }
  20876. function save() {textarea.value = cm.getValue();}
  20877. var realSubmit;
  20878. if (textarea.form) {
  20879. on(textarea.form, "submit", save);
  20880. // Deplorable hack to make the submit method do the right thing.
  20881. if (!options.leaveSubmitMethodAlone) {
  20882. var form = textarea.form;
  20883. realSubmit = form.submit;
  20884. try {
  20885. var wrappedSubmit = form.submit = function () {
  20886. save();
  20887. form.submit = realSubmit;
  20888. form.submit();
  20889. form.submit = wrappedSubmit;
  20890. };
  20891. } catch(e) {}
  20892. }
  20893. }
  20894. options.finishInit = function (cm) {
  20895. cm.save = save;
  20896. cm.getTextArea = function () { return textarea; };
  20897. cm.toTextArea = function () {
  20898. cm.toTextArea = isNaN; // Prevent this from being ran twice
  20899. save();
  20900. textarea.parentNode.removeChild(cm.getWrapperElement());
  20901. textarea.style.display = "";
  20902. if (textarea.form) {
  20903. off(textarea.form, "submit", save);
  20904. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  20905. { textarea.form.submit = realSubmit; }
  20906. }
  20907. };
  20908. };
  20909. textarea.style.display = "none";
  20910. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  20911. options);
  20912. return cm
  20913. }
  20914. function addLegacyProps(CodeMirror) {
  20915. CodeMirror.off = off;
  20916. CodeMirror.on = on;
  20917. CodeMirror.wheelEventPixels = wheelEventPixels;
  20918. CodeMirror.Doc = Doc;
  20919. CodeMirror.splitLines = splitLinesAuto;
  20920. CodeMirror.countColumn = countColumn;
  20921. CodeMirror.findColumn = findColumn;
  20922. CodeMirror.isWordChar = isWordCharBasic;
  20923. CodeMirror.Pass = Pass;
  20924. CodeMirror.signal = signal;
  20925. CodeMirror.Line = Line;
  20926. CodeMirror.changeEnd = changeEnd;
  20927. CodeMirror.scrollbarModel = scrollbarModel;
  20928. CodeMirror.Pos = Pos;
  20929. CodeMirror.cmpPos = cmp;
  20930. CodeMirror.modes = modes;
  20931. CodeMirror.mimeModes = mimeModes;
  20932. CodeMirror.resolveMode = resolveMode;
  20933. CodeMirror.getMode = getMode;
  20934. CodeMirror.modeExtensions = modeExtensions;
  20935. CodeMirror.extendMode = extendMode;
  20936. CodeMirror.copyState = copyState;
  20937. CodeMirror.startState = startState;
  20938. CodeMirror.innerMode = innerMode;
  20939. CodeMirror.commands = commands;
  20940. CodeMirror.keyMap = keyMap;
  20941. CodeMirror.keyName = keyName;
  20942. CodeMirror.isModifierKey = isModifierKey;
  20943. CodeMirror.lookupKey = lookupKey;
  20944. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  20945. CodeMirror.StringStream = StringStream;
  20946. CodeMirror.SharedTextMarker = SharedTextMarker;
  20947. CodeMirror.TextMarker = TextMarker;
  20948. CodeMirror.LineWidget = LineWidget;
  20949. CodeMirror.e_preventDefault = e_preventDefault;
  20950. CodeMirror.e_stopPropagation = e_stopPropagation;
  20951. CodeMirror.e_stop = e_stop;
  20952. CodeMirror.addClass = addClass;
  20953. CodeMirror.contains = contains;
  20954. CodeMirror.rmClass = rmClass;
  20955. CodeMirror.keyNames = keyNames;
  20956. }
  20957. // EDITOR CONSTRUCTOR
  20958. defineOptions(CodeMirror);
  20959. addEditorMethods(CodeMirror);
  20960. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  20961. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  20962. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  20963. { CodeMirror.prototype[prop] = (function(method) {
  20964. return function() {return method.apply(this.doc, arguments)}
  20965. })(Doc.prototype[prop]); } }
  20966. eventMixin(Doc);
  20967. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  20968. // Extra arguments are stored as the mode's dependencies, which is
  20969. // used by (legacy) mechanisms like loadmode.js to automatically
  20970. // load a mode. (Preferred mechanism is the require/define calls.)
  20971. CodeMirror.defineMode = function(name/*, mode, …*/) {
  20972. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  20973. defineMode.apply(this, arguments);
  20974. };
  20975. CodeMirror.defineMIME = defineMIME;
  20976. // Minimal default mode.
  20977. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  20978. CodeMirror.defineMIME("text/plain", "null");
  20979. // EXTENSIONS
  20980. CodeMirror.defineExtension = function (name, func) {
  20981. CodeMirror.prototype[name] = func;
  20982. };
  20983. CodeMirror.defineDocExtension = function (name, func) {
  20984. Doc.prototype[name] = func;
  20985. };
  20986. CodeMirror.fromTextArea = fromTextArea;
  20987. addLegacyProps(CodeMirror);
  20988. CodeMirror.version = "5.64.0";
  20989. return CodeMirror;
  20990. })));
  20991. /***/ }),
  20992. /***/ "./node_modules/decimal.js/decimal.js":
  20993. /*!********************************************!*\
  20994. !*** ./node_modules/decimal.js/decimal.js ***!
  20995. \********************************************/
  20996. /*! no static exports found */
  20997. /***/ (function(module, exports, __webpack_require__) {
  20998. var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalScope) {
  20999. 'use strict';
  21000. /*
  21001. * decimal.js v10.2.0
  21002. * An arbitrary-precision Decimal type for JavaScript.
  21003. * https://github.com/MikeMcl/decimal.js
  21004. * Copyright (c) 2019 Michael Mclaughlin <M8ch88l@gmail.com>
  21005. * MIT Licence
  21006. */
  21007. // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
  21008. // The maximum exponent magnitude.
  21009. // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
  21010. var EXP_LIMIT = 9e15, // 0 to 9e15
  21011. // The limit on the value of `precision`, and on the value of the first argument to
  21012. // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
  21013. MAX_DIGITS = 1e9, // 0 to 1e9
  21014. // Base conversion alphabet.
  21015. NUMERALS = '0123456789abcdef',
  21016. // The natural logarithm of 10 (1025 digits).
  21017. LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
  21018. // Pi (1025 digits).
  21019. PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
  21020. // The initial configuration properties of the Decimal constructor.
  21021. DEFAULTS = {
  21022. // These values must be integers within the stated ranges (inclusive).
  21023. // Most of these values can be changed at run-time using the `Decimal.config` method.
  21024. // The maximum number of significant digits of the result of a calculation or base conversion.
  21025. // E.g. `Decimal.config({ precision: 20 });`
  21026. precision: 20, // 1 to MAX_DIGITS
  21027. // The rounding mode used when rounding to `precision`.
  21028. //
  21029. // ROUND_UP 0 Away from zero.
  21030. // ROUND_DOWN 1 Towards zero.
  21031. // ROUND_CEIL 2 Towards +Infinity.
  21032. // ROUND_FLOOR 3 Towards -Infinity.
  21033. // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
  21034. // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
  21035. // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
  21036. // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
  21037. // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  21038. //
  21039. // E.g.
  21040. // `Decimal.rounding = 4;`
  21041. // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
  21042. rounding: 4, // 0 to 8
  21043. // The modulo mode used when calculating the modulus: a mod n.
  21044. // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
  21045. // The remainder (r) is calculated as: r = a - n * q.
  21046. //
  21047. // UP 0 The remainder is positive if the dividend is negative, else is negative.
  21048. // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).
  21049. // FLOOR 3 The remainder has the same sign as the divisor (Python %).
  21050. // HALF_EVEN 6 The IEEE 754 remainder function.
  21051. // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
  21052. //
  21053. // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
  21054. // division (9) are commonly used for the modulus operation. The other rounding modes can also
  21055. // be used, but they may not give useful results.
  21056. modulo: 1, // 0 to 9
  21057. // The exponent value at and beneath which `toString` returns exponential notation.
  21058. // JavaScript numbers: -7
  21059. toExpNeg: -7, // 0 to -EXP_LIMIT
  21060. // The exponent value at and above which `toString` returns exponential notation.
  21061. // JavaScript numbers: 21
  21062. toExpPos: 21, // 0 to EXP_LIMIT
  21063. // The minimum exponent value, beneath which underflow to zero occurs.
  21064. // JavaScript numbers: -324 (5e-324)
  21065. minE: -EXP_LIMIT, // -1 to -EXP_LIMIT
  21066. // The maximum exponent value, above which overflow to Infinity occurs.
  21067. // JavaScript numbers: 308 (1.7976931348623157e+308)
  21068. maxE: EXP_LIMIT, // 1 to EXP_LIMIT
  21069. // Whether to use cryptographically-secure random number generation, if available.
  21070. crypto: false // true/false
  21071. },
  21072. // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
  21073. Decimal, inexact, noConflict, quadrant,
  21074. external = true,
  21075. decimalError = '[DecimalError] ',
  21076. invalidArgument = decimalError + 'Invalid argument: ',
  21077. precisionLimitExceeded = decimalError + 'Precision limit exceeded',
  21078. cryptoUnavailable = decimalError + 'crypto unavailable',
  21079. mathfloor = Math.floor,
  21080. mathpow = Math.pow,
  21081. isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
  21082. isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
  21083. isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
  21084. isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
  21085. BASE = 1e7,
  21086. LOG_BASE = 7,
  21087. MAX_SAFE_INTEGER = 9007199254740991,
  21088. LN10_PRECISION = LN10.length - 1,
  21089. PI_PRECISION = PI.length - 1,
  21090. // Decimal.prototype object
  21091. P = { name: '[object Decimal]' };
  21092. // Decimal prototype methods
  21093. /*
  21094. * absoluteValue abs
  21095. * ceil
  21096. * comparedTo cmp
  21097. * cosine cos
  21098. * cubeRoot cbrt
  21099. * decimalPlaces dp
  21100. * dividedBy div
  21101. * dividedToIntegerBy divToInt
  21102. * equals eq
  21103. * floor
  21104. * greaterThan gt
  21105. * greaterThanOrEqualTo gte
  21106. * hyperbolicCosine cosh
  21107. * hyperbolicSine sinh
  21108. * hyperbolicTangent tanh
  21109. * inverseCosine acos
  21110. * inverseHyperbolicCosine acosh
  21111. * inverseHyperbolicSine asinh
  21112. * inverseHyperbolicTangent atanh
  21113. * inverseSine asin
  21114. * inverseTangent atan
  21115. * isFinite
  21116. * isInteger isInt
  21117. * isNaN
  21118. * isNegative isNeg
  21119. * isPositive isPos
  21120. * isZero
  21121. * lessThan lt
  21122. * lessThanOrEqualTo lte
  21123. * logarithm log
  21124. * [maximum] [max]
  21125. * [minimum] [min]
  21126. * minus sub
  21127. * modulo mod
  21128. * naturalExponential exp
  21129. * naturalLogarithm ln
  21130. * negated neg
  21131. * plus add
  21132. * precision sd
  21133. * round
  21134. * sine sin
  21135. * squareRoot sqrt
  21136. * tangent tan
  21137. * times mul
  21138. * toBinary
  21139. * toDecimalPlaces toDP
  21140. * toExponential
  21141. * toFixed
  21142. * toFraction
  21143. * toHexadecimal toHex
  21144. * toNearest
  21145. * toNumber
  21146. * toOctal
  21147. * toPower pow
  21148. * toPrecision
  21149. * toSignificantDigits toSD
  21150. * toString
  21151. * truncated trunc
  21152. * valueOf toJSON
  21153. */
  21154. /*
  21155. * Return a new Decimal whose value is the absolute value of this Decimal.
  21156. *
  21157. */
  21158. P.absoluteValue = P.abs = function () {
  21159. var x = new this.constructor(this);
  21160. if (x.s < 0) x.s = 1;
  21161. return finalise(x);
  21162. };
  21163. /*
  21164. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  21165. * direction of positive Infinity.
  21166. *
  21167. */
  21168. P.ceil = function () {
  21169. return finalise(new this.constructor(this), this.e + 1, 2);
  21170. };
  21171. /*
  21172. * Return
  21173. * 1 if the value of this Decimal is greater than the value of `y`,
  21174. * -1 if the value of this Decimal is less than the value of `y`,
  21175. * 0 if they have the same value,
  21176. * NaN if the value of either Decimal is NaN.
  21177. *
  21178. */
  21179. P.comparedTo = P.cmp = function (y) {
  21180. var i, j, xdL, ydL,
  21181. x = this,
  21182. xd = x.d,
  21183. yd = (y = new x.constructor(y)).d,
  21184. xs = x.s,
  21185. ys = y.s;
  21186. // Either NaN or ±Infinity?
  21187. if (!xd || !yd) {
  21188. return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
  21189. }
  21190. // Either zero?
  21191. if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
  21192. // Signs differ?
  21193. if (xs !== ys) return xs;
  21194. // Compare exponents.
  21195. if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
  21196. xdL = xd.length;
  21197. ydL = yd.length;
  21198. // Compare digit by digit.
  21199. for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
  21200. if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
  21201. }
  21202. // Compare lengths.
  21203. return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
  21204. };
  21205. /*
  21206. * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
  21207. *
  21208. * Domain: [-Infinity, Infinity]
  21209. * Range: [-1, 1]
  21210. *
  21211. * cos(0) = 1
  21212. * cos(-0) = 1
  21213. * cos(Infinity) = NaN
  21214. * cos(-Infinity) = NaN
  21215. * cos(NaN) = NaN
  21216. *
  21217. */
  21218. P.cosine = P.cos = function () {
  21219. var pr, rm,
  21220. x = this,
  21221. Ctor = x.constructor;
  21222. if (!x.d) return new Ctor(NaN);
  21223. // cos(0) = cos(-0) = 1
  21224. if (!x.d[0]) return new Ctor(1);
  21225. pr = Ctor.precision;
  21226. rm = Ctor.rounding;
  21227. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  21228. Ctor.rounding = 1;
  21229. x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
  21230. Ctor.precision = pr;
  21231. Ctor.rounding = rm;
  21232. return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
  21233. };
  21234. /*
  21235. *
  21236. * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
  21237. * `precision` significant digits using rounding mode `rounding`.
  21238. *
  21239. * cbrt(0) = 0
  21240. * cbrt(-0) = -0
  21241. * cbrt(1) = 1
  21242. * cbrt(-1) = -1
  21243. * cbrt(N) = N
  21244. * cbrt(-I) = -I
  21245. * cbrt(I) = I
  21246. *
  21247. * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
  21248. *
  21249. */
  21250. P.cubeRoot = P.cbrt = function () {
  21251. var e, m, n, r, rep, s, sd, t, t3, t3plusx,
  21252. x = this,
  21253. Ctor = x.constructor;
  21254. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  21255. external = false;
  21256. // Initial estimate.
  21257. s = x.s * mathpow(x.s * x, 1 / 3);
  21258. // Math.cbrt underflow/overflow?
  21259. // Pass x to Math.pow as integer, then adjust the exponent of the result.
  21260. if (!s || Math.abs(s) == 1 / 0) {
  21261. n = digitsToString(x.d);
  21262. e = x.e;
  21263. // Adjust n exponent so it is a multiple of 3 away from x exponent.
  21264. if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
  21265. s = mathpow(n, 1 / 3);
  21266. // Rarely, e may be one less than the result exponent value.
  21267. e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
  21268. if (s == 1 / 0) {
  21269. n = '5e' + e;
  21270. } else {
  21271. n = s.toExponential();
  21272. n = n.slice(0, n.indexOf('e') + 1) + e;
  21273. }
  21274. r = new Ctor(n);
  21275. r.s = x.s;
  21276. } else {
  21277. r = new Ctor(s.toString());
  21278. }
  21279. sd = (e = Ctor.precision) + 3;
  21280. // Halley's method.
  21281. // TODO? Compare Newton's method.
  21282. for (;;) {
  21283. t = r;
  21284. t3 = t.times(t).times(t);
  21285. t3plusx = t3.plus(x);
  21286. r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
  21287. // TODO? Replace with for-loop and checkRoundingDigits.
  21288. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  21289. n = n.slice(sd - 3, sd + 1);
  21290. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
  21291. // , i.e. approaching a rounding boundary, continue the iteration.
  21292. if (n == '9999' || !rep && n == '4999') {
  21293. // On the first iteration only, check to see if rounding up gives the exact result as the
  21294. // nines may infinitely repeat.
  21295. if (!rep) {
  21296. finalise(t, e + 1, 0);
  21297. if (t.times(t).times(t).eq(x)) {
  21298. r = t;
  21299. break;
  21300. }
  21301. }
  21302. sd += 4;
  21303. rep = 1;
  21304. } else {
  21305. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  21306. // If not, then there are further digits and m will be truthy.
  21307. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  21308. // Truncate to the first rounding digit.
  21309. finalise(r, e + 1, 1);
  21310. m = !r.times(r).times(r).eq(x);
  21311. }
  21312. break;
  21313. }
  21314. }
  21315. }
  21316. external = true;
  21317. return finalise(r, e, Ctor.rounding, m);
  21318. };
  21319. /*
  21320. * Return the number of decimal places of the value of this Decimal.
  21321. *
  21322. */
  21323. P.decimalPlaces = P.dp = function () {
  21324. var w,
  21325. d = this.d,
  21326. n = NaN;
  21327. if (d) {
  21328. w = d.length - 1;
  21329. n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
  21330. // Subtract the number of trailing zeros of the last word.
  21331. w = d[w];
  21332. if (w) for (; w % 10 == 0; w /= 10) n--;
  21333. if (n < 0) n = 0;
  21334. }
  21335. return n;
  21336. };
  21337. /*
  21338. * n / 0 = I
  21339. * n / N = N
  21340. * n / I = 0
  21341. * 0 / n = 0
  21342. * 0 / 0 = N
  21343. * 0 / N = N
  21344. * 0 / I = 0
  21345. * N / n = N
  21346. * N / 0 = N
  21347. * N / N = N
  21348. * N / I = N
  21349. * I / n = I
  21350. * I / 0 = I
  21351. * I / N = N
  21352. * I / I = N
  21353. *
  21354. * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
  21355. * `precision` significant digits using rounding mode `rounding`.
  21356. *
  21357. */
  21358. P.dividedBy = P.div = function (y) {
  21359. return divide(this, new this.constructor(y));
  21360. };
  21361. /*
  21362. * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
  21363. * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
  21364. *
  21365. */
  21366. P.dividedToIntegerBy = P.divToInt = function (y) {
  21367. var x = this,
  21368. Ctor = x.constructor;
  21369. return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
  21370. };
  21371. /*
  21372. * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
  21373. *
  21374. */
  21375. P.equals = P.eq = function (y) {
  21376. return this.cmp(y) === 0;
  21377. };
  21378. /*
  21379. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  21380. * direction of negative Infinity.
  21381. *
  21382. */
  21383. P.floor = function () {
  21384. return finalise(new this.constructor(this), this.e + 1, 3);
  21385. };
  21386. /*
  21387. * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
  21388. * false.
  21389. *
  21390. */
  21391. P.greaterThan = P.gt = function (y) {
  21392. return this.cmp(y) > 0;
  21393. };
  21394. /*
  21395. * Return true if the value of this Decimal is greater than or equal to the value of `y`,
  21396. * otherwise return false.
  21397. *
  21398. */
  21399. P.greaterThanOrEqualTo = P.gte = function (y) {
  21400. var k = this.cmp(y);
  21401. return k == 1 || k === 0;
  21402. };
  21403. /*
  21404. * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
  21405. * Decimal.
  21406. *
  21407. * Domain: [-Infinity, Infinity]
  21408. * Range: [1, Infinity]
  21409. *
  21410. * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
  21411. *
  21412. * cosh(0) = 1
  21413. * cosh(-0) = 1
  21414. * cosh(Infinity) = Infinity
  21415. * cosh(-Infinity) = Infinity
  21416. * cosh(NaN) = NaN
  21417. *
  21418. * x time taken (ms) result
  21419. * 1000 9 9.8503555700852349694e+433
  21420. * 10000 25 4.4034091128314607936e+4342
  21421. * 100000 171 1.4033316802130615897e+43429
  21422. * 1000000 3817 1.5166076984010437725e+434294
  21423. * 10000000 abandoned after 2 minute wait
  21424. *
  21425. * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
  21426. *
  21427. */
  21428. P.hyperbolicCosine = P.cosh = function () {
  21429. var k, n, pr, rm, len,
  21430. x = this,
  21431. Ctor = x.constructor,
  21432. one = new Ctor(1);
  21433. if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
  21434. if (x.isZero()) return one;
  21435. pr = Ctor.precision;
  21436. rm = Ctor.rounding;
  21437. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  21438. Ctor.rounding = 1;
  21439. len = x.d.length;
  21440. // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
  21441. // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
  21442. // Estimate the optimum number of times to use the argument reduction.
  21443. // TODO? Estimation reused from cosine() and may not be optimal here.
  21444. if (len < 32) {
  21445. k = Math.ceil(len / 3);
  21446. n = (1 / tinyPow(4, k)).toString();
  21447. } else {
  21448. k = 16;
  21449. n = '2.3283064365386962890625e-10';
  21450. }
  21451. x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
  21452. // Reverse argument reduction
  21453. var cosh2_x,
  21454. i = k,
  21455. d8 = new Ctor(8);
  21456. for (; i--;) {
  21457. cosh2_x = x.times(x);
  21458. x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
  21459. }
  21460. return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
  21461. };
  21462. /*
  21463. * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
  21464. * Decimal.
  21465. *
  21466. * Domain: [-Infinity, Infinity]
  21467. * Range: [-Infinity, Infinity]
  21468. *
  21469. * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
  21470. *
  21471. * sinh(0) = 0
  21472. * sinh(-0) = -0
  21473. * sinh(Infinity) = Infinity
  21474. * sinh(-Infinity) = -Infinity
  21475. * sinh(NaN) = NaN
  21476. *
  21477. * x time taken (ms)
  21478. * 10 2 ms
  21479. * 100 5 ms
  21480. * 1000 14 ms
  21481. * 10000 82 ms
  21482. * 100000 886 ms 1.4033316802130615897e+43429
  21483. * 200000 2613 ms
  21484. * 300000 5407 ms
  21485. * 400000 8824 ms
  21486. * 500000 13026 ms 8.7080643612718084129e+217146
  21487. * 1000000 48543 ms
  21488. *
  21489. * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
  21490. *
  21491. */
  21492. P.hyperbolicSine = P.sinh = function () {
  21493. var k, pr, rm, len,
  21494. x = this,
  21495. Ctor = x.constructor;
  21496. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  21497. pr = Ctor.precision;
  21498. rm = Ctor.rounding;
  21499. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  21500. Ctor.rounding = 1;
  21501. len = x.d.length;
  21502. if (len < 3) {
  21503. x = taylorSeries(Ctor, 2, x, x, true);
  21504. } else {
  21505. // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
  21506. // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
  21507. // 3 multiplications and 1 addition
  21508. // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
  21509. // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
  21510. // 4 multiplications and 2 additions
  21511. // Estimate the optimum number of times to use the argument reduction.
  21512. k = 1.4 * Math.sqrt(len);
  21513. k = k > 16 ? 16 : k | 0;
  21514. x = x.times(1 / tinyPow(5, k));
  21515. x = taylorSeries(Ctor, 2, x, x, true);
  21516. // Reverse argument reduction
  21517. var sinh2_x,
  21518. d5 = new Ctor(5),
  21519. d16 = new Ctor(16),
  21520. d20 = new Ctor(20);
  21521. for (; k--;) {
  21522. sinh2_x = x.times(x);
  21523. x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
  21524. }
  21525. }
  21526. Ctor.precision = pr;
  21527. Ctor.rounding = rm;
  21528. return finalise(x, pr, rm, true);
  21529. };
  21530. /*
  21531. * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
  21532. * Decimal.
  21533. *
  21534. * Domain: [-Infinity, Infinity]
  21535. * Range: [-1, 1]
  21536. *
  21537. * tanh(x) = sinh(x) / cosh(x)
  21538. *
  21539. * tanh(0) = 0
  21540. * tanh(-0) = -0
  21541. * tanh(Infinity) = 1
  21542. * tanh(-Infinity) = -1
  21543. * tanh(NaN) = NaN
  21544. *
  21545. */
  21546. P.hyperbolicTangent = P.tanh = function () {
  21547. var pr, rm,
  21548. x = this,
  21549. Ctor = x.constructor;
  21550. if (!x.isFinite()) return new Ctor(x.s);
  21551. if (x.isZero()) return new Ctor(x);
  21552. pr = Ctor.precision;
  21553. rm = Ctor.rounding;
  21554. Ctor.precision = pr + 7;
  21555. Ctor.rounding = 1;
  21556. return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
  21557. };
  21558. /*
  21559. * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
  21560. * this Decimal.
  21561. *
  21562. * Domain: [-1, 1]
  21563. * Range: [0, pi]
  21564. *
  21565. * acos(x) = pi/2 - asin(x)
  21566. *
  21567. * acos(0) = pi/2
  21568. * acos(-0) = pi/2
  21569. * acos(1) = 0
  21570. * acos(-1) = pi
  21571. * acos(1/2) = pi/3
  21572. * acos(-1/2) = 2*pi/3
  21573. * acos(|x| > 1) = NaN
  21574. * acos(NaN) = NaN
  21575. *
  21576. */
  21577. P.inverseCosine = P.acos = function () {
  21578. var halfPi,
  21579. x = this,
  21580. Ctor = x.constructor,
  21581. k = x.abs().cmp(1),
  21582. pr = Ctor.precision,
  21583. rm = Ctor.rounding;
  21584. if (k !== -1) {
  21585. return k === 0
  21586. // |x| is 1
  21587. ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
  21588. // |x| > 1 or x is NaN
  21589. : new Ctor(NaN);
  21590. }
  21591. if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
  21592. // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
  21593. Ctor.precision = pr + 6;
  21594. Ctor.rounding = 1;
  21595. x = x.asin();
  21596. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  21597. Ctor.precision = pr;
  21598. Ctor.rounding = rm;
  21599. return halfPi.minus(x);
  21600. };
  21601. /*
  21602. * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
  21603. * value of this Decimal.
  21604. *
  21605. * Domain: [1, Infinity]
  21606. * Range: [0, Infinity]
  21607. *
  21608. * acosh(x) = ln(x + sqrt(x^2 - 1))
  21609. *
  21610. * acosh(x < 1) = NaN
  21611. * acosh(NaN) = NaN
  21612. * acosh(Infinity) = Infinity
  21613. * acosh(-Infinity) = NaN
  21614. * acosh(0) = NaN
  21615. * acosh(-0) = NaN
  21616. * acosh(1) = 0
  21617. * acosh(-1) = NaN
  21618. *
  21619. */
  21620. P.inverseHyperbolicCosine = P.acosh = function () {
  21621. var pr, rm,
  21622. x = this,
  21623. Ctor = x.constructor;
  21624. if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
  21625. if (!x.isFinite()) return new Ctor(x);
  21626. pr = Ctor.precision;
  21627. rm = Ctor.rounding;
  21628. Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
  21629. Ctor.rounding = 1;
  21630. external = false;
  21631. x = x.times(x).minus(1).sqrt().plus(x);
  21632. external = true;
  21633. Ctor.precision = pr;
  21634. Ctor.rounding = rm;
  21635. return x.ln();
  21636. };
  21637. /*
  21638. * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
  21639. * of this Decimal.
  21640. *
  21641. * Domain: [-Infinity, Infinity]
  21642. * Range: [-Infinity, Infinity]
  21643. *
  21644. * asinh(x) = ln(x + sqrt(x^2 + 1))
  21645. *
  21646. * asinh(NaN) = NaN
  21647. * asinh(Infinity) = Infinity
  21648. * asinh(-Infinity) = -Infinity
  21649. * asinh(0) = 0
  21650. * asinh(-0) = -0
  21651. *
  21652. */
  21653. P.inverseHyperbolicSine = P.asinh = function () {
  21654. var pr, rm,
  21655. x = this,
  21656. Ctor = x.constructor;
  21657. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  21658. pr = Ctor.precision;
  21659. rm = Ctor.rounding;
  21660. Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
  21661. Ctor.rounding = 1;
  21662. external = false;
  21663. x = x.times(x).plus(1).sqrt().plus(x);
  21664. external = true;
  21665. Ctor.precision = pr;
  21666. Ctor.rounding = rm;
  21667. return x.ln();
  21668. };
  21669. /*
  21670. * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
  21671. * value of this Decimal.
  21672. *
  21673. * Domain: [-1, 1]
  21674. * Range: [-Infinity, Infinity]
  21675. *
  21676. * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
  21677. *
  21678. * atanh(|x| > 1) = NaN
  21679. * atanh(NaN) = NaN
  21680. * atanh(Infinity) = NaN
  21681. * atanh(-Infinity) = NaN
  21682. * atanh(0) = 0
  21683. * atanh(-0) = -0
  21684. * atanh(1) = Infinity
  21685. * atanh(-1) = -Infinity
  21686. *
  21687. */
  21688. P.inverseHyperbolicTangent = P.atanh = function () {
  21689. var pr, rm, wpr, xsd,
  21690. x = this,
  21691. Ctor = x.constructor;
  21692. if (!x.isFinite()) return new Ctor(NaN);
  21693. if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
  21694. pr = Ctor.precision;
  21695. rm = Ctor.rounding;
  21696. xsd = x.sd();
  21697. if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
  21698. Ctor.precision = wpr = xsd - x.e;
  21699. x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
  21700. Ctor.precision = pr + 4;
  21701. Ctor.rounding = 1;
  21702. x = x.ln();
  21703. Ctor.precision = pr;
  21704. Ctor.rounding = rm;
  21705. return x.times(0.5);
  21706. };
  21707. /*
  21708. * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
  21709. * Decimal.
  21710. *
  21711. * Domain: [-Infinity, Infinity]
  21712. * Range: [-pi/2, pi/2]
  21713. *
  21714. * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
  21715. *
  21716. * asin(0) = 0
  21717. * asin(-0) = -0
  21718. * asin(1/2) = pi/6
  21719. * asin(-1/2) = -pi/6
  21720. * asin(1) = pi/2
  21721. * asin(-1) = -pi/2
  21722. * asin(|x| > 1) = NaN
  21723. * asin(NaN) = NaN
  21724. *
  21725. * TODO? Compare performance of Taylor series.
  21726. *
  21727. */
  21728. P.inverseSine = P.asin = function () {
  21729. var halfPi, k,
  21730. pr, rm,
  21731. x = this,
  21732. Ctor = x.constructor;
  21733. if (x.isZero()) return new Ctor(x);
  21734. k = x.abs().cmp(1);
  21735. pr = Ctor.precision;
  21736. rm = Ctor.rounding;
  21737. if (k !== -1) {
  21738. // |x| is 1
  21739. if (k === 0) {
  21740. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  21741. halfPi.s = x.s;
  21742. return halfPi;
  21743. }
  21744. // |x| > 1 or x is NaN
  21745. return new Ctor(NaN);
  21746. }
  21747. // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
  21748. Ctor.precision = pr + 6;
  21749. Ctor.rounding = 1;
  21750. x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
  21751. Ctor.precision = pr;
  21752. Ctor.rounding = rm;
  21753. return x.times(2);
  21754. };
  21755. /*
  21756. * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
  21757. * of this Decimal.
  21758. *
  21759. * Domain: [-Infinity, Infinity]
  21760. * Range: [-pi/2, pi/2]
  21761. *
  21762. * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  21763. *
  21764. * atan(0) = 0
  21765. * atan(-0) = -0
  21766. * atan(1) = pi/4
  21767. * atan(-1) = -pi/4
  21768. * atan(Infinity) = pi/2
  21769. * atan(-Infinity) = -pi/2
  21770. * atan(NaN) = NaN
  21771. *
  21772. */
  21773. P.inverseTangent = P.atan = function () {
  21774. var i, j, k, n, px, t, r, wpr, x2,
  21775. x = this,
  21776. Ctor = x.constructor,
  21777. pr = Ctor.precision,
  21778. rm = Ctor.rounding;
  21779. if (!x.isFinite()) {
  21780. if (!x.s) return new Ctor(NaN);
  21781. if (pr + 4 <= PI_PRECISION) {
  21782. r = getPi(Ctor, pr + 4, rm).times(0.5);
  21783. r.s = x.s;
  21784. return r;
  21785. }
  21786. } else if (x.isZero()) {
  21787. return new Ctor(x);
  21788. } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
  21789. r = getPi(Ctor, pr + 4, rm).times(0.25);
  21790. r.s = x.s;
  21791. return r;
  21792. }
  21793. Ctor.precision = wpr = pr + 10;
  21794. Ctor.rounding = 1;
  21795. // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
  21796. // Argument reduction
  21797. // Ensure |x| < 0.42
  21798. // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
  21799. k = Math.min(28, wpr / LOG_BASE + 2 | 0);
  21800. for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
  21801. external = false;
  21802. j = Math.ceil(wpr / LOG_BASE);
  21803. n = 1;
  21804. x2 = x.times(x);
  21805. r = new Ctor(x);
  21806. px = x;
  21807. // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  21808. for (; i !== -1;) {
  21809. px = px.times(x2);
  21810. t = r.minus(px.div(n += 2));
  21811. px = px.times(x2);
  21812. r = t.plus(px.div(n += 2));
  21813. if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
  21814. }
  21815. if (k) r = r.times(2 << (k - 1));
  21816. external = true;
  21817. return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
  21818. };
  21819. /*
  21820. * Return true if the value of this Decimal is a finite number, otherwise return false.
  21821. *
  21822. */
  21823. P.isFinite = function () {
  21824. return !!this.d;
  21825. };
  21826. /*
  21827. * Return true if the value of this Decimal is an integer, otherwise return false.
  21828. *
  21829. */
  21830. P.isInteger = P.isInt = function () {
  21831. return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
  21832. };
  21833. /*
  21834. * Return true if the value of this Decimal is NaN, otherwise return false.
  21835. *
  21836. */
  21837. P.isNaN = function () {
  21838. return !this.s;
  21839. };
  21840. /*
  21841. * Return true if the value of this Decimal is negative, otherwise return false.
  21842. *
  21843. */
  21844. P.isNegative = P.isNeg = function () {
  21845. return this.s < 0;
  21846. };
  21847. /*
  21848. * Return true if the value of this Decimal is positive, otherwise return false.
  21849. *
  21850. */
  21851. P.isPositive = P.isPos = function () {
  21852. return this.s > 0;
  21853. };
  21854. /*
  21855. * Return true if the value of this Decimal is 0 or -0, otherwise return false.
  21856. *
  21857. */
  21858. P.isZero = function () {
  21859. return !!this.d && this.d[0] === 0;
  21860. };
  21861. /*
  21862. * Return true if the value of this Decimal is less than `y`, otherwise return false.
  21863. *
  21864. */
  21865. P.lessThan = P.lt = function (y) {
  21866. return this.cmp(y) < 0;
  21867. };
  21868. /*
  21869. * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
  21870. *
  21871. */
  21872. P.lessThanOrEqualTo = P.lte = function (y) {
  21873. return this.cmp(y) < 1;
  21874. };
  21875. /*
  21876. * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
  21877. * significant digits using rounding mode `rounding`.
  21878. *
  21879. * If no base is specified, return log[10](arg).
  21880. *
  21881. * log[base](arg) = ln(arg) / ln(base)
  21882. *
  21883. * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
  21884. * otherwise:
  21885. *
  21886. * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
  21887. * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
  21888. * between the result and the correctly rounded result will be one ulp (unit in the last place).
  21889. *
  21890. * log[-b](a) = NaN
  21891. * log[0](a) = NaN
  21892. * log[1](a) = NaN
  21893. * log[NaN](a) = NaN
  21894. * log[Infinity](a) = NaN
  21895. * log[b](0) = -Infinity
  21896. * log[b](-0) = -Infinity
  21897. * log[b](-a) = NaN
  21898. * log[b](1) = 0
  21899. * log[b](Infinity) = Infinity
  21900. * log[b](NaN) = NaN
  21901. *
  21902. * [base] {number|string|Decimal} The base of the logarithm.
  21903. *
  21904. */
  21905. P.logarithm = P.log = function (base) {
  21906. var isBase10, d, denominator, k, inf, num, sd, r,
  21907. arg = this,
  21908. Ctor = arg.constructor,
  21909. pr = Ctor.precision,
  21910. rm = Ctor.rounding,
  21911. guard = 5;
  21912. // Default base is 10.
  21913. if (base == null) {
  21914. base = new Ctor(10);
  21915. isBase10 = true;
  21916. } else {
  21917. base = new Ctor(base);
  21918. d = base.d;
  21919. // Return NaN if base is negative, or non-finite, or is 0 or 1.
  21920. if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
  21921. isBase10 = base.eq(10);
  21922. }
  21923. d = arg.d;
  21924. // Is arg negative, non-finite, 0 or 1?
  21925. if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
  21926. return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
  21927. }
  21928. // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
  21929. // integer power of 10.
  21930. if (isBase10) {
  21931. if (d.length > 1) {
  21932. inf = true;
  21933. } else {
  21934. for (k = d[0]; k % 10 === 0;) k /= 10;
  21935. inf = k !== 1;
  21936. }
  21937. }
  21938. external = false;
  21939. sd = pr + guard;
  21940. num = naturalLogarithm(arg, sd);
  21941. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  21942. // The result will have 5 rounding digits.
  21943. r = divide(num, denominator, sd, 1);
  21944. // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
  21945. // calculate 10 further digits.
  21946. //
  21947. // If the result is known to have an infinite decimal expansion, repeat this until it is clear
  21948. // that the result is above or below the boundary. Otherwise, if after calculating the 10
  21949. // further digits, the last 14 are nines, round up and assume the result is exact.
  21950. // Also assume the result is exact if the last 14 are zero.
  21951. //
  21952. // Example of a result that will be incorrectly rounded:
  21953. // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
  21954. // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
  21955. // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
  21956. // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
  21957. // place is still 2.6.
  21958. if (checkRoundingDigits(r.d, k = pr, rm)) {
  21959. do {
  21960. sd += 10;
  21961. num = naturalLogarithm(arg, sd);
  21962. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  21963. r = divide(num, denominator, sd, 1);
  21964. if (!inf) {
  21965. // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
  21966. if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
  21967. r = finalise(r, pr + 1, 0);
  21968. }
  21969. break;
  21970. }
  21971. } while (checkRoundingDigits(r.d, k += 10, rm));
  21972. }
  21973. external = true;
  21974. return finalise(r, pr, rm);
  21975. };
  21976. /*
  21977. * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
  21978. *
  21979. * arguments {number|string|Decimal}
  21980. *
  21981. P.max = function () {
  21982. Array.prototype.push.call(arguments, this);
  21983. return maxOrMin(this.constructor, arguments, 'lt');
  21984. };
  21985. */
  21986. /*
  21987. * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
  21988. *
  21989. * arguments {number|string|Decimal}
  21990. *
  21991. P.min = function () {
  21992. Array.prototype.push.call(arguments, this);
  21993. return maxOrMin(this.constructor, arguments, 'gt');
  21994. };
  21995. */
  21996. /*
  21997. * n - 0 = n
  21998. * n - N = N
  21999. * n - I = -I
  22000. * 0 - n = -n
  22001. * 0 - 0 = 0
  22002. * 0 - N = N
  22003. * 0 - I = -I
  22004. * N - n = N
  22005. * N - 0 = N
  22006. * N - N = N
  22007. * N - I = N
  22008. * I - n = I
  22009. * I - 0 = I
  22010. * I - N = N
  22011. * I - I = N
  22012. *
  22013. * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
  22014. * significant digits using rounding mode `rounding`.
  22015. *
  22016. */
  22017. P.minus = P.sub = function (y) {
  22018. var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
  22019. x = this,
  22020. Ctor = x.constructor;
  22021. y = new Ctor(y);
  22022. // If either is not finite...
  22023. if (!x.d || !y.d) {
  22024. // Return NaN if either is NaN.
  22025. if (!x.s || !y.s) y = new Ctor(NaN);
  22026. // Return y negated if x is finite and y is ±Infinity.
  22027. else if (x.d) y.s = -y.s;
  22028. // Return x if y is finite and x is ±Infinity.
  22029. // Return x if both are ±Infinity with different signs.
  22030. // Return NaN if both are ±Infinity with the same sign.
  22031. else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
  22032. return y;
  22033. }
  22034. // If signs differ...
  22035. if (x.s != y.s) {
  22036. y.s = -y.s;
  22037. return x.plus(y);
  22038. }
  22039. xd = x.d;
  22040. yd = y.d;
  22041. pr = Ctor.precision;
  22042. rm = Ctor.rounding;
  22043. // If either is zero...
  22044. if (!xd[0] || !yd[0]) {
  22045. // Return y negated if x is zero and y is non-zero.
  22046. if (yd[0]) y.s = -y.s;
  22047. // Return x if y is zero and x is non-zero.
  22048. else if (xd[0]) y = new Ctor(x);
  22049. // Return zero if both are zero.
  22050. // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
  22051. else return new Ctor(rm === 3 ? -0 : 0);
  22052. return external ? finalise(y, pr, rm) : y;
  22053. }
  22054. // x and y are finite, non-zero numbers with the same sign.
  22055. // Calculate base 1e7 exponents.
  22056. e = mathfloor(y.e / LOG_BASE);
  22057. xe = mathfloor(x.e / LOG_BASE);
  22058. xd = xd.slice();
  22059. k = xe - e;
  22060. // If base 1e7 exponents differ...
  22061. if (k) {
  22062. xLTy = k < 0;
  22063. if (xLTy) {
  22064. d = xd;
  22065. k = -k;
  22066. len = yd.length;
  22067. } else {
  22068. d = yd;
  22069. e = xe;
  22070. len = xd.length;
  22071. }
  22072. // Numbers with massively different exponents would result in a very high number of
  22073. // zeros needing to be prepended, but this can be avoided while still ensuring correct
  22074. // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
  22075. i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
  22076. if (k > i) {
  22077. k = i;
  22078. d.length = 1;
  22079. }
  22080. // Prepend zeros to equalise exponents.
  22081. d.reverse();
  22082. for (i = k; i--;) d.push(0);
  22083. d.reverse();
  22084. // Base 1e7 exponents equal.
  22085. } else {
  22086. // Check digits to determine which is the bigger number.
  22087. i = xd.length;
  22088. len = yd.length;
  22089. xLTy = i < len;
  22090. if (xLTy) len = i;
  22091. for (i = 0; i < len; i++) {
  22092. if (xd[i] != yd[i]) {
  22093. xLTy = xd[i] < yd[i];
  22094. break;
  22095. }
  22096. }
  22097. k = 0;
  22098. }
  22099. if (xLTy) {
  22100. d = xd;
  22101. xd = yd;
  22102. yd = d;
  22103. y.s = -y.s;
  22104. }
  22105. len = xd.length;
  22106. // Append zeros to `xd` if shorter.
  22107. // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
  22108. for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
  22109. // Subtract yd from xd.
  22110. for (i = yd.length; i > k;) {
  22111. if (xd[--i] < yd[i]) {
  22112. for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
  22113. --xd[j];
  22114. xd[i] += BASE;
  22115. }
  22116. xd[i] -= yd[i];
  22117. }
  22118. // Remove trailing zeros.
  22119. for (; xd[--len] === 0;) xd.pop();
  22120. // Remove leading zeros and adjust exponent accordingly.
  22121. for (; xd[0] === 0; xd.shift()) --e;
  22122. // Zero?
  22123. if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
  22124. y.d = xd;
  22125. y.e = getBase10Exponent(xd, e);
  22126. return external ? finalise(y, pr, rm) : y;
  22127. };
  22128. /*
  22129. * n % 0 = N
  22130. * n % N = N
  22131. * n % I = n
  22132. * 0 % n = 0
  22133. * -0 % n = -0
  22134. * 0 % 0 = N
  22135. * 0 % N = N
  22136. * 0 % I = 0
  22137. * N % n = N
  22138. * N % 0 = N
  22139. * N % N = N
  22140. * N % I = N
  22141. * I % n = N
  22142. * I % 0 = N
  22143. * I % N = N
  22144. * I % I = N
  22145. *
  22146. * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
  22147. * `precision` significant digits using rounding mode `rounding`.
  22148. *
  22149. * The result depends on the modulo mode.
  22150. *
  22151. */
  22152. P.modulo = P.mod = function (y) {
  22153. var q,
  22154. x = this,
  22155. Ctor = x.constructor;
  22156. y = new Ctor(y);
  22157. // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
  22158. if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
  22159. // Return x if y is ±Infinity or x is ±0.
  22160. if (!y.d || x.d && !x.d[0]) {
  22161. return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
  22162. }
  22163. // Prevent rounding of intermediate calculations.
  22164. external = false;
  22165. if (Ctor.modulo == 9) {
  22166. // Euclidian division: q = sign(y) * floor(x / abs(y))
  22167. // result = x - q * y where 0 <= result < abs(y)
  22168. q = divide(x, y.abs(), 0, 3, 1);
  22169. q.s *= y.s;
  22170. } else {
  22171. q = divide(x, y, 0, Ctor.modulo, 1);
  22172. }
  22173. q = q.times(y);
  22174. external = true;
  22175. return x.minus(q);
  22176. };
  22177. /*
  22178. * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
  22179. * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
  22180. * significant digits using rounding mode `rounding`.
  22181. *
  22182. */
  22183. P.naturalExponential = P.exp = function () {
  22184. return naturalExponential(this);
  22185. };
  22186. /*
  22187. * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
  22188. * rounded to `precision` significant digits using rounding mode `rounding`.
  22189. *
  22190. */
  22191. P.naturalLogarithm = P.ln = function () {
  22192. return naturalLogarithm(this);
  22193. };
  22194. /*
  22195. * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
  22196. * -1.
  22197. *
  22198. */
  22199. P.negated = P.neg = function () {
  22200. var x = new this.constructor(this);
  22201. x.s = -x.s;
  22202. return finalise(x);
  22203. };
  22204. /*
  22205. * n + 0 = n
  22206. * n + N = N
  22207. * n + I = I
  22208. * 0 + n = n
  22209. * 0 + 0 = 0
  22210. * 0 + N = N
  22211. * 0 + I = I
  22212. * N + n = N
  22213. * N + 0 = N
  22214. * N + N = N
  22215. * N + I = N
  22216. * I + n = I
  22217. * I + 0 = I
  22218. * I + N = N
  22219. * I + I = I
  22220. *
  22221. * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
  22222. * significant digits using rounding mode `rounding`.
  22223. *
  22224. */
  22225. P.plus = P.add = function (y) {
  22226. var carry, d, e, i, k, len, pr, rm, xd, yd,
  22227. x = this,
  22228. Ctor = x.constructor;
  22229. y = new Ctor(y);
  22230. // If either is not finite...
  22231. if (!x.d || !y.d) {
  22232. // Return NaN if either is NaN.
  22233. if (!x.s || !y.s) y = new Ctor(NaN);
  22234. // Return x if y is finite and x is ±Infinity.
  22235. // Return x if both are ±Infinity with the same sign.
  22236. // Return NaN if both are ±Infinity with different signs.
  22237. // Return y if x is finite and y is ±Infinity.
  22238. else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
  22239. return y;
  22240. }
  22241. // If signs differ...
  22242. if (x.s != y.s) {
  22243. y.s = -y.s;
  22244. return x.minus(y);
  22245. }
  22246. xd = x.d;
  22247. yd = y.d;
  22248. pr = Ctor.precision;
  22249. rm = Ctor.rounding;
  22250. // If either is zero...
  22251. if (!xd[0] || !yd[0]) {
  22252. // Return x if y is zero.
  22253. // Return y if y is non-zero.
  22254. if (!yd[0]) y = new Ctor(x);
  22255. return external ? finalise(y, pr, rm) : y;
  22256. }
  22257. // x and y are finite, non-zero numbers with the same sign.
  22258. // Calculate base 1e7 exponents.
  22259. k = mathfloor(x.e / LOG_BASE);
  22260. e = mathfloor(y.e / LOG_BASE);
  22261. xd = xd.slice();
  22262. i = k - e;
  22263. // If base 1e7 exponents differ...
  22264. if (i) {
  22265. if (i < 0) {
  22266. d = xd;
  22267. i = -i;
  22268. len = yd.length;
  22269. } else {
  22270. d = yd;
  22271. e = k;
  22272. len = xd.length;
  22273. }
  22274. // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
  22275. k = Math.ceil(pr / LOG_BASE);
  22276. len = k > len ? k + 1 : len + 1;
  22277. if (i > len) {
  22278. i = len;
  22279. d.length = 1;
  22280. }
  22281. // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
  22282. d.reverse();
  22283. for (; i--;) d.push(0);
  22284. d.reverse();
  22285. }
  22286. len = xd.length;
  22287. i = yd.length;
  22288. // If yd is longer than xd, swap xd and yd so xd points to the longer array.
  22289. if (len - i < 0) {
  22290. i = len;
  22291. d = yd;
  22292. yd = xd;
  22293. xd = d;
  22294. }
  22295. // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
  22296. for (carry = 0; i;) {
  22297. carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
  22298. xd[i] %= BASE;
  22299. }
  22300. if (carry) {
  22301. xd.unshift(carry);
  22302. ++e;
  22303. }
  22304. // Remove trailing zeros.
  22305. // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  22306. for (len = xd.length; xd[--len] == 0;) xd.pop();
  22307. y.d = xd;
  22308. y.e = getBase10Exponent(xd, e);
  22309. return external ? finalise(y, pr, rm) : y;
  22310. };
  22311. /*
  22312. * Return the number of significant digits of the value of this Decimal.
  22313. *
  22314. * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
  22315. *
  22316. */
  22317. P.precision = P.sd = function (z) {
  22318. var k,
  22319. x = this;
  22320. if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
  22321. if (x.d) {
  22322. k = getPrecision(x.d);
  22323. if (z && x.e + 1 > k) k = x.e + 1;
  22324. } else {
  22325. k = NaN;
  22326. }
  22327. return k;
  22328. };
  22329. /*
  22330. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
  22331. * rounding mode `rounding`.
  22332. *
  22333. */
  22334. P.round = function () {
  22335. var x = this,
  22336. Ctor = x.constructor;
  22337. return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
  22338. };
  22339. /*
  22340. * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
  22341. *
  22342. * Domain: [-Infinity, Infinity]
  22343. * Range: [-1, 1]
  22344. *
  22345. * sin(x) = x - x^3/3! + x^5/5! - ...
  22346. *
  22347. * sin(0) = 0
  22348. * sin(-0) = -0
  22349. * sin(Infinity) = NaN
  22350. * sin(-Infinity) = NaN
  22351. * sin(NaN) = NaN
  22352. *
  22353. */
  22354. P.sine = P.sin = function () {
  22355. var pr, rm,
  22356. x = this,
  22357. Ctor = x.constructor;
  22358. if (!x.isFinite()) return new Ctor(NaN);
  22359. if (x.isZero()) return new Ctor(x);
  22360. pr = Ctor.precision;
  22361. rm = Ctor.rounding;
  22362. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  22363. Ctor.rounding = 1;
  22364. x = sine(Ctor, toLessThanHalfPi(Ctor, x));
  22365. Ctor.precision = pr;
  22366. Ctor.rounding = rm;
  22367. return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
  22368. };
  22369. /*
  22370. * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
  22371. * significant digits using rounding mode `rounding`.
  22372. *
  22373. * sqrt(-n) = N
  22374. * sqrt(N) = N
  22375. * sqrt(-I) = N
  22376. * sqrt(I) = I
  22377. * sqrt(0) = 0
  22378. * sqrt(-0) = -0
  22379. *
  22380. */
  22381. P.squareRoot = P.sqrt = function () {
  22382. var m, n, sd, r, rep, t,
  22383. x = this,
  22384. d = x.d,
  22385. e = x.e,
  22386. s = x.s,
  22387. Ctor = x.constructor;
  22388. // Negative/NaN/Infinity/zero?
  22389. if (s !== 1 || !d || !d[0]) {
  22390. return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
  22391. }
  22392. external = false;
  22393. // Initial estimate.
  22394. s = Math.sqrt(+x);
  22395. // Math.sqrt underflow/overflow?
  22396. // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  22397. if (s == 0 || s == 1 / 0) {
  22398. n = digitsToString(d);
  22399. if ((n.length + e) % 2 == 0) n += '0';
  22400. s = Math.sqrt(n);
  22401. e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
  22402. if (s == 1 / 0) {
  22403. n = '1e' + e;
  22404. } else {
  22405. n = s.toExponential();
  22406. n = n.slice(0, n.indexOf('e') + 1) + e;
  22407. }
  22408. r = new Ctor(n);
  22409. } else {
  22410. r = new Ctor(s.toString());
  22411. }
  22412. sd = (e = Ctor.precision) + 3;
  22413. // Newton-Raphson iteration.
  22414. for (;;) {
  22415. t = r;
  22416. r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
  22417. // TODO? Replace with for-loop and checkRoundingDigits.
  22418. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  22419. n = n.slice(sd - 3, sd + 1);
  22420. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
  22421. // 4999, i.e. approaching a rounding boundary, continue the iteration.
  22422. if (n == '9999' || !rep && n == '4999') {
  22423. // On the first iteration only, check to see if rounding up gives the exact result as the
  22424. // nines may infinitely repeat.
  22425. if (!rep) {
  22426. finalise(t, e + 1, 0);
  22427. if (t.times(t).eq(x)) {
  22428. r = t;
  22429. break;
  22430. }
  22431. }
  22432. sd += 4;
  22433. rep = 1;
  22434. } else {
  22435. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  22436. // If not, then there are further digits and m will be truthy.
  22437. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  22438. // Truncate to the first rounding digit.
  22439. finalise(r, e + 1, 1);
  22440. m = !r.times(r).eq(x);
  22441. }
  22442. break;
  22443. }
  22444. }
  22445. }
  22446. external = true;
  22447. return finalise(r, e, Ctor.rounding, m);
  22448. };
  22449. /*
  22450. * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
  22451. *
  22452. * Domain: [-Infinity, Infinity]
  22453. * Range: [-Infinity, Infinity]
  22454. *
  22455. * tan(0) = 0
  22456. * tan(-0) = -0
  22457. * tan(Infinity) = NaN
  22458. * tan(-Infinity) = NaN
  22459. * tan(NaN) = NaN
  22460. *
  22461. */
  22462. P.tangent = P.tan = function () {
  22463. var pr, rm,
  22464. x = this,
  22465. Ctor = x.constructor;
  22466. if (!x.isFinite()) return new Ctor(NaN);
  22467. if (x.isZero()) return new Ctor(x);
  22468. pr = Ctor.precision;
  22469. rm = Ctor.rounding;
  22470. Ctor.precision = pr + 10;
  22471. Ctor.rounding = 1;
  22472. x = x.sin();
  22473. x.s = 1;
  22474. x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
  22475. Ctor.precision = pr;
  22476. Ctor.rounding = rm;
  22477. return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
  22478. };
  22479. /*
  22480. * n * 0 = 0
  22481. * n * N = N
  22482. * n * I = I
  22483. * 0 * n = 0
  22484. * 0 * 0 = 0
  22485. * 0 * N = N
  22486. * 0 * I = N
  22487. * N * n = N
  22488. * N * 0 = N
  22489. * N * N = N
  22490. * N * I = N
  22491. * I * n = I
  22492. * I * 0 = N
  22493. * I * N = N
  22494. * I * I = I
  22495. *
  22496. * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
  22497. * digits using rounding mode `rounding`.
  22498. *
  22499. */
  22500. P.times = P.mul = function (y) {
  22501. var carry, e, i, k, r, rL, t, xdL, ydL,
  22502. x = this,
  22503. Ctor = x.constructor,
  22504. xd = x.d,
  22505. yd = (y = new Ctor(y)).d;
  22506. y.s *= x.s;
  22507. // If either is NaN, ±Infinity or ±0...
  22508. if (!xd || !xd[0] || !yd || !yd[0]) {
  22509. return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
  22510. // Return NaN if either is NaN.
  22511. // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
  22512. ? NaN
  22513. // Return ±Infinity if either is ±Infinity.
  22514. // Return ±0 if either is ±0.
  22515. : !xd || !yd ? y.s / 0 : y.s * 0);
  22516. }
  22517. e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
  22518. xdL = xd.length;
  22519. ydL = yd.length;
  22520. // Ensure xd points to the longer array.
  22521. if (xdL < ydL) {
  22522. r = xd;
  22523. xd = yd;
  22524. yd = r;
  22525. rL = xdL;
  22526. xdL = ydL;
  22527. ydL = rL;
  22528. }
  22529. // Initialise the result array with zeros.
  22530. r = [];
  22531. rL = xdL + ydL;
  22532. for (i = rL; i--;) r.push(0);
  22533. // Multiply!
  22534. for (i = ydL; --i >= 0;) {
  22535. carry = 0;
  22536. for (k = xdL + i; k > i;) {
  22537. t = r[k] + yd[i] * xd[k - i - 1] + carry;
  22538. r[k--] = t % BASE | 0;
  22539. carry = t / BASE | 0;
  22540. }
  22541. r[k] = (r[k] + carry) % BASE | 0;
  22542. }
  22543. // Remove trailing zeros.
  22544. for (; !r[--rL];) r.pop();
  22545. if (carry) ++e;
  22546. else r.shift();
  22547. y.d = r;
  22548. y.e = getBase10Exponent(r, e);
  22549. return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
  22550. };
  22551. /*
  22552. * Return a string representing the value of this Decimal in base 2, round to `sd` significant
  22553. * digits using rounding mode `rm`.
  22554. *
  22555. * If the optional `sd` argument is present then return binary exponential notation.
  22556. *
  22557. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22558. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22559. *
  22560. */
  22561. P.toBinary = function (sd, rm) {
  22562. return toStringBinary(this, 2, sd, rm);
  22563. };
  22564. /*
  22565. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
  22566. * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
  22567. *
  22568. * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
  22569. *
  22570. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  22571. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22572. *
  22573. */
  22574. P.toDecimalPlaces = P.toDP = function (dp, rm) {
  22575. var x = this,
  22576. Ctor = x.constructor;
  22577. x = new Ctor(x);
  22578. if (dp === void 0) return x;
  22579. checkInt32(dp, 0, MAX_DIGITS);
  22580. if (rm === void 0) rm = Ctor.rounding;
  22581. else checkInt32(rm, 0, 8);
  22582. return finalise(x, dp + x.e + 1, rm);
  22583. };
  22584. /*
  22585. * Return a string representing the value of this Decimal in exponential notation rounded to
  22586. * `dp` fixed decimal places using rounding mode `rounding`.
  22587. *
  22588. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  22589. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22590. *
  22591. */
  22592. P.toExponential = function (dp, rm) {
  22593. var str,
  22594. x = this,
  22595. Ctor = x.constructor;
  22596. if (dp === void 0) {
  22597. str = finiteToString(x, true);
  22598. } else {
  22599. checkInt32(dp, 0, MAX_DIGITS);
  22600. if (rm === void 0) rm = Ctor.rounding;
  22601. else checkInt32(rm, 0, 8);
  22602. x = finalise(new Ctor(x), dp + 1, rm);
  22603. str = finiteToString(x, true, dp + 1);
  22604. }
  22605. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22606. };
  22607. /*
  22608. * Return a string representing the value of this Decimal in normal (fixed-point) notation to
  22609. * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
  22610. * omitted.
  22611. *
  22612. * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
  22613. *
  22614. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  22615. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22616. *
  22617. * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
  22618. * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
  22619. * (-0).toFixed(3) is '0.000'.
  22620. * (-0.5).toFixed(0) is '-0'.
  22621. *
  22622. */
  22623. P.toFixed = function (dp, rm) {
  22624. var str, y,
  22625. x = this,
  22626. Ctor = x.constructor;
  22627. if (dp === void 0) {
  22628. str = finiteToString(x);
  22629. } else {
  22630. checkInt32(dp, 0, MAX_DIGITS);
  22631. if (rm === void 0) rm = Ctor.rounding;
  22632. else checkInt32(rm, 0, 8);
  22633. y = finalise(new Ctor(x), dp + x.e + 1, rm);
  22634. str = finiteToString(y, false, dp + y.e + 1);
  22635. }
  22636. // To determine whether to add the minus sign look at the value before it was rounded,
  22637. // i.e. look at `x` rather than `y`.
  22638. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22639. };
  22640. /*
  22641. * Return an array representing the value of this Decimal as a simple fraction with an integer
  22642. * numerator and an integer denominator.
  22643. *
  22644. * The denominator will be a positive non-zero value less than or equal to the specified maximum
  22645. * denominator. If a maximum denominator is not specified, the denominator will be the lowest
  22646. * value necessary to represent the number exactly.
  22647. *
  22648. * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
  22649. *
  22650. */
  22651. P.toFraction = function (maxD) {
  22652. var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
  22653. x = this,
  22654. xd = x.d,
  22655. Ctor = x.constructor;
  22656. if (!xd) return new Ctor(x);
  22657. n1 = d0 = new Ctor(1);
  22658. d1 = n0 = new Ctor(0);
  22659. d = new Ctor(d1);
  22660. e = d.e = getPrecision(xd) - x.e - 1;
  22661. k = e % LOG_BASE;
  22662. d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
  22663. if (maxD == null) {
  22664. // d is 10**e, the minimum max-denominator needed.
  22665. maxD = e > 0 ? d : n1;
  22666. } else {
  22667. n = new Ctor(maxD);
  22668. if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
  22669. maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
  22670. }
  22671. external = false;
  22672. n = new Ctor(digitsToString(xd));
  22673. pr = Ctor.precision;
  22674. Ctor.precision = e = xd.length * LOG_BASE * 2;
  22675. for (;;) {
  22676. q = divide(n, d, 0, 1, 1);
  22677. d2 = d0.plus(q.times(d1));
  22678. if (d2.cmp(maxD) == 1) break;
  22679. d0 = d1;
  22680. d1 = d2;
  22681. d2 = n1;
  22682. n1 = n0.plus(q.times(d2));
  22683. n0 = d2;
  22684. d2 = d;
  22685. d = n.minus(q.times(d2));
  22686. n = d2;
  22687. }
  22688. d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
  22689. n0 = n0.plus(d2.times(n1));
  22690. d0 = d0.plus(d2.times(d1));
  22691. n0.s = n1.s = x.s;
  22692. // Determine which fraction is closer to x, n0/d0 or n1/d1?
  22693. r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
  22694. ? [n1, d1] : [n0, d0];
  22695. Ctor.precision = pr;
  22696. external = true;
  22697. return r;
  22698. };
  22699. /*
  22700. * Return a string representing the value of this Decimal in base 16, round to `sd` significant
  22701. * digits using rounding mode `rm`.
  22702. *
  22703. * If the optional `sd` argument is present then return binary exponential notation.
  22704. *
  22705. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22706. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22707. *
  22708. */
  22709. P.toHexadecimal = P.toHex = function (sd, rm) {
  22710. return toStringBinary(this, 16, sd, rm);
  22711. };
  22712. /*
  22713. * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding
  22714. * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.
  22715. *
  22716. * The return value will always have the same sign as this Decimal, unless either this Decimal
  22717. * or `y` is NaN, in which case the return value will be also be NaN.
  22718. *
  22719. * The return value is not affected by the value of `precision`.
  22720. *
  22721. * y {number|string|Decimal} The magnitude to round to a multiple of.
  22722. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22723. *
  22724. * 'toNearest() rounding mode not an integer: {rm}'
  22725. * 'toNearest() rounding mode out of range: {rm}'
  22726. *
  22727. */
  22728. P.toNearest = function (y, rm) {
  22729. var x = this,
  22730. Ctor = x.constructor;
  22731. x = new Ctor(x);
  22732. if (y == null) {
  22733. // If x is not finite, return x.
  22734. if (!x.d) return x;
  22735. y = new Ctor(1);
  22736. rm = Ctor.rounding;
  22737. } else {
  22738. y = new Ctor(y);
  22739. if (rm === void 0) {
  22740. rm = Ctor.rounding;
  22741. } else {
  22742. checkInt32(rm, 0, 8);
  22743. }
  22744. // If x is not finite, return x if y is not NaN, else NaN.
  22745. if (!x.d) return y.s ? x : y;
  22746. // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
  22747. if (!y.d) {
  22748. if (y.s) y.s = x.s;
  22749. return y;
  22750. }
  22751. }
  22752. // If y is not zero, calculate the nearest multiple of y to x.
  22753. if (y.d[0]) {
  22754. external = false;
  22755. x = divide(x, y, 0, rm, 1).times(y);
  22756. external = true;
  22757. finalise(x);
  22758. // If y is zero, return zero with the sign of x.
  22759. } else {
  22760. y.s = x.s;
  22761. x = y;
  22762. }
  22763. return x;
  22764. };
  22765. /*
  22766. * Return the value of this Decimal converted to a number primitive.
  22767. * Zero keeps its sign.
  22768. *
  22769. */
  22770. P.toNumber = function () {
  22771. return +this;
  22772. };
  22773. /*
  22774. * Return a string representing the value of this Decimal in base 8, round to `sd` significant
  22775. * digits using rounding mode `rm`.
  22776. *
  22777. * If the optional `sd` argument is present then return binary exponential notation.
  22778. *
  22779. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22780. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22781. *
  22782. */
  22783. P.toOctal = function (sd, rm) {
  22784. return toStringBinary(this, 8, sd, rm);
  22785. };
  22786. /*
  22787. * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
  22788. * to `precision` significant digits using rounding mode `rounding`.
  22789. *
  22790. * ECMAScript compliant.
  22791. *
  22792. * pow(x, NaN) = NaN
  22793. * pow(x, ±0) = 1
  22794. * pow(NaN, non-zero) = NaN
  22795. * pow(abs(x) > 1, +Infinity) = +Infinity
  22796. * pow(abs(x) > 1, -Infinity) = +0
  22797. * pow(abs(x) == 1, ±Infinity) = NaN
  22798. * pow(abs(x) < 1, +Infinity) = +0
  22799. * pow(abs(x) < 1, -Infinity) = +Infinity
  22800. * pow(+Infinity, y > 0) = +Infinity
  22801. * pow(+Infinity, y < 0) = +0
  22802. * pow(-Infinity, odd integer > 0) = -Infinity
  22803. * pow(-Infinity, even integer > 0) = +Infinity
  22804. * pow(-Infinity, odd integer < 0) = -0
  22805. * pow(-Infinity, even integer < 0) = +0
  22806. * pow(+0, y > 0) = +0
  22807. * pow(+0, y < 0) = +Infinity
  22808. * pow(-0, odd integer > 0) = -0
  22809. * pow(-0, even integer > 0) = +0
  22810. * pow(-0, odd integer < 0) = -Infinity
  22811. * pow(-0, even integer < 0) = +Infinity
  22812. * pow(finite x < 0, finite non-integer) = NaN
  22813. *
  22814. * For non-integer or very large exponents pow(x, y) is calculated using
  22815. *
  22816. * x^y = exp(y*ln(x))
  22817. *
  22818. * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
  22819. * probability of an incorrectly rounded result
  22820. * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
  22821. * i.e. 1 in 250,000,000,000,000
  22822. *
  22823. * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
  22824. *
  22825. * y {number|string|Decimal} The power to which to raise this Decimal.
  22826. *
  22827. */
  22828. P.toPower = P.pow = function (y) {
  22829. var e, k, pr, r, rm, s,
  22830. x = this,
  22831. Ctor = x.constructor,
  22832. yn = +(y = new Ctor(y));
  22833. // Either ±Infinity, NaN or ±0?
  22834. if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
  22835. x = new Ctor(x);
  22836. if (x.eq(1)) return x;
  22837. pr = Ctor.precision;
  22838. rm = Ctor.rounding;
  22839. if (y.eq(1)) return finalise(x, pr, rm);
  22840. // y exponent
  22841. e = mathfloor(y.e / LOG_BASE);
  22842. // If y is a small integer use the 'exponentiation by squaring' algorithm.
  22843. if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
  22844. r = intPow(Ctor, x, k, pr);
  22845. return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
  22846. }
  22847. s = x.s;
  22848. // if x is negative
  22849. if (s < 0) {
  22850. // if y is not an integer
  22851. if (e < y.d.length - 1) return new Ctor(NaN);
  22852. // Result is positive if x is negative and the last digit of integer y is even.
  22853. if ((y.d[e] & 1) == 0) s = 1;
  22854. // if x.eq(-1)
  22855. if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
  22856. x.s = s;
  22857. return x;
  22858. }
  22859. }
  22860. // Estimate result exponent.
  22861. // x^y = 10^e, where e = y * log10(x)
  22862. // log10(x) = log10(x_significand) + x_exponent
  22863. // log10(x_significand) = ln(x_significand) / ln(10)
  22864. k = mathpow(+x, yn);
  22865. e = k == 0 || !isFinite(k)
  22866. ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
  22867. : new Ctor(k + '').e;
  22868. // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
  22869. // Overflow/underflow?
  22870. if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);
  22871. external = false;
  22872. Ctor.rounding = x.s = 1;
  22873. // Estimate the extra guard digits needed to ensure five correct rounding digits from
  22874. // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
  22875. // new Decimal(2.32456).pow('2087987436534566.46411')
  22876. // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
  22877. k = Math.min(12, (e + '').length);
  22878. // r = x^y = exp(y*ln(x))
  22879. r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
  22880. // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
  22881. if (r.d) {
  22882. // Truncate to the required precision plus five rounding digits.
  22883. r = finalise(r, pr + 5, 1);
  22884. // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
  22885. // the result.
  22886. if (checkRoundingDigits(r.d, pr, rm)) {
  22887. e = pr + 10;
  22888. // Truncate to the increased precision plus five rounding digits.
  22889. r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
  22890. // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
  22891. if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
  22892. r = finalise(r, pr + 1, 0);
  22893. }
  22894. }
  22895. }
  22896. r.s = s;
  22897. external = true;
  22898. Ctor.rounding = rm;
  22899. return finalise(r, pr, rm);
  22900. };
  22901. /*
  22902. * Return a string representing the value of this Decimal rounded to `sd` significant digits
  22903. * using rounding mode `rounding`.
  22904. *
  22905. * Return exponential notation if `sd` is less than the number of digits necessary to represent
  22906. * the integer part of the value in normal notation.
  22907. *
  22908. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22909. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22910. *
  22911. */
  22912. P.toPrecision = function (sd, rm) {
  22913. var str,
  22914. x = this,
  22915. Ctor = x.constructor;
  22916. if (sd === void 0) {
  22917. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  22918. } else {
  22919. checkInt32(sd, 1, MAX_DIGITS);
  22920. if (rm === void 0) rm = Ctor.rounding;
  22921. else checkInt32(rm, 0, 8);
  22922. x = finalise(new Ctor(x), sd, rm);
  22923. str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
  22924. }
  22925. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22926. };
  22927. /*
  22928. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
  22929. * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
  22930. * omitted.
  22931. *
  22932. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  22933. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  22934. *
  22935. * 'toSD() digits out of range: {sd}'
  22936. * 'toSD() digits not an integer: {sd}'
  22937. * 'toSD() rounding mode not an integer: {rm}'
  22938. * 'toSD() rounding mode out of range: {rm}'
  22939. *
  22940. */
  22941. P.toSignificantDigits = P.toSD = function (sd, rm) {
  22942. var x = this,
  22943. Ctor = x.constructor;
  22944. if (sd === void 0) {
  22945. sd = Ctor.precision;
  22946. rm = Ctor.rounding;
  22947. } else {
  22948. checkInt32(sd, 1, MAX_DIGITS);
  22949. if (rm === void 0) rm = Ctor.rounding;
  22950. else checkInt32(rm, 0, 8);
  22951. }
  22952. return finalise(new Ctor(x), sd, rm);
  22953. };
  22954. /*
  22955. * Return a string representing the value of this Decimal.
  22956. *
  22957. * Return exponential notation if this Decimal has a positive exponent equal to or greater than
  22958. * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
  22959. *
  22960. */
  22961. P.toString = function () {
  22962. var x = this,
  22963. Ctor = x.constructor,
  22964. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  22965. return x.isNeg() && !x.isZero() ? '-' + str : str;
  22966. };
  22967. /*
  22968. * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
  22969. *
  22970. */
  22971. P.truncated = P.trunc = function () {
  22972. return finalise(new this.constructor(this), this.e + 1, 1);
  22973. };
  22974. /*
  22975. * Return a string representing the value of this Decimal.
  22976. * Unlike `toString`, negative zero will include the minus sign.
  22977. *
  22978. */
  22979. P.valueOf = P.toJSON = function () {
  22980. var x = this,
  22981. Ctor = x.constructor,
  22982. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  22983. return x.isNeg() ? '-' + str : str;
  22984. };
  22985. /*
  22986. // Add aliases to match BigDecimal method names.
  22987. // P.add = P.plus;
  22988. P.subtract = P.minus;
  22989. P.multiply = P.times;
  22990. P.divide = P.div;
  22991. P.remainder = P.mod;
  22992. P.compareTo = P.cmp;
  22993. P.negate = P.neg;
  22994. */
  22995. // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
  22996. /*
  22997. * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
  22998. * finiteToString, naturalExponential, naturalLogarithm
  22999. * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
  23000. * P.toPrecision, P.toSignificantDigits, toStringBinary, random
  23001. * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm
  23002. * convertBase toStringBinary, parseOther
  23003. * cos P.cos
  23004. * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
  23005. * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
  23006. * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
  23007. * taylorSeries, atan2, parseOther
  23008. * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
  23009. * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
  23010. * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
  23011. * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
  23012. * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
  23013. * P.truncated, divide, getLn10, getPi, naturalExponential,
  23014. * naturalLogarithm, ceil, floor, round, trunc
  23015. * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
  23016. * toStringBinary
  23017. * getBase10Exponent P.minus, P.plus, P.times, parseOther
  23018. * getLn10 P.logarithm, naturalLogarithm
  23019. * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
  23020. * getPrecision P.precision, P.toFraction
  23021. * getZeroString digitsToString, finiteToString
  23022. * intPow P.toPower, parseOther
  23023. * isOdd toLessThanHalfPi
  23024. * maxOrMin max, min
  23025. * naturalExponential P.naturalExponential, P.toPower
  23026. * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
  23027. * P.toPower, naturalExponential
  23028. * nonFiniteToString finiteToString, toStringBinary
  23029. * parseDecimal Decimal
  23030. * parseOther Decimal
  23031. * sin P.sin
  23032. * taylorSeries P.cosh, P.sinh, cos, sin
  23033. * toLessThanHalfPi P.cos, P.sin
  23034. * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal
  23035. * truncate intPow
  23036. *
  23037. * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
  23038. * naturalLogarithm, config, parseOther, random, Decimal
  23039. */
  23040. function digitsToString(d) {
  23041. var i, k, ws,
  23042. indexOfLastWord = d.length - 1,
  23043. str = '',
  23044. w = d[0];
  23045. if (indexOfLastWord > 0) {
  23046. str += w;
  23047. for (i = 1; i < indexOfLastWord; i++) {
  23048. ws = d[i] + '';
  23049. k = LOG_BASE - ws.length;
  23050. if (k) str += getZeroString(k);
  23051. str += ws;
  23052. }
  23053. w = d[i];
  23054. ws = w + '';
  23055. k = LOG_BASE - ws.length;
  23056. if (k) str += getZeroString(k);
  23057. } else if (w === 0) {
  23058. return '0';
  23059. }
  23060. // Remove trailing zeros of last w.
  23061. for (; w % 10 === 0;) w /= 10;
  23062. return str + w;
  23063. }
  23064. function checkInt32(i, min, max) {
  23065. if (i !== ~~i || i < min || i > max) {
  23066. throw Error(invalidArgument + i);
  23067. }
  23068. }
  23069. /*
  23070. * Check 5 rounding digits if `repeating` is null, 4 otherwise.
  23071. * `repeating == null` if caller is `log` or `pow`,
  23072. * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
  23073. */
  23074. function checkRoundingDigits(d, i, rm, repeating) {
  23075. var di, k, r, rd;
  23076. // Get the length of the first word of the array d.
  23077. for (k = d[0]; k >= 10; k /= 10) --i;
  23078. // Is the rounding digit in the first word of d?
  23079. if (--i < 0) {
  23080. i += LOG_BASE;
  23081. di = 0;
  23082. } else {
  23083. di = Math.ceil((i + 1) / LOG_BASE);
  23084. i %= LOG_BASE;
  23085. }
  23086. // i is the index (0 - 6) of the rounding digit.
  23087. // E.g. if within the word 3487563 the first rounding digit is 5,
  23088. // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
  23089. k = mathpow(10, LOG_BASE - i);
  23090. rd = d[di] % k | 0;
  23091. if (repeating == null) {
  23092. if (i < 3) {
  23093. if (i == 0) rd = rd / 100 | 0;
  23094. else if (i == 1) rd = rd / 10 | 0;
  23095. r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
  23096. } else {
  23097. r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
  23098. (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
  23099. (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
  23100. }
  23101. } else {
  23102. if (i < 4) {
  23103. if (i == 0) rd = rd / 1000 | 0;
  23104. else if (i == 1) rd = rd / 100 | 0;
  23105. else if (i == 2) rd = rd / 10 | 0;
  23106. r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
  23107. } else {
  23108. r = ((repeating || rm < 4) && rd + 1 == k ||
  23109. (!repeating && rm > 3) && rd + 1 == k / 2) &&
  23110. (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
  23111. }
  23112. }
  23113. return r;
  23114. }
  23115. // Convert string of `baseIn` to an array of numbers of `baseOut`.
  23116. // Eg. convertBase('255', 10, 16) returns [15, 15].
  23117. // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
  23118. function convertBase(str, baseIn, baseOut) {
  23119. var j,
  23120. arr = [0],
  23121. arrL,
  23122. i = 0,
  23123. strL = str.length;
  23124. for (; i < strL;) {
  23125. for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
  23126. arr[0] += NUMERALS.indexOf(str.charAt(i++));
  23127. for (j = 0; j < arr.length; j++) {
  23128. if (arr[j] > baseOut - 1) {
  23129. if (arr[j + 1] === void 0) arr[j + 1] = 0;
  23130. arr[j + 1] += arr[j] / baseOut | 0;
  23131. arr[j] %= baseOut;
  23132. }
  23133. }
  23134. }
  23135. return arr.reverse();
  23136. }
  23137. /*
  23138. * cos(x) = 1 - x^2/2! + x^4/4! - ...
  23139. * |x| < pi/2
  23140. *
  23141. */
  23142. function cosine(Ctor, x) {
  23143. var k, y,
  23144. len = x.d.length;
  23145. // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
  23146. // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
  23147. // Estimate the optimum number of times to use the argument reduction.
  23148. if (len < 32) {
  23149. k = Math.ceil(len / 3);
  23150. y = (1 / tinyPow(4, k)).toString();
  23151. } else {
  23152. k = 16;
  23153. y = '2.3283064365386962890625e-10';
  23154. }
  23155. Ctor.precision += k;
  23156. x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
  23157. // Reverse argument reduction
  23158. for (var i = k; i--;) {
  23159. var cos2x = x.times(x);
  23160. x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
  23161. }
  23162. Ctor.precision -= k;
  23163. return x;
  23164. }
  23165. /*
  23166. * Perform division in the specified base.
  23167. */
  23168. var divide = (function () {
  23169. // Assumes non-zero x and k, and hence non-zero result.
  23170. function multiplyInteger(x, k, base) {
  23171. var temp,
  23172. carry = 0,
  23173. i = x.length;
  23174. for (x = x.slice(); i--;) {
  23175. temp = x[i] * k + carry;
  23176. x[i] = temp % base | 0;
  23177. carry = temp / base | 0;
  23178. }
  23179. if (carry) x.unshift(carry);
  23180. return x;
  23181. }
  23182. function compare(a, b, aL, bL) {
  23183. var i, r;
  23184. if (aL != bL) {
  23185. r = aL > bL ? 1 : -1;
  23186. } else {
  23187. for (i = r = 0; i < aL; i++) {
  23188. if (a[i] != b[i]) {
  23189. r = a[i] > b[i] ? 1 : -1;
  23190. break;
  23191. }
  23192. }
  23193. }
  23194. return r;
  23195. }
  23196. function subtract(a, b, aL, base) {
  23197. var i = 0;
  23198. // Subtract b from a.
  23199. for (; aL--;) {
  23200. a[aL] -= i;
  23201. i = a[aL] < b[aL] ? 1 : 0;
  23202. a[aL] = i * base + a[aL] - b[aL];
  23203. }
  23204. // Remove leading zeros.
  23205. for (; !a[0] && a.length > 1;) a.shift();
  23206. }
  23207. return function (x, y, pr, rm, dp, base) {
  23208. var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
  23209. yL, yz,
  23210. Ctor = x.constructor,
  23211. sign = x.s == y.s ? 1 : -1,
  23212. xd = x.d,
  23213. yd = y.d;
  23214. // Either NaN, Infinity or 0?
  23215. if (!xd || !xd[0] || !yd || !yd[0]) {
  23216. return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
  23217. !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
  23218. // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
  23219. xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
  23220. }
  23221. if (base) {
  23222. logBase = 1;
  23223. e = x.e - y.e;
  23224. } else {
  23225. base = BASE;
  23226. logBase = LOG_BASE;
  23227. e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
  23228. }
  23229. yL = yd.length;
  23230. xL = xd.length;
  23231. q = new Ctor(sign);
  23232. qd = q.d = [];
  23233. // Result exponent may be one less than e.
  23234. // The digit array of a Decimal from toStringBinary may have trailing zeros.
  23235. for (i = 0; yd[i] == (xd[i] || 0); i++);
  23236. if (yd[i] > (xd[i] || 0)) e--;
  23237. if (pr == null) {
  23238. sd = pr = Ctor.precision;
  23239. rm = Ctor.rounding;
  23240. } else if (dp) {
  23241. sd = pr + (x.e - y.e) + 1;
  23242. } else {
  23243. sd = pr;
  23244. }
  23245. if (sd < 0) {
  23246. qd.push(1);
  23247. more = true;
  23248. } else {
  23249. // Convert precision in number of base 10 digits to base 1e7 digits.
  23250. sd = sd / logBase + 2 | 0;
  23251. i = 0;
  23252. // divisor < 1e7
  23253. if (yL == 1) {
  23254. k = 0;
  23255. yd = yd[0];
  23256. sd++;
  23257. // k is the carry.
  23258. for (; (i < xL || k) && sd--; i++) {
  23259. t = k * base + (xd[i] || 0);
  23260. qd[i] = t / yd | 0;
  23261. k = t % yd | 0;
  23262. }
  23263. more = k || i < xL;
  23264. // divisor >= 1e7
  23265. } else {
  23266. // Normalise xd and yd so highest order digit of yd is >= base/2
  23267. k = base / (yd[0] + 1) | 0;
  23268. if (k > 1) {
  23269. yd = multiplyInteger(yd, k, base);
  23270. xd = multiplyInteger(xd, k, base);
  23271. yL = yd.length;
  23272. xL = xd.length;
  23273. }
  23274. xi = yL;
  23275. rem = xd.slice(0, yL);
  23276. remL = rem.length;
  23277. // Add zeros to make remainder as long as divisor.
  23278. for (; remL < yL;) rem[remL++] = 0;
  23279. yz = yd.slice();
  23280. yz.unshift(0);
  23281. yd0 = yd[0];
  23282. if (yd[1] >= base / 2) ++yd0;
  23283. do {
  23284. k = 0;
  23285. // Compare divisor and remainder.
  23286. cmp = compare(yd, rem, yL, remL);
  23287. // If divisor < remainder.
  23288. if (cmp < 0) {
  23289. // Calculate trial digit, k.
  23290. rem0 = rem[0];
  23291. if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
  23292. // k will be how many times the divisor goes into the current remainder.
  23293. k = rem0 / yd0 | 0;
  23294. // Algorithm:
  23295. // 1. product = divisor * trial digit (k)
  23296. // 2. if product > remainder: product -= divisor, k--
  23297. // 3. remainder -= product
  23298. // 4. if product was < remainder at 2:
  23299. // 5. compare new remainder and divisor
  23300. // 6. If remainder > divisor: remainder -= divisor, k++
  23301. if (k > 1) {
  23302. if (k >= base) k = base - 1;
  23303. // product = divisor * trial digit.
  23304. prod = multiplyInteger(yd, k, base);
  23305. prodL = prod.length;
  23306. remL = rem.length;
  23307. // Compare product and remainder.
  23308. cmp = compare(prod, rem, prodL, remL);
  23309. // product > remainder.
  23310. if (cmp == 1) {
  23311. k--;
  23312. // Subtract divisor from product.
  23313. subtract(prod, yL < prodL ? yz : yd, prodL, base);
  23314. }
  23315. } else {
  23316. // cmp is -1.
  23317. // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
  23318. // to avoid it. If k is 1 there is a need to compare yd and rem again below.
  23319. if (k == 0) cmp = k = 1;
  23320. prod = yd.slice();
  23321. }
  23322. prodL = prod.length;
  23323. if (prodL < remL) prod.unshift(0);
  23324. // Subtract product from remainder.
  23325. subtract(rem, prod, remL, base);
  23326. // If product was < previous remainder.
  23327. if (cmp == -1) {
  23328. remL = rem.length;
  23329. // Compare divisor and new remainder.
  23330. cmp = compare(yd, rem, yL, remL);
  23331. // If divisor < new remainder, subtract divisor from remainder.
  23332. if (cmp < 1) {
  23333. k++;
  23334. // Subtract divisor from remainder.
  23335. subtract(rem, yL < remL ? yz : yd, remL, base);
  23336. }
  23337. }
  23338. remL = rem.length;
  23339. } else if (cmp === 0) {
  23340. k++;
  23341. rem = [0];
  23342. } // if cmp === 1, k will be 0
  23343. // Add the next digit, k, to the result array.
  23344. qd[i++] = k;
  23345. // Update the remainder.
  23346. if (cmp && rem[0]) {
  23347. rem[remL++] = xd[xi] || 0;
  23348. } else {
  23349. rem = [xd[xi]];
  23350. remL = 1;
  23351. }
  23352. } while ((xi++ < xL || rem[0] !== void 0) && sd--);
  23353. more = rem[0] !== void 0;
  23354. }
  23355. // Leading zero?
  23356. if (!qd[0]) qd.shift();
  23357. }
  23358. // logBase is 1 when divide is being used for base conversion.
  23359. if (logBase == 1) {
  23360. q.e = e;
  23361. inexact = more;
  23362. } else {
  23363. // To calculate q.e, first get the number of digits of qd[0].
  23364. for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
  23365. q.e = i + e * logBase - 1;
  23366. finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
  23367. }
  23368. return q;
  23369. };
  23370. })();
  23371. /*
  23372. * Round `x` to `sd` significant digits using rounding mode `rm`.
  23373. * Check for over/under-flow.
  23374. */
  23375. function finalise(x, sd, rm, isTruncated) {
  23376. var digits, i, j, k, rd, roundUp, w, xd, xdi,
  23377. Ctor = x.constructor;
  23378. // Don't round if sd is null or undefined.
  23379. out: if (sd != null) {
  23380. xd = x.d;
  23381. // Infinity/NaN.
  23382. if (!xd) return x;
  23383. // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
  23384. // w: the word of xd containing rd, a base 1e7 number.
  23385. // xdi: the index of w within xd.
  23386. // digits: the number of digits of w.
  23387. // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
  23388. // they had leading zeros)
  23389. // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
  23390. // Get the length of the first word of the digits array xd.
  23391. for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
  23392. i = sd - digits;
  23393. // Is the rounding digit in the first word of xd?
  23394. if (i < 0) {
  23395. i += LOG_BASE;
  23396. j = sd;
  23397. w = xd[xdi = 0];
  23398. // Get the rounding digit at index j of w.
  23399. rd = w / mathpow(10, digits - j - 1) % 10 | 0;
  23400. } else {
  23401. xdi = Math.ceil((i + 1) / LOG_BASE);
  23402. k = xd.length;
  23403. if (xdi >= k) {
  23404. if (isTruncated) {
  23405. // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
  23406. for (; k++ <= xdi;) xd.push(0);
  23407. w = rd = 0;
  23408. digits = 1;
  23409. i %= LOG_BASE;
  23410. j = i - LOG_BASE + 1;
  23411. } else {
  23412. break out;
  23413. }
  23414. } else {
  23415. w = k = xd[xdi];
  23416. // Get the number of digits of w.
  23417. for (digits = 1; k >= 10; k /= 10) digits++;
  23418. // Get the index of rd within w.
  23419. i %= LOG_BASE;
  23420. // Get the index of rd within w, adjusted for leading zeros.
  23421. // The number of leading zeros of w is given by LOG_BASE - digits.
  23422. j = i - LOG_BASE + digits;
  23423. // Get the rounding digit at index j of w.
  23424. rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
  23425. }
  23426. }
  23427. // Are there any non-zero digits after the rounding digit?
  23428. isTruncated = isTruncated || sd < 0 ||
  23429. xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
  23430. // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
  23431. // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
  23432. // will give 714.
  23433. roundUp = rm < 4
  23434. ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
  23435. : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
  23436. // Check whether the digit to the left of the rounding digit is odd.
  23437. ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
  23438. rm == (x.s < 0 ? 8 : 7));
  23439. if (sd < 1 || !xd[0]) {
  23440. xd.length = 0;
  23441. if (roundUp) {
  23442. // Convert sd to decimal places.
  23443. sd -= x.e + 1;
  23444. // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  23445. xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
  23446. x.e = -sd || 0;
  23447. } else {
  23448. // Zero.
  23449. xd[0] = x.e = 0;
  23450. }
  23451. return x;
  23452. }
  23453. // Remove excess digits.
  23454. if (i == 0) {
  23455. xd.length = xdi;
  23456. k = 1;
  23457. xdi--;
  23458. } else {
  23459. xd.length = xdi + 1;
  23460. k = mathpow(10, LOG_BASE - i);
  23461. // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  23462. // j > 0 means i > number of leading zeros of w.
  23463. xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
  23464. }
  23465. if (roundUp) {
  23466. for (;;) {
  23467. // Is the digit to be rounded up in the first word of xd?
  23468. if (xdi == 0) {
  23469. // i will be the length of xd[0] before k is added.
  23470. for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
  23471. j = xd[0] += k;
  23472. for (k = 1; j >= 10; j /= 10) k++;
  23473. // if i != k the length has increased.
  23474. if (i != k) {
  23475. x.e++;
  23476. if (xd[0] == BASE) xd[0] = 1;
  23477. }
  23478. break;
  23479. } else {
  23480. xd[xdi] += k;
  23481. if (xd[xdi] != BASE) break;
  23482. xd[xdi--] = 0;
  23483. k = 1;
  23484. }
  23485. }
  23486. }
  23487. // Remove trailing zeros.
  23488. for (i = xd.length; xd[--i] === 0;) xd.pop();
  23489. }
  23490. if (external) {
  23491. // Overflow?
  23492. if (x.e > Ctor.maxE) {
  23493. // Infinity.
  23494. x.d = null;
  23495. x.e = NaN;
  23496. // Underflow?
  23497. } else if (x.e < Ctor.minE) {
  23498. // Zero.
  23499. x.e = 0;
  23500. x.d = [0];
  23501. // Ctor.underflow = true;
  23502. } // else Ctor.underflow = false;
  23503. }
  23504. return x;
  23505. }
  23506. function finiteToString(x, isExp, sd) {
  23507. if (!x.isFinite()) return nonFiniteToString(x);
  23508. var k,
  23509. e = x.e,
  23510. str = digitsToString(x.d),
  23511. len = str.length;
  23512. if (isExp) {
  23513. if (sd && (k = sd - len) > 0) {
  23514. str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
  23515. } else if (len > 1) {
  23516. str = str.charAt(0) + '.' + str.slice(1);
  23517. }
  23518. str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
  23519. } else if (e < 0) {
  23520. str = '0.' + getZeroString(-e - 1) + str;
  23521. if (sd && (k = sd - len) > 0) str += getZeroString(k);
  23522. } else if (e >= len) {
  23523. str += getZeroString(e + 1 - len);
  23524. if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
  23525. } else {
  23526. if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
  23527. if (sd && (k = sd - len) > 0) {
  23528. if (e + 1 === len) str += '.';
  23529. str += getZeroString(k);
  23530. }
  23531. }
  23532. return str;
  23533. }
  23534. // Calculate the base 10 exponent from the base 1e7 exponent.
  23535. function getBase10Exponent(digits, e) {
  23536. var w = digits[0];
  23537. // Add the number of digits of the first word of the digits array.
  23538. for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
  23539. return e;
  23540. }
  23541. function getLn10(Ctor, sd, pr) {
  23542. if (sd > LN10_PRECISION) {
  23543. // Reset global state in case the exception is caught.
  23544. external = true;
  23545. if (pr) Ctor.precision = pr;
  23546. throw Error(precisionLimitExceeded);
  23547. }
  23548. return finalise(new Ctor(LN10), sd, 1, true);
  23549. }
  23550. function getPi(Ctor, sd, rm) {
  23551. if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
  23552. return finalise(new Ctor(PI), sd, rm, true);
  23553. }
  23554. function getPrecision(digits) {
  23555. var w = digits.length - 1,
  23556. len = w * LOG_BASE + 1;
  23557. w = digits[w];
  23558. // If non-zero...
  23559. if (w) {
  23560. // Subtract the number of trailing zeros of the last word.
  23561. for (; w % 10 == 0; w /= 10) len--;
  23562. // Add the number of digits of the first word.
  23563. for (w = digits[0]; w >= 10; w /= 10) len++;
  23564. }
  23565. return len;
  23566. }
  23567. function getZeroString(k) {
  23568. var zs = '';
  23569. for (; k--;) zs += '0';
  23570. return zs;
  23571. }
  23572. /*
  23573. * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
  23574. * integer of type number.
  23575. *
  23576. * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
  23577. *
  23578. */
  23579. function intPow(Ctor, x, n, pr) {
  23580. var isTruncated,
  23581. r = new Ctor(1),
  23582. // Max n of 9007199254740991 takes 53 loop iterations.
  23583. // Maximum digits array length; leaves [28, 34] guard digits.
  23584. k = Math.ceil(pr / LOG_BASE + 4);
  23585. external = false;
  23586. for (;;) {
  23587. if (n % 2) {
  23588. r = r.times(x);
  23589. if (truncate(r.d, k)) isTruncated = true;
  23590. }
  23591. n = mathfloor(n / 2);
  23592. if (n === 0) {
  23593. // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
  23594. n = r.d.length - 1;
  23595. if (isTruncated && r.d[n] === 0) ++r.d[n];
  23596. break;
  23597. }
  23598. x = x.times(x);
  23599. truncate(x.d, k);
  23600. }
  23601. external = true;
  23602. return r;
  23603. }
  23604. function isOdd(n) {
  23605. return n.d[n.d.length - 1] & 1;
  23606. }
  23607. /*
  23608. * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
  23609. */
  23610. function maxOrMin(Ctor, args, ltgt) {
  23611. var y,
  23612. x = new Ctor(args[0]),
  23613. i = 0;
  23614. for (; ++i < args.length;) {
  23615. y = new Ctor(args[i]);
  23616. if (!y.s) {
  23617. x = y;
  23618. break;
  23619. } else if (x[ltgt](y)) {
  23620. x = y;
  23621. }
  23622. }
  23623. return x;
  23624. }
  23625. /*
  23626. * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
  23627. * digits.
  23628. *
  23629. * Taylor/Maclaurin series.
  23630. *
  23631. * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
  23632. *
  23633. * Argument reduction:
  23634. * Repeat x = x / 32, k += 5, until |x| < 0.1
  23635. * exp(x) = exp(x / 2^k)^(2^k)
  23636. *
  23637. * Previously, the argument was initially reduced by
  23638. * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
  23639. * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
  23640. * found to be slower than just dividing repeatedly by 32 as above.
  23641. *
  23642. * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
  23643. * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
  23644. * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
  23645. *
  23646. * exp(Infinity) = Infinity
  23647. * exp(-Infinity) = 0
  23648. * exp(NaN) = NaN
  23649. * exp(±0) = 1
  23650. *
  23651. * exp(x) is non-terminating for any finite, non-zero x.
  23652. *
  23653. * The result will always be correctly rounded.
  23654. *
  23655. */
  23656. function naturalExponential(x, sd) {
  23657. var denominator, guard, j, pow, sum, t, wpr,
  23658. rep = 0,
  23659. i = 0,
  23660. k = 0,
  23661. Ctor = x.constructor,
  23662. rm = Ctor.rounding,
  23663. pr = Ctor.precision;
  23664. // 0/NaN/Infinity?
  23665. if (!x.d || !x.d[0] || x.e > 17) {
  23666. return new Ctor(x.d
  23667. ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
  23668. : x.s ? x.s < 0 ? 0 : x : 0 / 0);
  23669. }
  23670. if (sd == null) {
  23671. external = false;
  23672. wpr = pr;
  23673. } else {
  23674. wpr = sd;
  23675. }
  23676. t = new Ctor(0.03125);
  23677. // while abs(x) >= 0.1
  23678. while (x.e > -2) {
  23679. // x = x / 2^5
  23680. x = x.times(t);
  23681. k += 5;
  23682. }
  23683. // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
  23684. // necessary to ensure the first 4 rounding digits are correct.
  23685. guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
  23686. wpr += guard;
  23687. denominator = pow = sum = new Ctor(1);
  23688. Ctor.precision = wpr;
  23689. for (;;) {
  23690. pow = finalise(pow.times(x), wpr, 1);
  23691. denominator = denominator.times(++i);
  23692. t = sum.plus(divide(pow, denominator, wpr, 1));
  23693. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  23694. j = k;
  23695. while (j--) sum = finalise(sum.times(sum), wpr, 1);
  23696. // Check to see if the first 4 rounding digits are [49]999.
  23697. // If so, repeat the summation with a higher precision, otherwise
  23698. // e.g. with precision: 18, rounding: 1
  23699. // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
  23700. // `wpr - guard` is the index of first rounding digit.
  23701. if (sd == null) {
  23702. if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  23703. Ctor.precision = wpr += 10;
  23704. denominator = pow = t = new Ctor(1);
  23705. i = 0;
  23706. rep++;
  23707. } else {
  23708. return finalise(sum, Ctor.precision = pr, rm, external = true);
  23709. }
  23710. } else {
  23711. Ctor.precision = pr;
  23712. return sum;
  23713. }
  23714. }
  23715. sum = t;
  23716. }
  23717. }
  23718. /*
  23719. * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
  23720. * digits.
  23721. *
  23722. * ln(-n) = NaN
  23723. * ln(0) = -Infinity
  23724. * ln(-0) = -Infinity
  23725. * ln(1) = 0
  23726. * ln(Infinity) = Infinity
  23727. * ln(-Infinity) = NaN
  23728. * ln(NaN) = NaN
  23729. *
  23730. * ln(n) (n != 1) is non-terminating.
  23731. *
  23732. */
  23733. function naturalLogarithm(y, sd) {
  23734. var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
  23735. n = 1,
  23736. guard = 10,
  23737. x = y,
  23738. xd = x.d,
  23739. Ctor = x.constructor,
  23740. rm = Ctor.rounding,
  23741. pr = Ctor.precision;
  23742. // Is x negative or Infinity, NaN, 0 or 1?
  23743. if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
  23744. return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
  23745. }
  23746. if (sd == null) {
  23747. external = false;
  23748. wpr = pr;
  23749. } else {
  23750. wpr = sd;
  23751. }
  23752. Ctor.precision = wpr += guard;
  23753. c = digitsToString(xd);
  23754. c0 = c.charAt(0);
  23755. if (Math.abs(e = x.e) < 1.5e15) {
  23756. // Argument reduction.
  23757. // The series converges faster the closer the argument is to 1, so using
  23758. // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
  23759. // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
  23760. // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
  23761. // later be divided by this number, then separate out the power of 10 using
  23762. // ln(a*10^b) = ln(a) + b*ln(10).
  23763. // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
  23764. //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
  23765. // max n is 6 (gives 0.7 - 1.3)
  23766. while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
  23767. x = x.times(y);
  23768. c = digitsToString(x.d);
  23769. c0 = c.charAt(0);
  23770. n++;
  23771. }
  23772. e = x.e;
  23773. if (c0 > 1) {
  23774. x = new Ctor('0.' + c);
  23775. e++;
  23776. } else {
  23777. x = new Ctor(c0 + '.' + c.slice(1));
  23778. }
  23779. } else {
  23780. // The argument reduction method above may result in overflow if the argument y is a massive
  23781. // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
  23782. // function using ln(x*10^e) = ln(x) + e*ln(10).
  23783. t = getLn10(Ctor, wpr + 2, pr).times(e + '');
  23784. x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
  23785. Ctor.precision = pr;
  23786. return sd == null ? finalise(x, pr, rm, external = true) : x;
  23787. }
  23788. // x1 is x reduced to a value near 1.
  23789. x1 = x;
  23790. // Taylor series.
  23791. // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
  23792. // where x = (y - 1)/(y + 1) (|x| < 1)
  23793. sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
  23794. x2 = finalise(x.times(x), wpr, 1);
  23795. denominator = 3;
  23796. for (;;) {
  23797. numerator = finalise(numerator.times(x2), wpr, 1);
  23798. t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
  23799. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  23800. sum = sum.times(2);
  23801. // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
  23802. // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
  23803. if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
  23804. sum = divide(sum, new Ctor(n), wpr, 1);
  23805. // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
  23806. // been repeated previously) and the first 4 rounding digits 9999?
  23807. // If so, restart the summation with a higher precision, otherwise
  23808. // e.g. with precision: 12, rounding: 1
  23809. // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
  23810. // `wpr - guard` is the index of first rounding digit.
  23811. if (sd == null) {
  23812. if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  23813. Ctor.precision = wpr += guard;
  23814. t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
  23815. x2 = finalise(x.times(x), wpr, 1);
  23816. denominator = rep = 1;
  23817. } else {
  23818. return finalise(sum, Ctor.precision = pr, rm, external = true);
  23819. }
  23820. } else {
  23821. Ctor.precision = pr;
  23822. return sum;
  23823. }
  23824. }
  23825. sum = t;
  23826. denominator += 2;
  23827. }
  23828. }
  23829. // ±Infinity, NaN.
  23830. function nonFiniteToString(x) {
  23831. // Unsigned.
  23832. return String(x.s * x.s / 0);
  23833. }
  23834. /*
  23835. * Parse the value of a new Decimal `x` from string `str`.
  23836. */
  23837. function parseDecimal(x, str) {
  23838. var e, i, len;
  23839. // Decimal point?
  23840. if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
  23841. // Exponential form?
  23842. if ((i = str.search(/e/i)) > 0) {
  23843. // Determine exponent.
  23844. if (e < 0) e = i;
  23845. e += +str.slice(i + 1);
  23846. str = str.substring(0, i);
  23847. } else if (e < 0) {
  23848. // Integer.
  23849. e = str.length;
  23850. }
  23851. // Determine leading zeros.
  23852. for (i = 0; str.charCodeAt(i) === 48; i++);
  23853. // Determine trailing zeros.
  23854. for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
  23855. str = str.slice(i, len);
  23856. if (str) {
  23857. len -= i;
  23858. x.e = e = e - i - 1;
  23859. x.d = [];
  23860. // Transform base
  23861. // e is the base 10 exponent.
  23862. // i is where to slice str to get the first word of the digits array.
  23863. i = (e + 1) % LOG_BASE;
  23864. if (e < 0) i += LOG_BASE;
  23865. if (i < len) {
  23866. if (i) x.d.push(+str.slice(0, i));
  23867. for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
  23868. str = str.slice(i);
  23869. i = LOG_BASE - str.length;
  23870. } else {
  23871. i -= len;
  23872. }
  23873. for (; i--;) str += '0';
  23874. x.d.push(+str);
  23875. if (external) {
  23876. // Overflow?
  23877. if (x.e > x.constructor.maxE) {
  23878. // Infinity.
  23879. x.d = null;
  23880. x.e = NaN;
  23881. // Underflow?
  23882. } else if (x.e < x.constructor.minE) {
  23883. // Zero.
  23884. x.e = 0;
  23885. x.d = [0];
  23886. // x.constructor.underflow = true;
  23887. } // else x.constructor.underflow = false;
  23888. }
  23889. } else {
  23890. // Zero.
  23891. x.e = 0;
  23892. x.d = [0];
  23893. }
  23894. return x;
  23895. }
  23896. /*
  23897. * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
  23898. */
  23899. function parseOther(x, str) {
  23900. var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
  23901. if (str === 'Infinity' || str === 'NaN') {
  23902. if (!+str) x.s = NaN;
  23903. x.e = NaN;
  23904. x.d = null;
  23905. return x;
  23906. }
  23907. if (isHex.test(str)) {
  23908. base = 16;
  23909. str = str.toLowerCase();
  23910. } else if (isBinary.test(str)) {
  23911. base = 2;
  23912. } else if (isOctal.test(str)) {
  23913. base = 8;
  23914. } else {
  23915. throw Error(invalidArgument + str);
  23916. }
  23917. // Is there a binary exponent part?
  23918. i = str.search(/p/i);
  23919. if (i > 0) {
  23920. p = +str.slice(i + 1);
  23921. str = str.substring(2, i);
  23922. } else {
  23923. str = str.slice(2);
  23924. }
  23925. // Convert `str` as an integer then divide the result by `base` raised to a power such that the
  23926. // fraction part will be restored.
  23927. i = str.indexOf('.');
  23928. isFloat = i >= 0;
  23929. Ctor = x.constructor;
  23930. if (isFloat) {
  23931. str = str.replace('.', '');
  23932. len = str.length;
  23933. i = len - i;
  23934. // log[10](16) = 1.2041... , log[10](88) = 1.9444....
  23935. divisor = intPow(Ctor, new Ctor(base), i, i * 2);
  23936. }
  23937. xd = convertBase(str, base, BASE);
  23938. xe = xd.length - 1;
  23939. // Remove trailing zeros.
  23940. for (i = xe; xd[i] === 0; --i) xd.pop();
  23941. if (i < 0) return new Ctor(x.s * 0);
  23942. x.e = getBase10Exponent(xd, xe);
  23943. x.d = xd;
  23944. external = false;
  23945. // At what precision to perform the division to ensure exact conversion?
  23946. // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
  23947. // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
  23948. // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
  23949. // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
  23950. // Therefore using 4 * the number of digits of str will always be enough.
  23951. if (isFloat) x = divide(x, divisor, len * 4);
  23952. // Multiply by the binary exponent part if present.
  23953. if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));
  23954. external = true;
  23955. return x;
  23956. }
  23957. /*
  23958. * sin(x) = x - x^3/3! + x^5/5! - ...
  23959. * |x| < pi/2
  23960. *
  23961. */
  23962. function sine(Ctor, x) {
  23963. var k,
  23964. len = x.d.length;
  23965. if (len < 3) return taylorSeries(Ctor, 2, x, x);
  23966. // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
  23967. // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
  23968. // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
  23969. // Estimate the optimum number of times to use the argument reduction.
  23970. k = 1.4 * Math.sqrt(len);
  23971. k = k > 16 ? 16 : k | 0;
  23972. x = x.times(1 / tinyPow(5, k));
  23973. x = taylorSeries(Ctor, 2, x, x);
  23974. // Reverse argument reduction
  23975. var sin2_x,
  23976. d5 = new Ctor(5),
  23977. d16 = new Ctor(16),
  23978. d20 = new Ctor(20);
  23979. for (; k--;) {
  23980. sin2_x = x.times(x);
  23981. x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
  23982. }
  23983. return x;
  23984. }
  23985. // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
  23986. function taylorSeries(Ctor, n, x, y, isHyperbolic) {
  23987. var j, t, u, x2,
  23988. i = 1,
  23989. pr = Ctor.precision,
  23990. k = Math.ceil(pr / LOG_BASE);
  23991. external = false;
  23992. x2 = x.times(x);
  23993. u = new Ctor(y);
  23994. for (;;) {
  23995. t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
  23996. u = isHyperbolic ? y.plus(t) : y.minus(t);
  23997. y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
  23998. t = u.plus(y);
  23999. if (t.d[k] !== void 0) {
  24000. for (j = k; t.d[j] === u.d[j] && j--;);
  24001. if (j == -1) break;
  24002. }
  24003. j = u;
  24004. u = y;
  24005. y = t;
  24006. t = j;
  24007. i++;
  24008. }
  24009. external = true;
  24010. t.d.length = k + 1;
  24011. return t;
  24012. }
  24013. // Exponent e must be positive and non-zero.
  24014. function tinyPow(b, e) {
  24015. var n = b;
  24016. while (--e) n *= b;
  24017. return n;
  24018. }
  24019. // Return the absolute value of `x` reduced to less than or equal to half pi.
  24020. function toLessThanHalfPi(Ctor, x) {
  24021. var t,
  24022. isNeg = x.s < 0,
  24023. pi = getPi(Ctor, Ctor.precision, 1),
  24024. halfPi = pi.times(0.5);
  24025. x = x.abs();
  24026. if (x.lte(halfPi)) {
  24027. quadrant = isNeg ? 4 : 1;
  24028. return x;
  24029. }
  24030. t = x.divToInt(pi);
  24031. if (t.isZero()) {
  24032. quadrant = isNeg ? 3 : 2;
  24033. } else {
  24034. x = x.minus(t.times(pi));
  24035. // 0 <= x < pi
  24036. if (x.lte(halfPi)) {
  24037. quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
  24038. return x;
  24039. }
  24040. quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
  24041. }
  24042. return x.minus(pi).abs();
  24043. }
  24044. /*
  24045. * Return the value of Decimal `x` as a string in base `baseOut`.
  24046. *
  24047. * If the optional `sd` argument is present include a binary exponent suffix.
  24048. */
  24049. function toStringBinary(x, baseOut, sd, rm) {
  24050. var base, e, i, k, len, roundUp, str, xd, y,
  24051. Ctor = x.constructor,
  24052. isExp = sd !== void 0;
  24053. if (isExp) {
  24054. checkInt32(sd, 1, MAX_DIGITS);
  24055. if (rm === void 0) rm = Ctor.rounding;
  24056. else checkInt32(rm, 0, 8);
  24057. } else {
  24058. sd = Ctor.precision;
  24059. rm = Ctor.rounding;
  24060. }
  24061. if (!x.isFinite()) {
  24062. str = nonFiniteToString(x);
  24063. } else {
  24064. str = finiteToString(x);
  24065. i = str.indexOf('.');
  24066. // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
  24067. // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
  24068. // minBinaryExponent = floor(decimalExponent * log[2](10))
  24069. // log[2](10) = 3.321928094887362347870319429489390175864
  24070. if (isExp) {
  24071. base = 2;
  24072. if (baseOut == 16) {
  24073. sd = sd * 4 - 3;
  24074. } else if (baseOut == 8) {
  24075. sd = sd * 3 - 2;
  24076. }
  24077. } else {
  24078. base = baseOut;
  24079. }
  24080. // Convert the number as an integer then divide the result by its base raised to a power such
  24081. // that the fraction part will be restored.
  24082. // Non-integer.
  24083. if (i >= 0) {
  24084. str = str.replace('.', '');
  24085. y = new Ctor(1);
  24086. y.e = str.length - i;
  24087. y.d = convertBase(finiteToString(y), 10, base);
  24088. y.e = y.d.length;
  24089. }
  24090. xd = convertBase(str, 10, base);
  24091. e = len = xd.length;
  24092. // Remove trailing zeros.
  24093. for (; xd[--len] == 0;) xd.pop();
  24094. if (!xd[0]) {
  24095. str = isExp ? '0p+0' : '0';
  24096. } else {
  24097. if (i < 0) {
  24098. e--;
  24099. } else {
  24100. x = new Ctor(x);
  24101. x.d = xd;
  24102. x.e = e;
  24103. x = divide(x, y, sd, rm, 0, base);
  24104. xd = x.d;
  24105. e = x.e;
  24106. roundUp = inexact;
  24107. }
  24108. // The rounding digit, i.e. the digit after the digit that may be rounded up.
  24109. i = xd[sd];
  24110. k = base / 2;
  24111. roundUp = roundUp || xd[sd + 1] !== void 0;
  24112. roundUp = rm < 4
  24113. ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
  24114. : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
  24115. rm === (x.s < 0 ? 8 : 7));
  24116. xd.length = sd;
  24117. if (roundUp) {
  24118. // Rounding up may mean the previous digit has to be rounded up and so on.
  24119. for (; ++xd[--sd] > base - 1;) {
  24120. xd[sd] = 0;
  24121. if (!sd) {
  24122. ++e;
  24123. xd.unshift(1);
  24124. }
  24125. }
  24126. }
  24127. // Determine trailing zeros.
  24128. for (len = xd.length; !xd[len - 1]; --len);
  24129. // E.g. [4, 11, 15] becomes 4bf.
  24130. for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
  24131. // Add binary exponent suffix?
  24132. if (isExp) {
  24133. if (len > 1) {
  24134. if (baseOut == 16 || baseOut == 8) {
  24135. i = baseOut == 16 ? 4 : 3;
  24136. for (--len; len % i; len++) str += '0';
  24137. xd = convertBase(str, base, baseOut);
  24138. for (len = xd.length; !xd[len - 1]; --len);
  24139. // xd[0] will always be be 1
  24140. for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
  24141. } else {
  24142. str = str.charAt(0) + '.' + str.slice(1);
  24143. }
  24144. }
  24145. str = str + (e < 0 ? 'p' : 'p+') + e;
  24146. } else if (e < 0) {
  24147. for (; ++e;) str = '0' + str;
  24148. str = '0.' + str;
  24149. } else {
  24150. if (++e > len) for (e -= len; e-- ;) str += '0';
  24151. else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
  24152. }
  24153. }
  24154. str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
  24155. }
  24156. return x.s < 0 ? '-' + str : str;
  24157. }
  24158. // Does not strip trailing zeros.
  24159. function truncate(arr, len) {
  24160. if (arr.length > len) {
  24161. arr.length = len;
  24162. return true;
  24163. }
  24164. }
  24165. // Decimal methods
  24166. /*
  24167. * abs
  24168. * acos
  24169. * acosh
  24170. * add
  24171. * asin
  24172. * asinh
  24173. * atan
  24174. * atanh
  24175. * atan2
  24176. * cbrt
  24177. * ceil
  24178. * clone
  24179. * config
  24180. * cos
  24181. * cosh
  24182. * div
  24183. * exp
  24184. * floor
  24185. * hypot
  24186. * ln
  24187. * log
  24188. * log2
  24189. * log10
  24190. * max
  24191. * min
  24192. * mod
  24193. * mul
  24194. * pow
  24195. * random
  24196. * round
  24197. * set
  24198. * sign
  24199. * sin
  24200. * sinh
  24201. * sqrt
  24202. * sub
  24203. * tan
  24204. * tanh
  24205. * trunc
  24206. */
  24207. /*
  24208. * Return a new Decimal whose value is the absolute value of `x`.
  24209. *
  24210. * x {number|string|Decimal}
  24211. *
  24212. */
  24213. function abs(x) {
  24214. return new this(x).abs();
  24215. }
  24216. /*
  24217. * Return a new Decimal whose value is the arccosine in radians of `x`.
  24218. *
  24219. * x {number|string|Decimal}
  24220. *
  24221. */
  24222. function acos(x) {
  24223. return new this(x).acos();
  24224. }
  24225. /*
  24226. * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
  24227. * `precision` significant digits using rounding mode `rounding`.
  24228. *
  24229. * x {number|string|Decimal} A value in radians.
  24230. *
  24231. */
  24232. function acosh(x) {
  24233. return new this(x).acosh();
  24234. }
  24235. /*
  24236. * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
  24237. * digits using rounding mode `rounding`.
  24238. *
  24239. * x {number|string|Decimal}
  24240. * y {number|string|Decimal}
  24241. *
  24242. */
  24243. function add(x, y) {
  24244. return new this(x).plus(y);
  24245. }
  24246. /*
  24247. * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
  24248. * significant digits using rounding mode `rounding`.
  24249. *
  24250. * x {number|string|Decimal}
  24251. *
  24252. */
  24253. function asin(x) {
  24254. return new this(x).asin();
  24255. }
  24256. /*
  24257. * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
  24258. * `precision` significant digits using rounding mode `rounding`.
  24259. *
  24260. * x {number|string|Decimal} A value in radians.
  24261. *
  24262. */
  24263. function asinh(x) {
  24264. return new this(x).asinh();
  24265. }
  24266. /*
  24267. * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
  24268. * significant digits using rounding mode `rounding`.
  24269. *
  24270. * x {number|string|Decimal}
  24271. *
  24272. */
  24273. function atan(x) {
  24274. return new this(x).atan();
  24275. }
  24276. /*
  24277. * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
  24278. * `precision` significant digits using rounding mode `rounding`.
  24279. *
  24280. * x {number|string|Decimal} A value in radians.
  24281. *
  24282. */
  24283. function atanh(x) {
  24284. return new this(x).atanh();
  24285. }
  24286. /*
  24287. * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
  24288. * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
  24289. *
  24290. * Domain: [-Infinity, Infinity]
  24291. * Range: [-pi, pi]
  24292. *
  24293. * y {number|string|Decimal} The y-coordinate.
  24294. * x {number|string|Decimal} The x-coordinate.
  24295. *
  24296. * atan2(±0, -0) = ±pi
  24297. * atan2(±0, +0) = ±0
  24298. * atan2(±0, -x) = ±pi for x > 0
  24299. * atan2(±0, x) = ±0 for x > 0
  24300. * atan2(-y, ±0) = -pi/2 for y > 0
  24301. * atan2(y, ±0) = pi/2 for y > 0
  24302. * atan2(±y, -Infinity) = ±pi for finite y > 0
  24303. * atan2(±y, +Infinity) = ±0 for finite y > 0
  24304. * atan2(±Infinity, x) = ±pi/2 for finite x
  24305. * atan2(±Infinity, -Infinity) = ±3*pi/4
  24306. * atan2(±Infinity, +Infinity) = ±pi/4
  24307. * atan2(NaN, x) = NaN
  24308. * atan2(y, NaN) = NaN
  24309. *
  24310. */
  24311. function atan2(y, x) {
  24312. y = new this(y);
  24313. x = new this(x);
  24314. var r,
  24315. pr = this.precision,
  24316. rm = this.rounding,
  24317. wpr = pr + 4;
  24318. // Either NaN
  24319. if (!y.s || !x.s) {
  24320. r = new this(NaN);
  24321. // Both ±Infinity
  24322. } else if (!y.d && !x.d) {
  24323. r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
  24324. r.s = y.s;
  24325. // x is ±Infinity or y is ±0
  24326. } else if (!x.d || y.isZero()) {
  24327. r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
  24328. r.s = y.s;
  24329. // y is ±Infinity or x is ±0
  24330. } else if (!y.d || x.isZero()) {
  24331. r = getPi(this, wpr, 1).times(0.5);
  24332. r.s = y.s;
  24333. // Both non-zero and finite
  24334. } else if (x.s < 0) {
  24335. this.precision = wpr;
  24336. this.rounding = 1;
  24337. r = this.atan(divide(y, x, wpr, 1));
  24338. x = getPi(this, wpr, 1);
  24339. this.precision = pr;
  24340. this.rounding = rm;
  24341. r = y.s < 0 ? r.minus(x) : r.plus(x);
  24342. } else {
  24343. r = this.atan(divide(y, x, wpr, 1));
  24344. }
  24345. return r;
  24346. }
  24347. /*
  24348. * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
  24349. * digits using rounding mode `rounding`.
  24350. *
  24351. * x {number|string|Decimal}
  24352. *
  24353. */
  24354. function cbrt(x) {
  24355. return new this(x).cbrt();
  24356. }
  24357. /*
  24358. * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
  24359. *
  24360. * x {number|string|Decimal}
  24361. *
  24362. */
  24363. function ceil(x) {
  24364. return finalise(x = new this(x), x.e + 1, 2);
  24365. }
  24366. /*
  24367. * Configure global settings for a Decimal constructor.
  24368. *
  24369. * `obj` is an object with one or more of the following properties,
  24370. *
  24371. * precision {number}
  24372. * rounding {number}
  24373. * toExpNeg {number}
  24374. * toExpPos {number}
  24375. * maxE {number}
  24376. * minE {number}
  24377. * modulo {number}
  24378. * crypto {boolean|number}
  24379. * defaults {true}
  24380. *
  24381. * E.g. Decimal.config({ precision: 20, rounding: 4 })
  24382. *
  24383. */
  24384. function config(obj) {
  24385. if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
  24386. var i, p, v,
  24387. useDefaults = obj.defaults === true,
  24388. ps = [
  24389. 'precision', 1, MAX_DIGITS,
  24390. 'rounding', 0, 8,
  24391. 'toExpNeg', -EXP_LIMIT, 0,
  24392. 'toExpPos', 0, EXP_LIMIT,
  24393. 'maxE', 0, EXP_LIMIT,
  24394. 'minE', -EXP_LIMIT, 0,
  24395. 'modulo', 0, 9
  24396. ];
  24397. for (i = 0; i < ps.length; i += 3) {
  24398. if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
  24399. if ((v = obj[p]) !== void 0) {
  24400. if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
  24401. else throw Error(invalidArgument + p + ': ' + v);
  24402. }
  24403. }
  24404. if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
  24405. if ((v = obj[p]) !== void 0) {
  24406. if (v === true || v === false || v === 0 || v === 1) {
  24407. if (v) {
  24408. if (typeof crypto != 'undefined' && crypto &&
  24409. (crypto.getRandomValues || crypto.randomBytes)) {
  24410. this[p] = true;
  24411. } else {
  24412. throw Error(cryptoUnavailable);
  24413. }
  24414. } else {
  24415. this[p] = false;
  24416. }
  24417. } else {
  24418. throw Error(invalidArgument + p + ': ' + v);
  24419. }
  24420. }
  24421. return this;
  24422. }
  24423. /*
  24424. * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
  24425. * digits using rounding mode `rounding`.
  24426. *
  24427. * x {number|string|Decimal} A value in radians.
  24428. *
  24429. */
  24430. function cos(x) {
  24431. return new this(x).cos();
  24432. }
  24433. /*
  24434. * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
  24435. * significant digits using rounding mode `rounding`.
  24436. *
  24437. * x {number|string|Decimal} A value in radians.
  24438. *
  24439. */
  24440. function cosh(x) {
  24441. return new this(x).cosh();
  24442. }
  24443. /*
  24444. * Create and return a Decimal constructor with the same configuration properties as this Decimal
  24445. * constructor.
  24446. *
  24447. */
  24448. function clone(obj) {
  24449. var i, p, ps;
  24450. /*
  24451. * The Decimal constructor and exported function.
  24452. * Return a new Decimal instance.
  24453. *
  24454. * v {number|string|Decimal} A numeric value.
  24455. *
  24456. */
  24457. function Decimal(v) {
  24458. var e, i, t,
  24459. x = this;
  24460. // Decimal called without new.
  24461. if (!(x instanceof Decimal)) return new Decimal(v);
  24462. // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
  24463. // which points to Object.
  24464. x.constructor = Decimal;
  24465. // Duplicate.
  24466. if (v instanceof Decimal) {
  24467. x.s = v.s;
  24468. if (external) {
  24469. if (!v.d || v.e > Decimal.maxE) {
  24470. // Infinity.
  24471. x.e = NaN;
  24472. x.d = null;
  24473. } else if (v.e < Decimal.minE) {
  24474. // Zero.
  24475. x.e = 0;
  24476. x.d = [0];
  24477. } else {
  24478. x.e = v.e;
  24479. x.d = v.d.slice();
  24480. }
  24481. } else {
  24482. x.e = v.e;
  24483. x.d = v.d ? v.d.slice() : v.d;
  24484. }
  24485. return;
  24486. }
  24487. t = typeof v;
  24488. if (t === 'number') {
  24489. if (v === 0) {
  24490. x.s = 1 / v < 0 ? -1 : 1;
  24491. x.e = 0;
  24492. x.d = [0];
  24493. return;
  24494. }
  24495. if (v < 0) {
  24496. v = -v;
  24497. x.s = -1;
  24498. } else {
  24499. x.s = 1;
  24500. }
  24501. // Fast path for small integers.
  24502. if (v === ~~v && v < 1e7) {
  24503. for (e = 0, i = v; i >= 10; i /= 10) e++;
  24504. if (external) {
  24505. if (e > Decimal.maxE) {
  24506. x.e = NaN;
  24507. x.d = null;
  24508. } else if (e < Decimal.minE) {
  24509. x.e = 0;
  24510. x.d = [0];
  24511. } else {
  24512. x.e = e;
  24513. x.d = [v];
  24514. }
  24515. } else {
  24516. x.e = e;
  24517. x.d = [v];
  24518. }
  24519. return;
  24520. // Infinity, NaN.
  24521. } else if (v * 0 !== 0) {
  24522. if (!v) x.s = NaN;
  24523. x.e = NaN;
  24524. x.d = null;
  24525. return;
  24526. }
  24527. return parseDecimal(x, v.toString());
  24528. } else if (t !== 'string') {
  24529. throw Error(invalidArgument + v);
  24530. }
  24531. // Minus sign?
  24532. if ((i = v.charCodeAt(0)) === 45) {
  24533. v = v.slice(1);
  24534. x.s = -1;
  24535. } else {
  24536. // Plus sign?
  24537. if (i === 43) v = v.slice(1);
  24538. x.s = 1;
  24539. }
  24540. return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
  24541. }
  24542. Decimal.prototype = P;
  24543. Decimal.ROUND_UP = 0;
  24544. Decimal.ROUND_DOWN = 1;
  24545. Decimal.ROUND_CEIL = 2;
  24546. Decimal.ROUND_FLOOR = 3;
  24547. Decimal.ROUND_HALF_UP = 4;
  24548. Decimal.ROUND_HALF_DOWN = 5;
  24549. Decimal.ROUND_HALF_EVEN = 6;
  24550. Decimal.ROUND_HALF_CEIL = 7;
  24551. Decimal.ROUND_HALF_FLOOR = 8;
  24552. Decimal.EUCLID = 9;
  24553. Decimal.config = Decimal.set = config;
  24554. Decimal.clone = clone;
  24555. Decimal.isDecimal = isDecimalInstance;
  24556. Decimal.abs = abs;
  24557. Decimal.acos = acos;
  24558. Decimal.acosh = acosh; // ES6
  24559. Decimal.add = add;
  24560. Decimal.asin = asin;
  24561. Decimal.asinh = asinh; // ES6
  24562. Decimal.atan = atan;
  24563. Decimal.atanh = atanh; // ES6
  24564. Decimal.atan2 = atan2;
  24565. Decimal.cbrt = cbrt; // ES6
  24566. Decimal.ceil = ceil;
  24567. Decimal.cos = cos;
  24568. Decimal.cosh = cosh; // ES6
  24569. Decimal.div = div;
  24570. Decimal.exp = exp;
  24571. Decimal.floor = floor;
  24572. Decimal.hypot = hypot; // ES6
  24573. Decimal.ln = ln;
  24574. Decimal.log = log;
  24575. Decimal.log10 = log10; // ES6
  24576. Decimal.log2 = log2; // ES6
  24577. Decimal.max = max;
  24578. Decimal.min = min;
  24579. Decimal.mod = mod;
  24580. Decimal.mul = mul;
  24581. Decimal.pow = pow;
  24582. Decimal.random = random;
  24583. Decimal.round = round;
  24584. Decimal.sign = sign; // ES6
  24585. Decimal.sin = sin;
  24586. Decimal.sinh = sinh; // ES6
  24587. Decimal.sqrt = sqrt;
  24588. Decimal.sub = sub;
  24589. Decimal.tan = tan;
  24590. Decimal.tanh = tanh; // ES6
  24591. Decimal.trunc = trunc; // ES6
  24592. if (obj === void 0) obj = {};
  24593. if (obj) {
  24594. if (obj.defaults !== true) {
  24595. ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
  24596. for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
  24597. }
  24598. }
  24599. Decimal.config(obj);
  24600. return Decimal;
  24601. }
  24602. /*
  24603. * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
  24604. * digits using rounding mode `rounding`.
  24605. *
  24606. * x {number|string|Decimal}
  24607. * y {number|string|Decimal}
  24608. *
  24609. */
  24610. function div(x, y) {
  24611. return new this(x).div(y);
  24612. }
  24613. /*
  24614. * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
  24615. * significant digits using rounding mode `rounding`.
  24616. *
  24617. * x {number|string|Decimal} The power to which to raise the base of the natural log.
  24618. *
  24619. */
  24620. function exp(x) {
  24621. return new this(x).exp();
  24622. }
  24623. /*
  24624. * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
  24625. *
  24626. * x {number|string|Decimal}
  24627. *
  24628. */
  24629. function floor(x) {
  24630. return finalise(x = new this(x), x.e + 1, 3);
  24631. }
  24632. /*
  24633. * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
  24634. * rounded to `precision` significant digits using rounding mode `rounding`.
  24635. *
  24636. * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
  24637. *
  24638. * arguments {number|string|Decimal}
  24639. *
  24640. */
  24641. function hypot() {
  24642. var i, n,
  24643. t = new this(0);
  24644. external = false;
  24645. for (i = 0; i < arguments.length;) {
  24646. n = new this(arguments[i++]);
  24647. if (!n.d) {
  24648. if (n.s) {
  24649. external = true;
  24650. return new this(1 / 0);
  24651. }
  24652. t = n;
  24653. } else if (t.d) {
  24654. t = t.plus(n.times(n));
  24655. }
  24656. }
  24657. external = true;
  24658. return t.sqrt();
  24659. }
  24660. /*
  24661. * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
  24662. * otherwise return false.
  24663. *
  24664. */
  24665. function isDecimalInstance(obj) {
  24666. return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false;
  24667. }
  24668. /*
  24669. * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
  24670. * significant digits using rounding mode `rounding`.
  24671. *
  24672. * x {number|string|Decimal}
  24673. *
  24674. */
  24675. function ln(x) {
  24676. return new this(x).ln();
  24677. }
  24678. /*
  24679. * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
  24680. * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
  24681. *
  24682. * log[y](x)
  24683. *
  24684. * x {number|string|Decimal} The argument of the logarithm.
  24685. * y {number|string|Decimal} The base of the logarithm.
  24686. *
  24687. */
  24688. function log(x, y) {
  24689. return new this(x).log(y);
  24690. }
  24691. /*
  24692. * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
  24693. * significant digits using rounding mode `rounding`.
  24694. *
  24695. * x {number|string|Decimal}
  24696. *
  24697. */
  24698. function log2(x) {
  24699. return new this(x).log(2);
  24700. }
  24701. /*
  24702. * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
  24703. * significant digits using rounding mode `rounding`.
  24704. *
  24705. * x {number|string|Decimal}
  24706. *
  24707. */
  24708. function log10(x) {
  24709. return new this(x).log(10);
  24710. }
  24711. /*
  24712. * Return a new Decimal whose value is the maximum of the arguments.
  24713. *
  24714. * arguments {number|string|Decimal}
  24715. *
  24716. */
  24717. function max() {
  24718. return maxOrMin(this, arguments, 'lt');
  24719. }
  24720. /*
  24721. * Return a new Decimal whose value is the minimum of the arguments.
  24722. *
  24723. * arguments {number|string|Decimal}
  24724. *
  24725. */
  24726. function min() {
  24727. return maxOrMin(this, arguments, 'gt');
  24728. }
  24729. /*
  24730. * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
  24731. * using rounding mode `rounding`.
  24732. *
  24733. * x {number|string|Decimal}
  24734. * y {number|string|Decimal}
  24735. *
  24736. */
  24737. function mod(x, y) {
  24738. return new this(x).mod(y);
  24739. }
  24740. /*
  24741. * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
  24742. * digits using rounding mode `rounding`.
  24743. *
  24744. * x {number|string|Decimal}
  24745. * y {number|string|Decimal}
  24746. *
  24747. */
  24748. function mul(x, y) {
  24749. return new this(x).mul(y);
  24750. }
  24751. /*
  24752. * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
  24753. * significant digits using rounding mode `rounding`.
  24754. *
  24755. * x {number|string|Decimal} The base.
  24756. * y {number|string|Decimal} The exponent.
  24757. *
  24758. */
  24759. function pow(x, y) {
  24760. return new this(x).pow(y);
  24761. }
  24762. /*
  24763. * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
  24764. * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
  24765. * are produced).
  24766. *
  24767. * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
  24768. *
  24769. */
  24770. function random(sd) {
  24771. var d, e, k, n,
  24772. i = 0,
  24773. r = new this(1),
  24774. rd = [];
  24775. if (sd === void 0) sd = this.precision;
  24776. else checkInt32(sd, 1, MAX_DIGITS);
  24777. k = Math.ceil(sd / LOG_BASE);
  24778. if (!this.crypto) {
  24779. for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
  24780. // Browsers supporting crypto.getRandomValues.
  24781. } else if (crypto.getRandomValues) {
  24782. d = crypto.getRandomValues(new Uint32Array(k));
  24783. for (; i < k;) {
  24784. n = d[i];
  24785. // 0 <= n < 4294967296
  24786. // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
  24787. if (n >= 4.29e9) {
  24788. d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
  24789. } else {
  24790. // 0 <= n <= 4289999999
  24791. // 0 <= (n % 1e7) <= 9999999
  24792. rd[i++] = n % 1e7;
  24793. }
  24794. }
  24795. // Node.js supporting crypto.randomBytes.
  24796. } else if (crypto.randomBytes) {
  24797. // buffer
  24798. d = crypto.randomBytes(k *= 4);
  24799. for (; i < k;) {
  24800. // 0 <= n < 2147483648
  24801. n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
  24802. // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
  24803. if (n >= 2.14e9) {
  24804. crypto.randomBytes(4).copy(d, i);
  24805. } else {
  24806. // 0 <= n <= 2139999999
  24807. // 0 <= (n % 1e7) <= 9999999
  24808. rd.push(n % 1e7);
  24809. i += 4;
  24810. }
  24811. }
  24812. i = k / 4;
  24813. } else {
  24814. throw Error(cryptoUnavailable);
  24815. }
  24816. k = rd[--i];
  24817. sd %= LOG_BASE;
  24818. // Convert trailing digits to zeros according to sd.
  24819. if (k && sd) {
  24820. n = mathpow(10, LOG_BASE - sd);
  24821. rd[i] = (k / n | 0) * n;
  24822. }
  24823. // Remove trailing words which are zero.
  24824. for (; rd[i] === 0; i--) rd.pop();
  24825. // Zero?
  24826. if (i < 0) {
  24827. e = 0;
  24828. rd = [0];
  24829. } else {
  24830. e = -1;
  24831. // Remove leading words which are zero and adjust exponent accordingly.
  24832. for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
  24833. // Count the digits of the first word of rd to determine leading zeros.
  24834. for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
  24835. // Adjust the exponent for leading zeros of the first word of rd.
  24836. if (k < LOG_BASE) e -= LOG_BASE - k;
  24837. }
  24838. r.e = e;
  24839. r.d = rd;
  24840. return r;
  24841. }
  24842. /*
  24843. * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
  24844. *
  24845. * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
  24846. *
  24847. * x {number|string|Decimal}
  24848. *
  24849. */
  24850. function round(x) {
  24851. return finalise(x = new this(x), x.e + 1, this.rounding);
  24852. }
  24853. /*
  24854. * Return
  24855. * 1 if x > 0,
  24856. * -1 if x < 0,
  24857. * 0 if x is 0,
  24858. * -0 if x is -0,
  24859. * NaN otherwise
  24860. *
  24861. * x {number|string|Decimal}
  24862. *
  24863. */
  24864. function sign(x) {
  24865. x = new this(x);
  24866. return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
  24867. }
  24868. /*
  24869. * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
  24870. * using rounding mode `rounding`.
  24871. *
  24872. * x {number|string|Decimal} A value in radians.
  24873. *
  24874. */
  24875. function sin(x) {
  24876. return new this(x).sin();
  24877. }
  24878. /*
  24879. * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
  24880. * significant digits using rounding mode `rounding`.
  24881. *
  24882. * x {number|string|Decimal} A value in radians.
  24883. *
  24884. */
  24885. function sinh(x) {
  24886. return new this(x).sinh();
  24887. }
  24888. /*
  24889. * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
  24890. * digits using rounding mode `rounding`.
  24891. *
  24892. * x {number|string|Decimal}
  24893. *
  24894. */
  24895. function sqrt(x) {
  24896. return new this(x).sqrt();
  24897. }
  24898. /*
  24899. * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
  24900. * using rounding mode `rounding`.
  24901. *
  24902. * x {number|string|Decimal}
  24903. * y {number|string|Decimal}
  24904. *
  24905. */
  24906. function sub(x, y) {
  24907. return new this(x).sub(y);
  24908. }
  24909. /*
  24910. * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
  24911. * digits using rounding mode `rounding`.
  24912. *
  24913. * x {number|string|Decimal} A value in radians.
  24914. *
  24915. */
  24916. function tan(x) {
  24917. return new this(x).tan();
  24918. }
  24919. /*
  24920. * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
  24921. * significant digits using rounding mode `rounding`.
  24922. *
  24923. * x {number|string|Decimal} A value in radians.
  24924. *
  24925. */
  24926. function tanh(x) {
  24927. return new this(x).tanh();
  24928. }
  24929. /*
  24930. * Return a new Decimal whose value is `x` truncated to an integer.
  24931. *
  24932. * x {number|string|Decimal}
  24933. *
  24934. */
  24935. function trunc(x) {
  24936. return finalise(x = new this(x), x.e + 1, 1);
  24937. }
  24938. // Create and configure initial Decimal constructor.
  24939. Decimal = clone(DEFAULTS);
  24940. Decimal['default'] = Decimal.Decimal = Decimal;
  24941. // Create the internal constants from their string values.
  24942. LN10 = new Decimal(LN10);
  24943. PI = new Decimal(PI);
  24944. // Export.
  24945. // AMD.
  24946. if (true) {
  24947. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
  24948. return Decimal;
  24949. }).call(exports, __webpack_require__, exports, module),
  24950. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  24951. // Node and other environments that support module.exports.
  24952. } else {}
  24953. })(this);
  24954. /***/ }),
  24955. /***/ "./node_modules/line-i18n/dist/LanguageService.js":
  24956. /*!********************************************************!*\
  24957. !*** ./node_modules/line-i18n/dist/LanguageService.js ***!
  24958. \********************************************************/
  24959. /*! exports provided: LanguageService */
  24960. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  24961. "use strict";
  24962. __webpack_require__.r(__webpack_exports__);
  24963. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LanguageService", function() { return LanguageService; });
  24964. var LanguageService = /** @class */ (function () {
  24965. function LanguageService(lsKey, defaultLang) {
  24966. if (defaultLang === void 0) { defaultLang = 'pt'; }
  24967. this.lsKey = lsKey;
  24968. this.defaultLang = defaultLang;
  24969. this.listeners = [];
  24970. this.document = document;
  24971. this.setupListener();
  24972. }
  24973. LanguageService.prototype.setupListener = function () {
  24974. var _this = this;
  24975. if (this.document !== null) {
  24976. this.document.addEventListener("storage", (function (event) {
  24977. var e = event;
  24978. if (e.key === _this.lsKey) {
  24979. _this.listeners.forEach(function (l) { return l(); });
  24980. }
  24981. }));
  24982. }
  24983. };
  24984. LanguageService.prototype.getLang = function () {
  24985. var lang = localStorage.getItem(this.lsKey);
  24986. if (lang === null || lang === undefined) {
  24987. console.warn("Internal Error: User language information has not been set. Returning default...");
  24988. return this.getDefaultLang();
  24989. }
  24990. return lang;
  24991. };
  24992. LanguageService.prototype.getDefaultLang = function () {
  24993. return this.defaultLang;
  24994. };
  24995. LanguageService.prototype.registerLanguageChangeListener = function (listener) {
  24996. this.listeners.push(listener);
  24997. };
  24998. return LanguageService;
  24999. }());
  25000. /***/ }),
  25001. /***/ "./node_modules/line-i18n/dist/LanguageServiceNoLS.js":
  25002. /*!************************************************************!*\
  25003. !*** ./node_modules/line-i18n/dist/LanguageServiceNoLS.js ***!
  25004. \************************************************************/
  25005. /*! exports provided: LanguageServiceNoLS */
  25006. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  25007. "use strict";
  25008. __webpack_require__.r(__webpack_exports__);
  25009. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LanguageServiceNoLS", function() { return LanguageServiceNoLS; });
  25010. var LanguageServiceNoLS = /** @class */ (function () {
  25011. function LanguageServiceNoLS(lang) {
  25012. this.lang = lang;
  25013. this.listeners = [];
  25014. }
  25015. LanguageServiceNoLS.prototype.setupListener = function () { };
  25016. LanguageServiceNoLS.prototype.notifyChange = function () {
  25017. this.listeners.forEach(function (l) { return l(); });
  25018. };
  25019. LanguageServiceNoLS.prototype.setLang = function (lang) {
  25020. this.lang = lang;
  25021. this.notifyChange();
  25022. };
  25023. LanguageServiceNoLS.prototype.getLang = function () {
  25024. return this.lang;
  25025. };
  25026. LanguageServiceNoLS.prototype.getDefaultLang = function () {
  25027. return this.lang;
  25028. };
  25029. LanguageServiceNoLS.prototype.registerLanguageChangeListener = function (listener) {
  25030. this.listeners.push(listener);
  25031. };
  25032. return LanguageServiceNoLS;
  25033. }());
  25034. /***/ }),
  25035. /***/ "./node_modules/line-i18n/dist/LocalizedStrings.js":
  25036. /*!*********************************************************!*\
  25037. !*** ./node_modules/line-i18n/dist/LocalizedStrings.js ***!
  25038. \*********************************************************/
  25039. /*! exports provided: LocalizedStrings */
  25040. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  25041. "use strict";
  25042. __webpack_require__.r(__webpack_exports__);
  25043. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocalizedStrings", function() { return LocalizedStrings; });
  25044. /* harmony import */ var _StringTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./StringTypes */ "./node_modules/line-i18n/dist/StringTypes.js");
  25045. var LocalizedStrings = /** @class */ (function () {
  25046. function LocalizedStrings(service, i18nData, listenToChange) {
  25047. var _this = this;
  25048. if (listenToChange === void 0) { listenToChange = false; }
  25049. this.service = service;
  25050. this.i18nData = i18nData;
  25051. this.listenToChange = listenToChange;
  25052. this.document = document;
  25053. if (this.listenToChange) {
  25054. service.registerLanguageChangeListener(function () {
  25055. _this.updateTagText();
  25056. });
  25057. }
  25058. }
  25059. LocalizedStrings.prototype.getString = function (id, type) {
  25060. var i18nObj = this.i18nData[this.service.getLang()];
  25061. if (!i18nObj) {
  25062. console.warn("Internal Error. The language set at ivprog.lang is not valid: " + this.service.getLang());
  25063. return this.getDefaultString(id, type);
  25064. }
  25065. if (!i18nObj[type]) {
  25066. return this.getDefaultString(id, type);
  25067. }
  25068. else if (!i18nObj[type][id]) {
  25069. return this.getDefaultString(id, type);
  25070. }
  25071. else {
  25072. return i18nObj[type][id];
  25073. }
  25074. };
  25075. LocalizedStrings.prototype.getDefaultString = function (id, type) {
  25076. var i18nObj = this.i18nData[this.service.getDefaultLang()];
  25077. if (!i18nObj[type]) {
  25078. return "{MISSING_I18N_TYPE_IDENTIFIER: " + type + "}";
  25079. }
  25080. else if (!i18nObj[type][id]) {
  25081. return "{MISSING_I18N_IDENTIFIER: " + id + "}";
  25082. }
  25083. else {
  25084. return i18nObj[type][id];
  25085. }
  25086. };
  25087. LocalizedStrings.prototype.getOR = function () {
  25088. return this.getUI("string_join_or");
  25089. };
  25090. LocalizedStrings.prototype.getError = function (id, context) {
  25091. if (context === void 0) { context = []; }
  25092. var text = this.getString(id, _StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].ERROR);
  25093. return this.processString(text, context);
  25094. };
  25095. LocalizedStrings.prototype.getMessage = function (id, context) {
  25096. if (context === void 0) { context = []; }
  25097. var text = this.getString(id, _StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].MESSAGE);
  25098. return this.processString(text, context);
  25099. };
  25100. LocalizedStrings.prototype.getUI = function (id, context) {
  25101. if (context === void 0) { context = []; }
  25102. var text = this.getString(id, _StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].UI);
  25103. return this.processString(text, context);
  25104. };
  25105. LocalizedStrings.prototype.processString = function (text, context) {
  25106. for (var i = 0; i < context.length; i++) {
  25107. var v = context[i];
  25108. text = text.replace("$" + i, v);
  25109. }
  25110. return text;
  25111. };
  25112. LocalizedStrings.prototype.updateTagText = function (func) {
  25113. var _this = this;
  25114. if (func === void 0) { func = null; }
  25115. if (this.document !== null) {
  25116. var list = this.document.querySelectorAll("data.i18n");
  25117. list.forEach(function (node) {
  25118. if (func === null) {
  25119. node.innerHTML = _this.processTagTex(node.getAttribute("value"));
  25120. }
  25121. else {
  25122. node.innerHTML = func(node.getAttribute("value"));
  25123. }
  25124. });
  25125. }
  25126. };
  25127. LocalizedStrings.prototype.processTagTex = function (text) {
  25128. if (text === null) {
  25129. return "<Invalid i18n identifier>";
  25130. }
  25131. var opts = text.split(":");
  25132. var type = opts[0].toLowerCase();
  25133. var id = opts[1];
  25134. if (_StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].ERROR === type) {
  25135. return this.getError(id);
  25136. }
  25137. else if (_StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].MESSAGE === type) {
  25138. return this.getMessage(id);
  25139. }
  25140. else if (_StringTypes__WEBPACK_IMPORTED_MODULE_0__["StringTypes"].UI === type) {
  25141. return this.getUI(id);
  25142. }
  25143. else {
  25144. console.warn(" A string has been passed to the i18n helper function that was not in the form type:id -> " +
  25145. text);
  25146. return this.getString(id, type);
  25147. }
  25148. };
  25149. return LocalizedStrings;
  25150. }());
  25151. /***/ }),
  25152. /***/ "./node_modules/line-i18n/dist/StringTypes.js":
  25153. /*!****************************************************!*\
  25154. !*** ./node_modules/line-i18n/dist/StringTypes.js ***!
  25155. \****************************************************/
  25156. /*! exports provided: StringTypes */
  25157. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  25158. "use strict";
  25159. __webpack_require__.r(__webpack_exports__);
  25160. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringTypes", function() { return StringTypes; });
  25161. var StringTypes;
  25162. (function (StringTypes) {
  25163. StringTypes["ERROR"] = "error";
  25164. StringTypes["MESSAGE"] = "message";
  25165. StringTypes["UI"] = "ui";
  25166. })(StringTypes || (StringTypes = {}));
  25167. /***/ }),
  25168. /***/ "./node_modules/line-i18n/dist/index.js":
  25169. /*!**********************************************!*\
  25170. !*** ./node_modules/line-i18n/dist/index.js ***!
  25171. \**********************************************/
  25172. /*! exports provided: default */
  25173. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  25174. "use strict";
  25175. __webpack_require__.r(__webpack_exports__);
  25176. /* harmony import */ var _LanguageService__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./LanguageService */ "./node_modules/line-i18n/dist/LanguageService.js");
  25177. /* harmony import */ var _LocalizedStrings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./LocalizedStrings */ "./node_modules/line-i18n/dist/LocalizedStrings.js");
  25178. /* harmony import */ var _StringTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./StringTypes */ "./node_modules/line-i18n/dist/StringTypes.js");
  25179. /* harmony import */ var _LanguageServiceNoLS__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LanguageServiceNoLS */ "./node_modules/line-i18n/dist/LanguageServiceNoLS.js");
  25180. /* harmony default export */ __webpack_exports__["default"] = ({
  25181. LanguageService: _LanguageService__WEBPACK_IMPORTED_MODULE_0__["LanguageService"],
  25182. LanguageServiceNoLS: _LanguageServiceNoLS__WEBPACK_IMPORTED_MODULE_3__["LanguageServiceNoLS"],
  25183. LocalizedStrings: _LocalizedStrings__WEBPACK_IMPORTED_MODULE_1__["LocalizedStrings"],
  25184. StringTypes: _StringTypes__WEBPACK_IMPORTED_MODULE_2__["StringTypes"]
  25185. });
  25186. /***/ }),
  25187. /***/ "./node_modules/melanke-watchjs/src/watch.js":
  25188. /*!***************************************************!*\
  25189. !*** ./node_modules/melanke-watchjs/src/watch.js ***!
  25190. \***************************************************/
  25191. /*! no static exports found */
  25192. /***/ (function(module, exports, __webpack_require__) {
  25193. "use strict";
  25194. /**
  25195. * DEVELOPED BY
  25196. * GIL LOPES BUENO
  25197. * gilbueno.mail@gmail.com
  25198. *
  25199. * WORKS WITH:
  25200. * IE8*, IE 9+, FF 4+, SF 5+, WebKit, CH 7+, OP 12+, BESEN, Rhino 1.7+
  25201. * For IE8 (and other legacy browsers) WatchJS will use dirty checking
  25202. *
  25203. * FORK:
  25204. * https://github.com/melanke/Watch.JS
  25205. *
  25206. * LICENSE: MIT
  25207. */
  25208. (function (factory) {
  25209. if (true) {
  25210. // Node. Does not work with strict CommonJS, but
  25211. // only CommonJS-like enviroments that support module.exports,
  25212. // like Node.
  25213. module.exports = factory();
  25214. } else {}
  25215. }(function () {
  25216. var WatchJS = {
  25217. noMore: false, // use WatchJS.suspend(obj) instead
  25218. useDirtyCheck: false, // use only dirty checking to track changes.
  25219. preserveExistingSetters: false
  25220. },
  25221. lengthsubjects = [];
  25222. var dirtyChecklist = [];
  25223. var pendingChanges = []; // used coalesce changes from defineProperty and __defineSetter__
  25224. var supportDefineProperty = false;
  25225. try {
  25226. supportDefineProperty = Object.defineProperty && Object.defineProperty({},'x', {});
  25227. } catch(ex) { /* not supported */ }
  25228. var isFunction = function (functionToCheck) {
  25229. var getType = {};
  25230. return functionToCheck && getType.toString.call(functionToCheck) == '[object Function]';
  25231. };
  25232. var isInt = function (x) {
  25233. return x % 1 === 0;
  25234. };
  25235. var isArray = function(obj) {
  25236. return Object.prototype.toString.call(obj) === '[object Array]';
  25237. };
  25238. var isObject = function(obj) {
  25239. return {}.toString.apply(obj) === '[object Object]';
  25240. };
  25241. var getObjDiff = function(a, b){
  25242. var aplus = [],
  25243. bplus = [];
  25244. if(!(typeof a == "string") && !(typeof b == "string")){
  25245. if (isArray(a) && b) {
  25246. for (var i=0; i<a.length; i++) {
  25247. if (b[i] === undefined) aplus.push(i);
  25248. }
  25249. } else {
  25250. for(var i in a){
  25251. if (a.hasOwnProperty(i)) {
  25252. if(b && !b.hasOwnProperty(i)) {
  25253. aplus.push(i);
  25254. }
  25255. }
  25256. }
  25257. }
  25258. if (isArray(b) && a) {
  25259. for (var j=0; j<b.length; j++) {
  25260. if (a[j] === undefined) bplus.push(j);
  25261. }
  25262. } else {
  25263. for(var j in b){
  25264. if (b.hasOwnProperty(j)) {
  25265. if(a && !a.hasOwnProperty(j)) {
  25266. bplus.push(j);
  25267. }
  25268. }
  25269. }
  25270. }
  25271. }
  25272. return {
  25273. added: aplus,
  25274. removed: bplus
  25275. }
  25276. };
  25277. var clone = function(obj){
  25278. if (null == obj || "object" != typeof obj) {
  25279. return obj;
  25280. }
  25281. var copy = obj.constructor();
  25282. for (var attr in obj) {
  25283. copy[attr] = obj[attr];
  25284. }
  25285. return copy;
  25286. }
  25287. var getExistingSetter = function (obj, propName) {
  25288. if (WatchJS.preserveExistingSetters) {
  25289. var existing = Object.getOwnPropertyDescriptor(obj, propName);
  25290. return existing.set;
  25291. }
  25292. return undefined;
  25293. }
  25294. var defineGetAndSet = function (obj, propName, getter, setter) {
  25295. try {
  25296. var existingSetter = getExistingSetter(obj, propName);
  25297. Object.defineProperty(obj, propName, {
  25298. get: getter,
  25299. set: function(value) {
  25300. setter.call(this, value, true); // coalesce changes
  25301. if (existingSetter) {
  25302. existingSetter(value);
  25303. }
  25304. },
  25305. enumerable: true,
  25306. configurable: true
  25307. });
  25308. }
  25309. catch(e1) {
  25310. try{
  25311. Object.prototype.__defineGetter__.call(obj, propName, getter);
  25312. Object.prototype.__defineSetter__.call(obj, propName, function(value) {
  25313. setter.call(this,value,true); // coalesce changes
  25314. });
  25315. }
  25316. catch(e2) {
  25317. observeDirtyChanges(obj,propName,setter);
  25318. //throw new Error("watchJS error: browser not supported :/")
  25319. }
  25320. }
  25321. };
  25322. var defineProp = function (obj, propName, value) {
  25323. try {
  25324. Object.defineProperty(obj, propName, {
  25325. enumerable: false,
  25326. configurable: true,
  25327. writable: false,
  25328. value: value
  25329. });
  25330. } catch(error) {
  25331. obj[propName] = value;
  25332. }
  25333. };
  25334. var observeDirtyChanges = function(obj,propName,setter) {
  25335. dirtyChecklist[dirtyChecklist.length] = {
  25336. prop: propName,
  25337. object: obj,
  25338. orig: clone(obj[propName]),
  25339. callback: setter
  25340. }
  25341. }
  25342. var watch = function () {
  25343. if (isFunction(arguments[1])) {
  25344. watchAll.apply(this, arguments);
  25345. } else if (isArray(arguments[1])) {
  25346. watchMany.apply(this, arguments);
  25347. } else {
  25348. watchOne.apply(this, arguments);
  25349. }
  25350. };
  25351. var watchAll = function (obj, watcher, level, addNRemove) {
  25352. if ((typeof obj == "string") || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  25353. return;
  25354. }
  25355. if(isArray(obj)) {
  25356. defineWatcher(obj, "__watchall__", watcher, level); // watch all changes on the array
  25357. if (level===undefined||level > 0) {
  25358. for (var prop = 0; prop < obj.length; prop++) { // watch objects in array
  25359. watchAll(obj[prop],watcher,level, addNRemove);
  25360. }
  25361. }
  25362. }
  25363. else {
  25364. var prop,props = [];
  25365. for (prop in obj) { //for each attribute if obj is an object
  25366. if (prop == "$val" || (!supportDefineProperty && prop === 'watchers')) {
  25367. continue;
  25368. }
  25369. if (Object.prototype.hasOwnProperty.call(obj, prop)) {
  25370. props.push(prop); //put in the props
  25371. }
  25372. }
  25373. watchMany(obj, props, watcher, level, addNRemove); //watch all items of the props
  25374. }
  25375. if (addNRemove) {
  25376. pushToLengthSubjects(obj, "$$watchlengthsubjectroot", watcher, level);
  25377. }
  25378. };
  25379. var watchMany = function (obj, props, watcher, level, addNRemove) {
  25380. if ((typeof obj == "string") || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  25381. return;
  25382. }
  25383. for (var i=0; i<props.length; i++) { //watch each property
  25384. var prop = props[i];
  25385. watchOne(obj, prop, watcher, level, addNRemove);
  25386. }
  25387. };
  25388. var watchOne = function (obj, prop, watcher, level, addNRemove) {
  25389. if ((typeof obj == "string") || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  25390. return;
  25391. }
  25392. if(isFunction(obj[prop])) { //dont watch if it is a function
  25393. return;
  25394. }
  25395. if(obj[prop] != null && (level === undefined || level > 0)){
  25396. watchAll(obj[prop], watcher, level!==undefined? level-1 : level); //recursively watch all attributes of this
  25397. }
  25398. defineWatcher(obj, prop, watcher, level);
  25399. if(addNRemove && (level === undefined || level > 0)){
  25400. pushToLengthSubjects(obj, prop, watcher, level);
  25401. }
  25402. };
  25403. var unwatch = function () {
  25404. if (isFunction(arguments[1])) {
  25405. unwatchAll.apply(this, arguments);
  25406. } else if (isArray(arguments[1])) {
  25407. unwatchMany.apply(this, arguments);
  25408. } else {
  25409. unwatchOne.apply(this, arguments);
  25410. }
  25411. };
  25412. var unwatchAll = function (obj, watcher) {
  25413. if (obj instanceof String || (!(obj instanceof Object) && !isArray(obj))) { //accepts only objects and array (not string)
  25414. return;
  25415. }
  25416. if (isArray(obj)) {
  25417. var props = ['__watchall__'];
  25418. for (var prop = 0; prop < obj.length; prop++) { //for each item if obj is an array
  25419. props.push(prop); //put in the props
  25420. }
  25421. unwatchMany(obj, props, watcher); //watch all itens of the props
  25422. } else {
  25423. var unwatchPropsInObject = function (obj2) {
  25424. var props = [];
  25425. for (var prop2 in obj2) { //for each attribute if obj is an object
  25426. if (obj2.hasOwnProperty(prop2)) {
  25427. if (obj2[prop2] instanceof Object) {
  25428. unwatchPropsInObject(obj2[prop2]); //recurs into object props
  25429. } else {
  25430. props.push(prop2); //put in the props
  25431. }
  25432. }
  25433. }
  25434. unwatchMany(obj2, props, watcher); //unwatch all of the props
  25435. };
  25436. unwatchPropsInObject(obj);
  25437. }
  25438. };
  25439. var unwatchMany = function (obj, props, watcher) {
  25440. for (var prop2 in props) { //watch each attribute of "props" if is an object
  25441. if (props.hasOwnProperty(prop2)) {
  25442. unwatchOne(obj, props[prop2], watcher);
  25443. }
  25444. }
  25445. };
  25446. var timeouts = [],
  25447. timerID = null;
  25448. function clearTimerID() {
  25449. timerID = null;
  25450. for(var i=0; i< timeouts.length; i++) {
  25451. timeouts[i]();
  25452. }
  25453. timeouts.length = 0;
  25454. }
  25455. var getTimerID= function () {
  25456. if (!timerID) {
  25457. timerID = setTimeout(clearTimerID);
  25458. }
  25459. return timerID;
  25460. }
  25461. var registerTimeout = function(fn) { // register function to be called on timeout
  25462. if (timerID==null) getTimerID();
  25463. timeouts[timeouts.length] = fn;
  25464. }
  25465. // Track changes made to an array, object or an object's property
  25466. // and invoke callback with a single change object containing type, value, oldvalue and array splices
  25467. // Syntax:
  25468. // trackChange(obj, callback, recursive, addNRemove)
  25469. // trackChange(obj, prop, callback, recursive, addNRemove)
  25470. var trackChange = function() {
  25471. var fn = (isFunction(arguments[2])) ? trackProperty : trackObject ;
  25472. fn.apply(this,arguments);
  25473. }
  25474. // track changes made to an object and invoke callback with a single change object containing type, value and array splices
  25475. var trackObject= function(obj, callback, recursive, addNRemove) {
  25476. var change = null,lastTimerID = -1;
  25477. var isArr = isArray(obj);
  25478. var level,fn = function(prop, action, newValue, oldValue) {
  25479. var timerID = getTimerID();
  25480. if (lastTimerID!==timerID) { // check if timer has changed since last update
  25481. lastTimerID = timerID;
  25482. change = {
  25483. type: 'update'
  25484. }
  25485. change['value'] = obj;
  25486. change['splices'] = null;
  25487. registerTimeout(function() {
  25488. callback.call(this,change);
  25489. change = null;
  25490. });
  25491. }
  25492. // create splices for array changes
  25493. if (isArr && obj === this && change !== null) {
  25494. if (action==='pop'||action==='shift') {
  25495. newValue = [];
  25496. oldValue = [oldValue];
  25497. }
  25498. else if (action==='push'||action==='unshift') {
  25499. newValue = [newValue];
  25500. oldValue = [];
  25501. }
  25502. else if (action!=='splice') {
  25503. return; // return here - for reverse and sort operations we don't need to return splices. a simple update will do
  25504. }
  25505. if (!change.splices) change.splices = [];
  25506. change.splices[change.splices.length] = {
  25507. index: prop,
  25508. deleteCount: oldValue ? oldValue.length : 0,
  25509. addedCount: newValue ? newValue.length : 0,
  25510. added: newValue,
  25511. deleted: oldValue
  25512. };
  25513. }
  25514. }
  25515. level = (recursive==true) ? undefined : 0;
  25516. watchAll(obj,fn, level, addNRemove);
  25517. }
  25518. // track changes made to the property of an object and invoke callback with a single change object containing type, value, oldvalue and splices
  25519. var trackProperty = function(obj,prop,callback,recursive, addNRemove) {
  25520. if (obj && prop) {
  25521. watchOne(obj,prop,function(prop, action, newvalue, oldvalue) {
  25522. var change = {
  25523. type: 'update'
  25524. }
  25525. change['value'] = newvalue;
  25526. change['oldvalue'] = oldvalue;
  25527. if (recursive && isObject(newvalue)||isArray(newvalue)) {
  25528. trackObject(newvalue,callback,recursive, addNRemove);
  25529. }
  25530. callback.call(this,change);
  25531. },0)
  25532. if (recursive && isObject(obj[prop])||isArray(obj[prop])) {
  25533. trackObject(obj[prop],callback,recursive, addNRemove);
  25534. }
  25535. }
  25536. }
  25537. var defineWatcher = function (obj, prop, watcher, level) {
  25538. var newWatcher = false;
  25539. var isArr = isArray(obj);
  25540. if (!obj.watchers) {
  25541. defineProp(obj, "watchers", {});
  25542. if (isArr) {
  25543. // watch array functions
  25544. watchFunctions(obj, function(index,action,newValue, oldValue) {
  25545. addPendingChange(obj, index, action,newValue, oldValue);
  25546. if (level !== 0 && newValue && (isObject(newValue) || isArray(newValue))) {
  25547. var i,n, ln, wAll, watchList = obj.watchers[prop];
  25548. if ((wAll = obj.watchers['__watchall__'])) {
  25549. watchList = watchList ? watchList.concat(wAll) : wAll;
  25550. }
  25551. ln = watchList ? watchList.length : 0;
  25552. for (i = 0; i<ln; i++) {
  25553. if (action!=='splice') {
  25554. watchAll(newValue, watchList[i], (level===undefined)?level:level-1);
  25555. }
  25556. else {
  25557. // watch spliced values
  25558. for(n=0; n < newValue.length; n++) {
  25559. watchAll(newValue[n], watchList[i], (level===undefined)?level:level-1);
  25560. }
  25561. }
  25562. }
  25563. }
  25564. });
  25565. }
  25566. }
  25567. if (!obj.watchers[prop]) {
  25568. obj.watchers[prop] = [];
  25569. if (!isArr) newWatcher = true;
  25570. }
  25571. for (var i=0; i<obj.watchers[prop].length; i++) {
  25572. if(obj.watchers[prop][i] === watcher){
  25573. return;
  25574. }
  25575. }
  25576. obj.watchers[prop].push(watcher); //add the new watcher to the watchers array
  25577. if (newWatcher) {
  25578. var val = obj[prop];
  25579. var getter = function () {
  25580. return val;
  25581. };
  25582. var setter = function (newval, delayWatcher) {
  25583. var oldval = val;
  25584. val = newval;
  25585. if (level !== 0
  25586. && obj[prop] && (isObject(obj[prop]) || isArray(obj[prop]))
  25587. && !obj[prop].watchers) {
  25588. // watch sub properties
  25589. var i,ln = obj.watchers[prop].length;
  25590. for(i=0; i<ln; i++) {
  25591. watchAll(obj[prop], obj.watchers[prop][i], (level===undefined)?level:level-1);
  25592. }
  25593. }
  25594. //watchFunctions(obj, prop);
  25595. if (isSuspended(obj, prop)) {
  25596. resume(obj, prop);
  25597. return;
  25598. }
  25599. if (!WatchJS.noMore){ // this does not work with Object.observe
  25600. //if (JSON.stringify(oldval) !== JSON.stringify(newval)) {
  25601. if (obj[prop] instanceof Date && oldval && newval) {
  25602. oldval = oldval.valueOf();
  25603. newval = newval.valueOf();
  25604. }
  25605. if (oldval !== newval) {
  25606. if (!delayWatcher) {
  25607. callWatchers(obj, prop, "set", newval, oldval);
  25608. }
  25609. else {
  25610. addPendingChange(obj, prop, "set", newval, oldval);
  25611. }
  25612. WatchJS.noMore = false;
  25613. }
  25614. }
  25615. };
  25616. if (WatchJS.useDirtyCheck) {
  25617. observeDirtyChanges(obj,prop,setter);
  25618. }
  25619. else {
  25620. defineGetAndSet(obj, prop, getter, setter);
  25621. }
  25622. }
  25623. };
  25624. var callWatchers = function (obj, prop, action, newval, oldval) {
  25625. if (prop !== undefined) {
  25626. var ln, wl, watchList = obj.watchers[prop];
  25627. if ((wl = obj.watchers['__watchall__'])) {
  25628. watchList = watchList ? watchList.concat(wl) : wl;
  25629. }
  25630. ln = watchList ? watchList.length : 0;
  25631. for (var wr=0; wr< ln; wr++) {
  25632. watchList[wr].call(obj, prop, action, newval, oldval);
  25633. }
  25634. } else {
  25635. for (var prop in obj) {//call all
  25636. if (obj.hasOwnProperty(prop)) {
  25637. callWatchers(obj, prop, action, newval, oldval);
  25638. }
  25639. }
  25640. }
  25641. };
  25642. var methodNames = ['pop', 'push', 'reverse', 'shift', 'sort', 'slice', 'unshift', 'splice'];
  25643. var defineArrayMethodWatcher = function (obj, original, methodName, callback) {
  25644. defineProp(obj, methodName, function () {
  25645. var index = 0;
  25646. var i,newValue, oldValue, response;
  25647. // get values before splicing array
  25648. if (methodName === 'splice') {
  25649. var start = arguments[0];
  25650. var end = start + arguments[1];
  25651. oldValue = obj.slice(start,end);
  25652. newValue = [];
  25653. for(i=2;i<arguments.length;i++) {
  25654. newValue[i-2] = arguments[i];
  25655. }
  25656. index = start;
  25657. }
  25658. else {
  25659. newValue = arguments.length > 0 ? arguments[0] : undefined;
  25660. }
  25661. response = original.apply(obj, arguments);
  25662. if (methodName !== 'slice') {
  25663. if (methodName === 'pop') {
  25664. oldValue = response;
  25665. index = obj.length;
  25666. }
  25667. else if (methodName === 'push') {
  25668. index = obj.length-1;
  25669. }
  25670. else if (methodName === 'shift') {
  25671. oldValue = response;
  25672. }
  25673. else if (methodName !== 'unshift' && newValue===undefined) {
  25674. newValue = response;
  25675. }
  25676. callback.call(obj, index, methodName,newValue, oldValue)
  25677. }
  25678. return response;
  25679. });
  25680. };
  25681. var watchFunctions = function(obj, callback) {
  25682. if (!isFunction(callback) || !obj || (obj instanceof String) || (!isArray(obj))) {
  25683. return;
  25684. }
  25685. for (var i = methodNames.length, methodName; i--;) {
  25686. methodName = methodNames[i];
  25687. defineArrayMethodWatcher(obj, obj[methodName], methodName, callback);
  25688. }
  25689. };
  25690. var unwatchOne = function (obj, prop, watcher) {
  25691. if (prop) {
  25692. if (obj.watchers && obj.watchers[prop]) {
  25693. if (watcher === undefined) {
  25694. delete obj.watchers[prop]; // remove all property watchers
  25695. }
  25696. else {
  25697. for (var i = 0; i < obj.watchers[prop].length; i++) {
  25698. var w = obj.watchers[prop][i];
  25699. if (w == watcher) {
  25700. obj.watchers[prop].splice(i, 1);
  25701. }
  25702. }
  25703. }
  25704. }
  25705. } else {
  25706. delete obj.watchers;
  25707. }
  25708. removeFromLengthSubjects(obj, prop, watcher);
  25709. removeFromDirtyChecklist(obj, prop);
  25710. };
  25711. // suspend watchers until next update cycle
  25712. var suspend = function(obj, prop) {
  25713. if (obj.watchers) {
  25714. var name = '__wjs_suspend__'+(prop!==undefined ? prop : '');
  25715. obj.watchers[name] = true;
  25716. }
  25717. }
  25718. var isSuspended = function(obj, prop) {
  25719. return obj.watchers
  25720. && (obj.watchers['__wjs_suspend__'] ||
  25721. obj.watchers['__wjs_suspend__'+prop]);
  25722. }
  25723. // resumes preivously suspended watchers
  25724. var resume = function(obj, prop) {
  25725. registerTimeout(function() {
  25726. delete obj.watchers['__wjs_suspend__'];
  25727. delete obj.watchers['__wjs_suspend__'+prop];
  25728. })
  25729. }
  25730. var pendingTimerID = null;
  25731. var addPendingChange = function(obj,prop, mode, newval, oldval) {
  25732. pendingChanges[pendingChanges.length] = {
  25733. obj:obj,
  25734. prop: prop,
  25735. mode: mode,
  25736. newval: newval,
  25737. oldval: oldval
  25738. };
  25739. if (pendingTimerID===null) {
  25740. pendingTimerID = setTimeout(applyPendingChanges);
  25741. }
  25742. };
  25743. var applyPendingChanges = function() {
  25744. // apply pending changes
  25745. var change = null;
  25746. pendingTimerID = null;
  25747. for(var i=0;i < pendingChanges.length;i++) {
  25748. change = pendingChanges[i];
  25749. callWatchers(change.obj, change.prop, change.mode, change.newval, change.oldval);
  25750. }
  25751. if (change) {
  25752. pendingChanges = [];
  25753. change = null;
  25754. }
  25755. }
  25756. var loop = function(){
  25757. // check for new or deleted props
  25758. for(var i=0; i<lengthsubjects.length; i++) {
  25759. var subj = lengthsubjects[i];
  25760. if (subj.prop === "$$watchlengthsubjectroot") {
  25761. var difference = getObjDiff(subj.obj, subj.actual);
  25762. if(difference.added.length || difference.removed.length){
  25763. if(difference.added.length){
  25764. watchMany(subj.obj, difference.added, subj.watcher, subj.level - 1, true);
  25765. }
  25766. subj.watcher.call(subj.obj, "root", "differentattr", difference, subj.actual);
  25767. }
  25768. subj.actual = clone(subj.obj);
  25769. } else {
  25770. var difference = getObjDiff(subj.obj[subj.prop], subj.actual);
  25771. if(difference.added.length || difference.removed.length){
  25772. if(difference.added.length){
  25773. for (var j=0; j<subj.obj.watchers[subj.prop].length; j++) {
  25774. watchMany(subj.obj[subj.prop], difference.added, subj.obj.watchers[subj.prop][j], subj.level - 1, true);
  25775. }
  25776. }
  25777. callWatchers(subj.obj, subj.prop, "differentattr", difference, subj.actual);
  25778. }
  25779. subj.actual = clone(subj.obj[subj.prop]);
  25780. }
  25781. }
  25782. // start dirty check
  25783. var n, value;
  25784. if (dirtyChecklist.length > 0) {
  25785. for (var i = 0; i < dirtyChecklist.length; i++) {
  25786. n = dirtyChecklist[i];
  25787. value = n.object[n.prop];
  25788. if (!compareValues(n.orig, value)) {
  25789. n.orig = clone(value);
  25790. n.callback(value);
  25791. }
  25792. }
  25793. }
  25794. };
  25795. var compareValues = function(a,b) {
  25796. var i, state = true;
  25797. if (a!==b) {
  25798. if (isObject(a)) {
  25799. for(i in a) {
  25800. if (!supportDefineProperty && i==='watchers') continue;
  25801. if (a[i]!==b[i]) {
  25802. state = false;
  25803. break;
  25804. };
  25805. }
  25806. }
  25807. else {
  25808. state = false;
  25809. }
  25810. }
  25811. return state;
  25812. }
  25813. var pushToLengthSubjects = function(obj, prop, watcher, level){
  25814. var actual;
  25815. if (prop === "$$watchlengthsubjectroot") {
  25816. actual = clone(obj);
  25817. } else {
  25818. actual = clone(obj[prop]);
  25819. }
  25820. lengthsubjects.push({
  25821. obj: obj,
  25822. prop: prop,
  25823. actual: actual,
  25824. watcher: watcher,
  25825. level: level
  25826. });
  25827. };
  25828. var removeFromLengthSubjects = function(obj, prop, watcher){
  25829. for (var i=0; i<lengthsubjects.length; i++) {
  25830. var subj = lengthsubjects[i];
  25831. if (subj.obj == obj) {
  25832. if (!prop || subj.prop == prop) {
  25833. if (!watcher || subj.watcher == watcher) {
  25834. // if we splice off one item at position i
  25835. // we need to decrement i as the array is one item shorter
  25836. // so when we increment i in the loop statement we
  25837. // will land at the correct index.
  25838. // if it's not decremented, you won't delete all length subjects
  25839. lengthsubjects.splice(i--, 1);
  25840. }
  25841. }
  25842. }
  25843. }
  25844. };
  25845. var removeFromDirtyChecklist = function(obj, prop){
  25846. var notInUse;
  25847. for (var i=0; i<dirtyChecklist.length; i++) {
  25848. var n = dirtyChecklist[i];
  25849. var watchers = n.object.watchers;
  25850. notInUse = (
  25851. n.object == obj
  25852. && (!prop || n.prop == prop)
  25853. && watchers
  25854. && (!prop || !watchers[prop] || watchers[prop].length == 0 )
  25855. );
  25856. if (notInUse) {
  25857. // we use the same syntax as in removeFromLengthSubjects
  25858. dirtyChecklist.splice(i--, 1);
  25859. }
  25860. }
  25861. };
  25862. setInterval(loop, 50);
  25863. WatchJS.watch = watch;
  25864. WatchJS.unwatch = unwatch;
  25865. WatchJS.callWatchers = callWatchers;
  25866. WatchJS.suspend = suspend; // suspend watchers
  25867. WatchJS.onChange = trackChange; // track changes made to object or it's property and return a single change object
  25868. return WatchJS;
  25869. }));
  25870. /***/ }),
  25871. /***/ "./node_modules/node-libs-browser/mock/empty.js":
  25872. /*!******************************************************!*\
  25873. !*** ./node_modules/node-libs-browser/mock/empty.js ***!
  25874. \******************************************************/
  25875. /*! no static exports found */
  25876. /***/ (function(module, exports) {
  25877. /***/ }),
  25878. /***/ "./node_modules/regenerator-runtime/runtime.js":
  25879. /*!*****************************************************!*\
  25880. !*** ./node_modules/regenerator-runtime/runtime.js ***!
  25881. \*****************************************************/
  25882. /*! no static exports found */
  25883. /***/ (function(module, exports, __webpack_require__) {
  25884. /**
  25885. * Copyright (c) 2014-present, Facebook, Inc.
  25886. *
  25887. * This source code is licensed under the MIT license found in the
  25888. * LICENSE file in the root directory of this source tree.
  25889. */
  25890. var runtime = (function (exports) {
  25891. "use strict";
  25892. var Op = Object.prototype;
  25893. var hasOwn = Op.hasOwnProperty;
  25894. var undefined; // More compressible than void 0.
  25895. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  25896. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  25897. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  25898. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  25899. function wrap(innerFn, outerFn, self, tryLocsList) {
  25900. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  25901. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  25902. var generator = Object.create(protoGenerator.prototype);
  25903. var context = new Context(tryLocsList || []);
  25904. // The ._invoke method unifies the implementations of the .next,
  25905. // .throw, and .return methods.
  25906. generator._invoke = makeInvokeMethod(innerFn, self, context);
  25907. return generator;
  25908. }
  25909. exports.wrap = wrap;
  25910. // Try/catch helper to minimize deoptimizations. Returns a completion
  25911. // record like context.tryEntries[i].completion. This interface could
  25912. // have been (and was previously) designed to take a closure to be
  25913. // invoked without arguments, but in all the cases we care about we
  25914. // already have an existing method we want to call, so there's no need
  25915. // to create a new function object. We can even get away with assuming
  25916. // the method takes exactly one argument, since that happens to be true
  25917. // in every case, so we don't have to touch the arguments object. The
  25918. // only additional allocation required is the completion record, which
  25919. // has a stable shape and so hopefully should be cheap to allocate.
  25920. function tryCatch(fn, obj, arg) {
  25921. try {
  25922. return { type: "normal", arg: fn.call(obj, arg) };
  25923. } catch (err) {
  25924. return { type: "throw", arg: err };
  25925. }
  25926. }
  25927. var GenStateSuspendedStart = "suspendedStart";
  25928. var GenStateSuspendedYield = "suspendedYield";
  25929. var GenStateExecuting = "executing";
  25930. var GenStateCompleted = "completed";
  25931. // Returning this object from the innerFn has the same effect as
  25932. // breaking out of the dispatch switch statement.
  25933. var ContinueSentinel = {};
  25934. // Dummy constructor functions that we use as the .constructor and
  25935. // .constructor.prototype properties for functions that return Generator
  25936. // objects. For full spec compliance, you may wish to configure your
  25937. // minifier not to mangle the names of these two functions.
  25938. function Generator() {}
  25939. function GeneratorFunction() {}
  25940. function GeneratorFunctionPrototype() {}
  25941. // This is a polyfill for %IteratorPrototype% for environments that
  25942. // don't natively support it.
  25943. var IteratorPrototype = {};
  25944. IteratorPrototype[iteratorSymbol] = function () {
  25945. return this;
  25946. };
  25947. var getProto = Object.getPrototypeOf;
  25948. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  25949. if (NativeIteratorPrototype &&
  25950. NativeIteratorPrototype !== Op &&
  25951. hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  25952. // This environment has a native %IteratorPrototype%; use it instead
  25953. // of the polyfill.
  25954. IteratorPrototype = NativeIteratorPrototype;
  25955. }
  25956. var Gp = GeneratorFunctionPrototype.prototype =
  25957. Generator.prototype = Object.create(IteratorPrototype);
  25958. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  25959. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  25960. GeneratorFunctionPrototype[toStringTagSymbol] =
  25961. GeneratorFunction.displayName = "GeneratorFunction";
  25962. // Helper for defining the .next, .throw, and .return methods of the
  25963. // Iterator interface in terms of a single ._invoke method.
  25964. function defineIteratorMethods(prototype) {
  25965. ["next", "throw", "return"].forEach(function(method) {
  25966. prototype[method] = function(arg) {
  25967. return this._invoke(method, arg);
  25968. };
  25969. });
  25970. }
  25971. exports.isGeneratorFunction = function(genFun) {
  25972. var ctor = typeof genFun === "function" && genFun.constructor;
  25973. return ctor
  25974. ? ctor === GeneratorFunction ||
  25975. // For the native GeneratorFunction constructor, the best we can
  25976. // do is to check its .name property.
  25977. (ctor.displayName || ctor.name) === "GeneratorFunction"
  25978. : false;
  25979. };
  25980. exports.mark = function(genFun) {
  25981. if (Object.setPrototypeOf) {
  25982. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  25983. } else {
  25984. genFun.__proto__ = GeneratorFunctionPrototype;
  25985. if (!(toStringTagSymbol in genFun)) {
  25986. genFun[toStringTagSymbol] = "GeneratorFunction";
  25987. }
  25988. }
  25989. genFun.prototype = Object.create(Gp);
  25990. return genFun;
  25991. };
  25992. // Within the body of any async function, `await x` is transformed to
  25993. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  25994. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  25995. // meant to be awaited.
  25996. exports.awrap = function(arg) {
  25997. return { __await: arg };
  25998. };
  25999. function AsyncIterator(generator, PromiseImpl) {
  26000. function invoke(method, arg, resolve, reject) {
  26001. var record = tryCatch(generator[method], generator, arg);
  26002. if (record.type === "throw") {
  26003. reject(record.arg);
  26004. } else {
  26005. var result = record.arg;
  26006. var value = result.value;
  26007. if (value &&
  26008. typeof value === "object" &&
  26009. hasOwn.call(value, "__await")) {
  26010. return PromiseImpl.resolve(value.__await).then(function(value) {
  26011. invoke("next", value, resolve, reject);
  26012. }, function(err) {
  26013. invoke("throw", err, resolve, reject);
  26014. });
  26015. }
  26016. return PromiseImpl.resolve(value).then(function(unwrapped) {
  26017. // When a yielded Promise is resolved, its final value becomes
  26018. // the .value of the Promise<{value,done}> result for the
  26019. // current iteration.
  26020. result.value = unwrapped;
  26021. resolve(result);
  26022. }, function(error) {
  26023. // If a rejected Promise was yielded, throw the rejection back
  26024. // into the async generator function so it can be handled there.
  26025. return invoke("throw", error, resolve, reject);
  26026. });
  26027. }
  26028. }
  26029. var previousPromise;
  26030. function enqueue(method, arg) {
  26031. function callInvokeWithMethodAndArg() {
  26032. return new PromiseImpl(function(resolve, reject) {
  26033. invoke(method, arg, resolve, reject);
  26034. });
  26035. }
  26036. return previousPromise =
  26037. // If enqueue has been called before, then we want to wait until
  26038. // all previous Promises have been resolved before calling invoke,
  26039. // so that results are always delivered in the correct order. If
  26040. // enqueue has not been called before, then it is important to
  26041. // call invoke immediately, without waiting on a callback to fire,
  26042. // so that the async generator function has the opportunity to do
  26043. // any necessary setup in a predictable way. This predictability
  26044. // is why the Promise constructor synchronously invokes its
  26045. // executor callback, and why async functions synchronously
  26046. // execute code before the first await. Since we implement simple
  26047. // async functions in terms of async generators, it is especially
  26048. // important to get this right, even though it requires care.
  26049. previousPromise ? previousPromise.then(
  26050. callInvokeWithMethodAndArg,
  26051. // Avoid propagating failures to Promises returned by later
  26052. // invocations of the iterator.
  26053. callInvokeWithMethodAndArg
  26054. ) : callInvokeWithMethodAndArg();
  26055. }
  26056. // Define the unified helper method that is used to implement .next,
  26057. // .throw, and .return (see defineIteratorMethods).
  26058. this._invoke = enqueue;
  26059. }
  26060. defineIteratorMethods(AsyncIterator.prototype);
  26061. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  26062. return this;
  26063. };
  26064. exports.AsyncIterator = AsyncIterator;
  26065. // Note that simple async functions are implemented on top of
  26066. // AsyncIterator objects; they just return a Promise for the value of
  26067. // the final result produced by the iterator.
  26068. exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
  26069. if (PromiseImpl === void 0) PromiseImpl = Promise;
  26070. var iter = new AsyncIterator(
  26071. wrap(innerFn, outerFn, self, tryLocsList),
  26072. PromiseImpl
  26073. );
  26074. return exports.isGeneratorFunction(outerFn)
  26075. ? iter // If outerFn is a generator, return the full iterator.
  26076. : iter.next().then(function(result) {
  26077. return result.done ? result.value : iter.next();
  26078. });
  26079. };
  26080. function makeInvokeMethod(innerFn, self, context) {
  26081. var state = GenStateSuspendedStart;
  26082. return function invoke(method, arg) {
  26083. if (state === GenStateExecuting) {
  26084. throw new Error("Generator is already running");
  26085. }
  26086. if (state === GenStateCompleted) {
  26087. if (method === "throw") {
  26088. throw arg;
  26089. }
  26090. // Be forgiving, per 25.3.3.3.3 of the spec:
  26091. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  26092. return doneResult();
  26093. }
  26094. context.method = method;
  26095. context.arg = arg;
  26096. while (true) {
  26097. var delegate = context.delegate;
  26098. if (delegate) {
  26099. var delegateResult = maybeInvokeDelegate(delegate, context);
  26100. if (delegateResult) {
  26101. if (delegateResult === ContinueSentinel) continue;
  26102. return delegateResult;
  26103. }
  26104. }
  26105. if (context.method === "next") {
  26106. // Setting context._sent for legacy support of Babel's
  26107. // function.sent implementation.
  26108. context.sent = context._sent = context.arg;
  26109. } else if (context.method === "throw") {
  26110. if (state === GenStateSuspendedStart) {
  26111. state = GenStateCompleted;
  26112. throw context.arg;
  26113. }
  26114. context.dispatchException(context.arg);
  26115. } else if (context.method === "return") {
  26116. context.abrupt("return", context.arg);
  26117. }
  26118. state = GenStateExecuting;
  26119. var record = tryCatch(innerFn, self, context);
  26120. if (record.type === "normal") {
  26121. // If an exception is thrown from innerFn, we leave state ===
  26122. // GenStateExecuting and loop back for another invocation.
  26123. state = context.done
  26124. ? GenStateCompleted
  26125. : GenStateSuspendedYield;
  26126. if (record.arg === ContinueSentinel) {
  26127. continue;
  26128. }
  26129. return {
  26130. value: record.arg,
  26131. done: context.done
  26132. };
  26133. } else if (record.type === "throw") {
  26134. state = GenStateCompleted;
  26135. // Dispatch the exception by looping back around to the
  26136. // context.dispatchException(context.arg) call above.
  26137. context.method = "throw";
  26138. context.arg = record.arg;
  26139. }
  26140. }
  26141. };
  26142. }
  26143. // Call delegate.iterator[context.method](context.arg) and handle the
  26144. // result, either by returning a { value, done } result from the
  26145. // delegate iterator, or by modifying context.method and context.arg,
  26146. // setting context.delegate to null, and returning the ContinueSentinel.
  26147. function maybeInvokeDelegate(delegate, context) {
  26148. var method = delegate.iterator[context.method];
  26149. if (method === undefined) {
  26150. // A .throw or .return when the delegate iterator has no .throw
  26151. // method always terminates the yield* loop.
  26152. context.delegate = null;
  26153. if (context.method === "throw") {
  26154. // Note: ["return"] must be used for ES3 parsing compatibility.
  26155. if (delegate.iterator["return"]) {
  26156. // If the delegate iterator has a return method, give it a
  26157. // chance to clean up.
  26158. context.method = "return";
  26159. context.arg = undefined;
  26160. maybeInvokeDelegate(delegate, context);
  26161. if (context.method === "throw") {
  26162. // If maybeInvokeDelegate(context) changed context.method from
  26163. // "return" to "throw", let that override the TypeError below.
  26164. return ContinueSentinel;
  26165. }
  26166. }
  26167. context.method = "throw";
  26168. context.arg = new TypeError(
  26169. "The iterator does not provide a 'throw' method");
  26170. }
  26171. return ContinueSentinel;
  26172. }
  26173. var record = tryCatch(method, delegate.iterator, context.arg);
  26174. if (record.type === "throw") {
  26175. context.method = "throw";
  26176. context.arg = record.arg;
  26177. context.delegate = null;
  26178. return ContinueSentinel;
  26179. }
  26180. var info = record.arg;
  26181. if (! info) {
  26182. context.method = "throw";
  26183. context.arg = new TypeError("iterator result is not an object");
  26184. context.delegate = null;
  26185. return ContinueSentinel;
  26186. }
  26187. if (info.done) {
  26188. // Assign the result of the finished delegate to the temporary
  26189. // variable specified by delegate.resultName (see delegateYield).
  26190. context[delegate.resultName] = info.value;
  26191. // Resume execution at the desired location (see delegateYield).
  26192. context.next = delegate.nextLoc;
  26193. // If context.method was "throw" but the delegate handled the
  26194. // exception, let the outer generator proceed normally. If
  26195. // context.method was "next", forget context.arg since it has been
  26196. // "consumed" by the delegate iterator. If context.method was
  26197. // "return", allow the original .return call to continue in the
  26198. // outer generator.
  26199. if (context.method !== "return") {
  26200. context.method = "next";
  26201. context.arg = undefined;
  26202. }
  26203. } else {
  26204. // Re-yield the result returned by the delegate method.
  26205. return info;
  26206. }
  26207. // The delegate iterator is finished, so forget it and continue with
  26208. // the outer generator.
  26209. context.delegate = null;
  26210. return ContinueSentinel;
  26211. }
  26212. // Define Generator.prototype.{next,throw,return} in terms of the
  26213. // unified ._invoke helper method.
  26214. defineIteratorMethods(Gp);
  26215. Gp[toStringTagSymbol] = "Generator";
  26216. // A Generator should always return itself as the iterator object when the
  26217. // @@iterator function is called on it. Some browsers' implementations of the
  26218. // iterator prototype chain incorrectly implement this, causing the Generator
  26219. // object to not be returned from this call. This ensures that doesn't happen.
  26220. // See https://github.com/facebook/regenerator/issues/274 for more details.
  26221. Gp[iteratorSymbol] = function() {
  26222. return this;
  26223. };
  26224. Gp.toString = function() {
  26225. return "[object Generator]";
  26226. };
  26227. function pushTryEntry(locs) {
  26228. var entry = { tryLoc: locs[0] };
  26229. if (1 in locs) {
  26230. entry.catchLoc = locs[1];
  26231. }
  26232. if (2 in locs) {
  26233. entry.finallyLoc = locs[2];
  26234. entry.afterLoc = locs[3];
  26235. }
  26236. this.tryEntries.push(entry);
  26237. }
  26238. function resetTryEntry(entry) {
  26239. var record = entry.completion || {};
  26240. record.type = "normal";
  26241. delete record.arg;
  26242. entry.completion = record;
  26243. }
  26244. function Context(tryLocsList) {
  26245. // The root entry object (effectively a try statement without a catch
  26246. // or a finally block) gives us a place to store values thrown from
  26247. // locations where there is no enclosing try statement.
  26248. this.tryEntries = [{ tryLoc: "root" }];
  26249. tryLocsList.forEach(pushTryEntry, this);
  26250. this.reset(true);
  26251. }
  26252. exports.keys = function(object) {
  26253. var keys = [];
  26254. for (var key in object) {
  26255. keys.push(key);
  26256. }
  26257. keys.reverse();
  26258. // Rather than returning an object with a next method, we keep
  26259. // things simple and return the next function itself.
  26260. return function next() {
  26261. while (keys.length) {
  26262. var key = keys.pop();
  26263. if (key in object) {
  26264. next.value = key;
  26265. next.done = false;
  26266. return next;
  26267. }
  26268. }
  26269. // To avoid creating an additional object, we just hang the .value
  26270. // and .done properties off the next function object itself. This
  26271. // also ensures that the minifier will not anonymize the function.
  26272. next.done = true;
  26273. return next;
  26274. };
  26275. };
  26276. function values(iterable) {
  26277. if (iterable) {
  26278. var iteratorMethod = iterable[iteratorSymbol];
  26279. if (iteratorMethod) {
  26280. return iteratorMethod.call(iterable);
  26281. }
  26282. if (typeof iterable.next === "function") {
  26283. return iterable;
  26284. }
  26285. if (!isNaN(iterable.length)) {
  26286. var i = -1, next = function next() {
  26287. while (++i < iterable.length) {
  26288. if (hasOwn.call(iterable, i)) {
  26289. next.value = iterable[i];
  26290. next.done = false;
  26291. return next;
  26292. }
  26293. }
  26294. next.value = undefined;
  26295. next.done = true;
  26296. return next;
  26297. };
  26298. return next.next = next;
  26299. }
  26300. }
  26301. // Return an iterator with no values.
  26302. return { next: doneResult };
  26303. }
  26304. exports.values = values;
  26305. function doneResult() {
  26306. return { value: undefined, done: true };
  26307. }
  26308. Context.prototype = {
  26309. constructor: Context,
  26310. reset: function(skipTempReset) {
  26311. this.prev = 0;
  26312. this.next = 0;
  26313. // Resetting context._sent for legacy support of Babel's
  26314. // function.sent implementation.
  26315. this.sent = this._sent = undefined;
  26316. this.done = false;
  26317. this.delegate = null;
  26318. this.method = "next";
  26319. this.arg = undefined;
  26320. this.tryEntries.forEach(resetTryEntry);
  26321. if (!skipTempReset) {
  26322. for (var name in this) {
  26323. // Not sure about the optimal order of these conditions:
  26324. if (name.charAt(0) === "t" &&
  26325. hasOwn.call(this, name) &&
  26326. !isNaN(+name.slice(1))) {
  26327. this[name] = undefined;
  26328. }
  26329. }
  26330. }
  26331. },
  26332. stop: function() {
  26333. this.done = true;
  26334. var rootEntry = this.tryEntries[0];
  26335. var rootRecord = rootEntry.completion;
  26336. if (rootRecord.type === "throw") {
  26337. throw rootRecord.arg;
  26338. }
  26339. return this.rval;
  26340. },
  26341. dispatchException: function(exception) {
  26342. if (this.done) {
  26343. throw exception;
  26344. }
  26345. var context = this;
  26346. function handle(loc, caught) {
  26347. record.type = "throw";
  26348. record.arg = exception;
  26349. context.next = loc;
  26350. if (caught) {
  26351. // If the dispatched exception was caught by a catch block,
  26352. // then let that catch block handle the exception normally.
  26353. context.method = "next";
  26354. context.arg = undefined;
  26355. }
  26356. return !! caught;
  26357. }
  26358. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  26359. var entry = this.tryEntries[i];
  26360. var record = entry.completion;
  26361. if (entry.tryLoc === "root") {
  26362. // Exception thrown outside of any try block that could handle
  26363. // it, so set the completion value of the entire function to
  26364. // throw the exception.
  26365. return handle("end");
  26366. }
  26367. if (entry.tryLoc <= this.prev) {
  26368. var hasCatch = hasOwn.call(entry, "catchLoc");
  26369. var hasFinally = hasOwn.call(entry, "finallyLoc");
  26370. if (hasCatch && hasFinally) {
  26371. if (this.prev < entry.catchLoc) {
  26372. return handle(entry.catchLoc, true);
  26373. } else if (this.prev < entry.finallyLoc) {
  26374. return handle(entry.finallyLoc);
  26375. }
  26376. } else if (hasCatch) {
  26377. if (this.prev < entry.catchLoc) {
  26378. return handle(entry.catchLoc, true);
  26379. }
  26380. } else if (hasFinally) {
  26381. if (this.prev < entry.finallyLoc) {
  26382. return handle(entry.finallyLoc);
  26383. }
  26384. } else {
  26385. throw new Error("try statement without catch or finally");
  26386. }
  26387. }
  26388. }
  26389. },
  26390. abrupt: function(type, arg) {
  26391. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  26392. var entry = this.tryEntries[i];
  26393. if (entry.tryLoc <= this.prev &&
  26394. hasOwn.call(entry, "finallyLoc") &&
  26395. this.prev < entry.finallyLoc) {
  26396. var finallyEntry = entry;
  26397. break;
  26398. }
  26399. }
  26400. if (finallyEntry &&
  26401. (type === "break" ||
  26402. type === "continue") &&
  26403. finallyEntry.tryLoc <= arg &&
  26404. arg <= finallyEntry.finallyLoc) {
  26405. // Ignore the finally entry if control is not jumping to a
  26406. // location outside the try/catch block.
  26407. finallyEntry = null;
  26408. }
  26409. var record = finallyEntry ? finallyEntry.completion : {};
  26410. record.type = type;
  26411. record.arg = arg;
  26412. if (finallyEntry) {
  26413. this.method = "next";
  26414. this.next = finallyEntry.finallyLoc;
  26415. return ContinueSentinel;
  26416. }
  26417. return this.complete(record);
  26418. },
  26419. complete: function(record, afterLoc) {
  26420. if (record.type === "throw") {
  26421. throw record.arg;
  26422. }
  26423. if (record.type === "break" ||
  26424. record.type === "continue") {
  26425. this.next = record.arg;
  26426. } else if (record.type === "return") {
  26427. this.rval = this.arg = record.arg;
  26428. this.method = "return";
  26429. this.next = "end";
  26430. } else if (record.type === "normal" && afterLoc) {
  26431. this.next = afterLoc;
  26432. }
  26433. return ContinueSentinel;
  26434. },
  26435. finish: function(finallyLoc) {
  26436. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  26437. var entry = this.tryEntries[i];
  26438. if (entry.finallyLoc === finallyLoc) {
  26439. this.complete(entry.completion, entry.afterLoc);
  26440. resetTryEntry(entry);
  26441. return ContinueSentinel;
  26442. }
  26443. }
  26444. },
  26445. "catch": function(tryLoc) {
  26446. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  26447. var entry = this.tryEntries[i];
  26448. if (entry.tryLoc === tryLoc) {
  26449. var record = entry.completion;
  26450. if (record.type === "throw") {
  26451. var thrown = record.arg;
  26452. resetTryEntry(entry);
  26453. }
  26454. return thrown;
  26455. }
  26456. }
  26457. // The context.catch method must only be called with a location
  26458. // argument that corresponds to a known catch block.
  26459. throw new Error("illegal catch attempt");
  26460. },
  26461. delegateYield: function(iterable, resultName, nextLoc) {
  26462. this.delegate = {
  26463. iterator: values(iterable),
  26464. resultName: resultName,
  26465. nextLoc: nextLoc
  26466. };
  26467. if (this.method === "next") {
  26468. // Deliberately forget the last sent value so that we don't
  26469. // accidentally pass it on to the delegate.
  26470. this.arg = undefined;
  26471. }
  26472. return ContinueSentinel;
  26473. }
  26474. };
  26475. // Regardless of whether this script is executing as a CommonJS module
  26476. // or not, return the runtime object so that we can declare the variable
  26477. // regeneratorRuntime in the outer scope, which allows this module to be
  26478. // injected easily by `bin/regenerator --include-runtime script.js`.
  26479. return exports;
  26480. }(
  26481. // If this script is executing as a CommonJS module, use module.exports
  26482. // as the regeneratorRuntime namespace. Otherwise create a new empty
  26483. // object. Either way, the resulting object will be used to initialize
  26484. // the regeneratorRuntime variable at the top of this file.
  26485. true ? module.exports : undefined
  26486. ));
  26487. try {
  26488. regeneratorRuntime = runtime;
  26489. } catch (accidentalStrictMode) {
  26490. // This module should not be running in strict mode, so the above
  26491. // assignment should always work unless something is misconfigured. Just
  26492. // in case runtime.js accidentally runs in strict mode, we can escape
  26493. // strict mode using a global Function call. This could conceivably fail
  26494. // if a Content Security Policy forbids using Function, but in that case
  26495. // the proper solution is to fix the accidental strict mode problem. If
  26496. // you've misconfigured your bundler to force strict mode and applied a
  26497. // CSP to forbid Function, and you're not willing to fix either of those
  26498. // problems, please detail your unique predicament in a GitHub issue.
  26499. Function("r", "regeneratorRuntime = r")(runtime);
  26500. }
  26501. /***/ })
  26502. }]);
  26503. //# sourceMappingURL=vendors~main.dd0a03a355e98d9beb77.js.map